1pub mod buffer_store;
2pub mod connection_manager;
3pub mod debounced_delay;
4pub mod lsp_command;
5pub mod lsp_ext_command;
6pub mod lsp_store;
7mod prettier_support;
8pub mod project_settings;
9pub mod search;
10mod task_inventory;
11pub mod terminals;
12pub mod worktree_store;
13
14#[cfg(test)]
15mod project_tests;
16
17mod environment;
18pub mod search_history;
19mod yarn;
20
21use anyhow::{anyhow, Context as _, Result};
22use buffer_store::{BufferStore, BufferStoreEvent};
23use client::{
24 proto, Client, Collaborator, DevServerProjectId, PendingEntitySubscription, ProjectId,
25 TypedEnvelope, UserStore,
26};
27use clock::ReplicaId;
28use collections::{BTreeSet, HashMap, HashSet};
29use debounced_delay::DebouncedDelay;
30pub use environment::ProjectEnvironment;
31use futures::{
32 channel::mpsc::{self, UnboundedReceiver},
33 future::try_join_all,
34 stream::FuturesUnordered,
35 AsyncWriteExt, FutureExt, StreamExt,
36};
37
38use git::{blame::Blame, repository::GitRepository};
39use gpui::{
40 AnyModel, AppContext, AsyncAppContext, BorrowAppContext, Context, EventEmitter, Model,
41 ModelContext, SharedString, Task, WeakModel, WindowContext,
42};
43use itertools::Itertools;
44use language::{
45 language_settings::{
46 language_settings, FormatOnSave, Formatter, InlayHintKind, LanguageSettings,
47 SelectedFormatter,
48 },
49 proto::{
50 deserialize_anchor, serialize_anchor, serialize_line_ending, serialize_version,
51 split_operations,
52 },
53 Buffer, CachedLspAdapter, Capability, CodeLabel, ContextProvider, DiagnosticEntry, Diff,
54 Documentation, Event as BufferEvent, File as _, Language, LanguageRegistry, LanguageServerName,
55 PointUtf16, ToOffset, ToPointUtf16, Transaction, Unclipped,
56};
57use lsp::{CompletionContext, DocumentHighlightKind, LanguageServer, LanguageServerId};
58use lsp_command::*;
59use node_runtime::NodeRuntime;
60use parking_lot::{Mutex, RwLock};
61use paths::{local_tasks_file_relative_path, local_vscode_tasks_file_relative_path};
62use prettier_support::{DefaultPrettier, PrettierInstance};
63use project_settings::{LspSettings, ProjectSettings, SettingsObserver};
64use remote::SshSession;
65use rpc::{
66 proto::{AnyProtoClient, SSH_PROJECT_ID},
67 ErrorCode,
68};
69use search::{SearchInputKind, SearchQuery, SearchResult};
70use search_history::SearchHistory;
71use settings::{watch_config_file, Settings, SettingsLocation, SettingsStore};
72use smol::channel::Receiver;
73use snippet::Snippet;
74use snippet_provider::SnippetProvider;
75use std::{
76 borrow::Cow,
77 ops::Range,
78 path::{Component, Path, PathBuf},
79 str,
80 sync::Arc,
81 time::Duration,
82};
83use task::{
84 static_source::{StaticSource, TrackedFile},
85 HideStrategy, RevealStrategy, Shell, TaskContext, TaskTemplate, TaskVariables, VariableName,
86};
87use terminals::Terminals;
88use text::{Anchor, BufferId};
89use util::{defer, paths::compare_paths, ResultExt as _};
90use worktree::{CreatedEntry, Snapshot, Traversal};
91use worktree_store::{WorktreeStore, WorktreeStoreEvent};
92
93pub use fs::*;
94pub use language::Location;
95#[cfg(any(test, feature = "test-support"))]
96pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
97pub use task_inventory::{
98 BasicContextProvider, ContextProviderWithTasks, Inventory, TaskSourceKind,
99};
100pub use worktree::{
101 Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId, RepositoryEntry,
102 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
103 FS_WATCH_LATENCY,
104};
105
106pub use buffer_store::ProjectTransaction;
107pub use lsp_store::{
108 DiagnosticSummary, LanguageServerLogType, LanguageServerProgress, LanguageServerPromptRequest,
109 LanguageServerStatus, LanguageServerToQuery, LspStore, LspStoreEvent,
110 ProjectLspAdapterDelegate, SERVER_PROGRESS_THROTTLE_TIMEOUT,
111};
112
113const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
114const MAX_SEARCH_RESULT_FILES: usize = 5_000;
115const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
116
117pub trait Item {
118 fn try_open(
119 project: &Model<Project>,
120 path: &ProjectPath,
121 cx: &mut AppContext,
122 ) -> Option<Task<Result<Model<Self>>>>
123 where
124 Self: Sized;
125 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
126 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
127}
128
129#[derive(Clone)]
130pub enum OpenedBufferEvent {
131 Disconnected,
132 Ok(BufferId),
133 Err(BufferId, Arc<anyhow::Error>),
134}
135
136/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
137/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
138/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
139///
140/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
141pub struct Project {
142 active_entry: Option<ProjectEntryId>,
143 buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
144 languages: Arc<LanguageRegistry>,
145 client: Arc<client::Client>,
146 current_lsp_settings: HashMap<Arc<str>, LspSettings>,
147 join_project_response_message_id: u32,
148 user_store: Model<UserStore>,
149 fs: Arc<dyn Fs>,
150 ssh_session: Option<Arc<SshSession>>,
151 client_state: ProjectClientState,
152 collaborators: HashMap<proto::PeerId, Collaborator>,
153 client_subscriptions: Vec<client::Subscription>,
154 worktree_store: Model<WorktreeStore>,
155 buffer_store: Model<BufferStore>,
156 lsp_store: Model<LspStore>,
157 _subscriptions: Vec<gpui::Subscription>,
158 buffers_needing_diff: HashSet<WeakModel<Buffer>>,
159 git_diff_debouncer: DebouncedDelay<Self>,
160 remotely_created_buffers: Arc<Mutex<RemotelyCreatedBuffers>>,
161 terminals: Terminals,
162 node: Option<Arc<dyn NodeRuntime>>,
163 default_prettier: DefaultPrettier,
164 prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
165 prettier_instances: HashMap<PathBuf, PrettierInstance>,
166 tasks: Model<Inventory>,
167 hosted_project_id: Option<ProjectId>,
168 dev_server_project_id: Option<client::DevServerProjectId>,
169 search_history: SearchHistory,
170 search_included_history: SearchHistory,
171 search_excluded_history: SearchHistory,
172 snippets: Model<SnippetProvider>,
173 last_formatting_failure: Option<String>,
174 buffers_being_formatted: HashSet<BufferId>,
175 environment: Model<ProjectEnvironment>,
176 settings_observer: Model<SettingsObserver>,
177}
178
179#[derive(Default)]
180struct RemotelyCreatedBuffers {
181 buffers: Vec<Model<Buffer>>,
182 retain_count: usize,
183}
184
185struct RemotelyCreatedBufferGuard {
186 remote_buffers: std::sync::Weak<Mutex<RemotelyCreatedBuffers>>,
187}
188
189impl Drop for RemotelyCreatedBufferGuard {
190 fn drop(&mut self) {
191 if let Some(remote_buffers) = self.remote_buffers.upgrade() {
192 let mut remote_buffers = remote_buffers.lock();
193 assert!(
194 remote_buffers.retain_count > 0,
195 "RemotelyCreatedBufferGuard dropped too many times"
196 );
197 remote_buffers.retain_count -= 1;
198 if remote_buffers.retain_count == 0 {
199 remote_buffers.buffers.clear();
200 }
201 }
202 }
203}
204/// Message ordered with respect to buffer operations
205#[derive(Debug)]
206enum BufferOrderedMessage {
207 Operation {
208 buffer_id: BufferId,
209 operation: proto::Operation,
210 },
211 LanguageServerUpdate {
212 language_server_id: LanguageServerId,
213 message: proto::update_language_server::Variant,
214 },
215 Resync,
216}
217
218#[derive(Debug)]
219enum ProjectClientState {
220 Local,
221 Shared {
222 remote_id: u64,
223 },
224 Remote {
225 sharing_has_stopped: bool,
226 capability: Capability,
227 remote_id: u64,
228 replica_id: ReplicaId,
229 in_room: bool,
230 },
231}
232
233#[derive(Clone, Debug, PartialEq)]
234pub enum Event {
235 LanguageServerAdded(LanguageServerId),
236 LanguageServerRemoved(LanguageServerId),
237 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
238 Notification(String),
239 LanguageServerPrompt(LanguageServerPromptRequest),
240 LanguageNotFound(Model<Buffer>),
241 ActiveEntryChanged(Option<ProjectEntryId>),
242 ActivateProjectPanel,
243 WorktreeAdded,
244 WorktreeOrderChanged,
245 WorktreeRemoved(WorktreeId),
246 WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
247 WorktreeUpdatedGitRepositories,
248 DiskBasedDiagnosticsStarted {
249 language_server_id: LanguageServerId,
250 },
251 DiskBasedDiagnosticsFinished {
252 language_server_id: LanguageServerId,
253 },
254 DiagnosticsUpdated {
255 path: ProjectPath,
256 language_server_id: LanguageServerId,
257 },
258 RemoteIdChanged(Option<u64>),
259 DisconnectedFromHost,
260 Closed,
261 DeletedEntry(ProjectEntryId),
262 CollaboratorUpdated {
263 old_peer_id: proto::PeerId,
264 new_peer_id: proto::PeerId,
265 },
266 CollaboratorJoined(proto::PeerId),
267 CollaboratorLeft(proto::PeerId),
268 HostReshared,
269 Reshared,
270 Rejoined,
271 RefreshInlayHints,
272 RevealInProjectPanel(ProjectEntryId),
273 SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
274}
275
276#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
277pub struct ProjectPath {
278 pub worktree_id: WorktreeId,
279 pub path: Arc<Path>,
280}
281
282impl ProjectPath {
283 pub fn from_proto(p: proto::ProjectPath) -> Self {
284 Self {
285 worktree_id: WorktreeId::from_proto(p.worktree_id),
286 path: Arc::from(PathBuf::from(p.path)),
287 }
288 }
289
290 pub fn to_proto(&self) -> proto::ProjectPath {
291 proto::ProjectPath {
292 worktree_id: self.worktree_id.to_proto(),
293 path: self.path.to_string_lossy().to_string(),
294 }
295 }
296}
297
298#[derive(Debug, Clone, PartialEq, Eq)]
299pub struct InlayHint {
300 pub position: language::Anchor,
301 pub label: InlayHintLabel,
302 pub kind: Option<InlayHintKind>,
303 pub padding_left: bool,
304 pub padding_right: bool,
305 pub tooltip: Option<InlayHintTooltip>,
306 pub resolve_state: ResolveState,
307}
308
309/// The user's intent behind a given completion confirmation
310#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
311pub enum CompletionIntent {
312 /// The user intends to 'commit' this result, if possible
313 /// completion confirmations should run side effects
314 Complete,
315 /// The user intends to continue 'composing' this completion
316 /// completion confirmations should not run side effects and
317 /// let the user continue composing their action
318 Compose,
319}
320
321impl CompletionIntent {
322 pub fn is_complete(&self) -> bool {
323 self == &Self::Complete
324 }
325
326 pub fn is_compose(&self) -> bool {
327 self == &Self::Compose
328 }
329}
330
331/// A completion provided by a language server
332#[derive(Clone)]
333pub struct Completion {
334 /// The range of the buffer that will be replaced.
335 pub old_range: Range<Anchor>,
336 /// The new text that will be inserted.
337 pub new_text: String,
338 /// A label for this completion that is shown in the menu.
339 pub label: CodeLabel,
340 /// The id of the language server that produced this completion.
341 pub server_id: LanguageServerId,
342 /// The documentation for this completion.
343 pub documentation: Option<Documentation>,
344 /// The raw completion provided by the language server.
345 pub lsp_completion: lsp::CompletionItem,
346 /// An optional callback to invoke when this completion is confirmed.
347 /// Returns, whether new completions should be retriggered after the current one.
348 /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
349 /// if no confirmation is provided or `false` is returned, the completion will be committed.
350 pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut WindowContext) -> bool>>,
351}
352
353impl std::fmt::Debug for Completion {
354 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
355 f.debug_struct("Completion")
356 .field("old_range", &self.old_range)
357 .field("new_text", &self.new_text)
358 .field("label", &self.label)
359 .field("server_id", &self.server_id)
360 .field("documentation", &self.documentation)
361 .field("lsp_completion", &self.lsp_completion)
362 .finish()
363 }
364}
365
366/// A completion provided by a language server
367#[derive(Clone, Debug)]
368pub(crate) struct CoreCompletion {
369 old_range: Range<Anchor>,
370 new_text: String,
371 server_id: LanguageServerId,
372 lsp_completion: lsp::CompletionItem,
373}
374
375/// A code action provided by a language server.
376#[derive(Clone, Debug)]
377pub struct CodeAction {
378 /// The id of the language server that produced this code action.
379 pub server_id: LanguageServerId,
380 /// The range of the buffer where this code action is applicable.
381 pub range: Range<Anchor>,
382 /// The raw code action provided by the language server.
383 pub lsp_action: lsp::CodeAction,
384}
385
386#[derive(Debug, Clone, PartialEq, Eq)]
387pub enum ResolveState {
388 Resolved,
389 CanResolve(LanguageServerId, Option<lsp::LSPAny>),
390 Resolving,
391}
392
393impl InlayHint {
394 pub fn text(&self) -> String {
395 match &self.label {
396 InlayHintLabel::String(s) => s.to_owned(),
397 InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
398 }
399 }
400}
401
402#[derive(Debug, Clone, PartialEq, Eq)]
403pub enum InlayHintLabel {
404 String(String),
405 LabelParts(Vec<InlayHintLabelPart>),
406}
407
408#[derive(Debug, Clone, PartialEq, Eq)]
409pub struct InlayHintLabelPart {
410 pub value: String,
411 pub tooltip: Option<InlayHintLabelPartTooltip>,
412 pub location: Option<(LanguageServerId, lsp::Location)>,
413}
414
415#[derive(Debug, Clone, PartialEq, Eq)]
416pub enum InlayHintTooltip {
417 String(String),
418 MarkupContent(MarkupContent),
419}
420
421#[derive(Debug, Clone, PartialEq, Eq)]
422pub enum InlayHintLabelPartTooltip {
423 String(String),
424 MarkupContent(MarkupContent),
425}
426
427#[derive(Debug, Clone, PartialEq, Eq)]
428pub struct MarkupContent {
429 pub kind: HoverBlockKind,
430 pub value: String,
431}
432
433#[derive(Debug, Clone)]
434pub struct LocationLink {
435 pub origin: Option<Location>,
436 pub target: Location,
437}
438
439#[derive(Debug)]
440pub struct DocumentHighlight {
441 pub range: Range<language::Anchor>,
442 pub kind: DocumentHighlightKind,
443}
444
445#[derive(Clone, Debug)]
446pub struct Symbol {
447 pub language_server_name: LanguageServerName,
448 pub source_worktree_id: WorktreeId,
449 pub path: ProjectPath,
450 pub label: CodeLabel,
451 pub name: String,
452 pub kind: lsp::SymbolKind,
453 pub range: Range<Unclipped<PointUtf16>>,
454 pub signature: [u8; 32],
455}
456
457#[derive(Clone, Debug, PartialEq)]
458pub struct HoverBlock {
459 pub text: String,
460 pub kind: HoverBlockKind,
461}
462
463#[derive(Clone, Debug, PartialEq, Eq)]
464pub enum HoverBlockKind {
465 PlainText,
466 Markdown,
467 Code { language: String },
468}
469
470#[derive(Debug, Clone)]
471pub struct Hover {
472 pub contents: Vec<HoverBlock>,
473 pub range: Option<Range<language::Anchor>>,
474 pub language: Option<Arc<Language>>,
475}
476
477impl Hover {
478 pub fn is_empty(&self) -> bool {
479 self.contents.iter().all(|block| block.text.is_empty())
480 }
481}
482
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484pub enum FormatTrigger {
485 Save,
486 Manual,
487}
488
489// Currently, formatting operations are represented differently depending on
490// whether they come from a language server or an external command.
491#[derive(Debug)]
492enum FormatOperation {
493 Lsp(Vec<(Range<Anchor>, String)>),
494 External(Diff),
495 Prettier(Diff),
496}
497
498impl FormatTrigger {
499 fn from_proto(value: i32) -> FormatTrigger {
500 match value {
501 0 => FormatTrigger::Save,
502 1 => FormatTrigger::Manual,
503 _ => FormatTrigger::Save,
504 }
505 }
506}
507
508enum EntitySubscription {
509 Project(PendingEntitySubscription<Project>),
510 BufferStore(PendingEntitySubscription<BufferStore>),
511 WorktreeStore(PendingEntitySubscription<WorktreeStore>),
512 LspStore(PendingEntitySubscription<LspStore>),
513 SettingsObserver(PendingEntitySubscription<SettingsObserver>),
514}
515
516#[derive(Clone)]
517pub enum DirectoryLister {
518 Project(Model<Project>),
519 Local(Arc<dyn Fs>),
520}
521
522impl DirectoryLister {
523 pub fn is_local(&self, cx: &AppContext) -> bool {
524 match self {
525 DirectoryLister::Local(_) => true,
526 DirectoryLister::Project(project) => project.read(cx).is_local_or_ssh(),
527 }
528 }
529
530 pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &AppContext) -> Cow<'a, str> {
531 if self.is_local(cx) {
532 shellexpand::tilde(path)
533 } else {
534 Cow::from(path)
535 }
536 }
537
538 pub fn default_query(&self, cx: &mut AppContext) -> String {
539 if let DirectoryLister::Project(project) = self {
540 if let Some(worktree) = project.read(cx).visible_worktrees(cx).next() {
541 return worktree.read(cx).abs_path().to_string_lossy().to_string();
542 }
543 };
544 "~/".to_string()
545 }
546
547 pub fn list_directory(&self, path: String, cx: &mut AppContext) -> Task<Result<Vec<PathBuf>>> {
548 match self {
549 DirectoryLister::Project(project) => {
550 project.update(cx, |project, cx| project.list_directory(path, cx))
551 }
552 DirectoryLister::Local(fs) => {
553 let fs = fs.clone();
554 cx.background_executor().spawn(async move {
555 let mut results = vec![];
556 let expanded = shellexpand::tilde(&path);
557 let query = Path::new(expanded.as_ref());
558 let mut response = fs.read_dir(query).await?;
559 while let Some(path) = response.next().await {
560 if let Some(file_name) = path?.file_name() {
561 results.push(PathBuf::from(file_name.to_os_string()));
562 }
563 }
564 Ok(results)
565 })
566 }
567 }
568 }
569}
570
571#[cfg(any(test, feature = "test-support"))]
572pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
573 trigger_kind: lsp::CompletionTriggerKind::INVOKED,
574 trigger_character: None,
575};
576
577impl Project {
578 pub fn init_settings(cx: &mut AppContext) {
579 WorktreeSettings::register(cx);
580 ProjectSettings::register(cx);
581 }
582
583 pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
584 connection_manager::init(client.clone(), cx);
585 Self::init_settings(cx);
586
587 let client: AnyProtoClient = client.clone().into();
588 client.add_model_message_handler(Self::handle_add_collaborator);
589 client.add_model_message_handler(Self::handle_update_project_collaborator);
590 client.add_model_message_handler(Self::handle_remove_collaborator);
591 client.add_model_message_handler(Self::handle_update_project);
592 client.add_model_message_handler(Self::handle_unshare_project);
593 client.add_model_request_handler(Self::handle_update_buffer);
594 client.add_model_message_handler(Self::handle_update_worktree);
595 client.add_model_request_handler(Self::handle_reload_buffers);
596 client.add_model_request_handler(Self::handle_synchronize_buffers);
597 client.add_model_request_handler(Self::handle_format_buffers);
598 client.add_model_request_handler(Self::handle_search_project);
599 client.add_model_request_handler(Self::handle_search_candidate_buffers);
600 client.add_model_request_handler(Self::handle_open_buffer_by_id);
601 client.add_model_request_handler(Self::handle_open_buffer_by_path);
602 client.add_model_request_handler(Self::handle_open_new_buffer);
603 client.add_model_request_handler(Self::handle_task_context_for_location);
604 client.add_model_request_handler(Self::handle_task_templates);
605 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
606
607 WorktreeStore::init(&client);
608 BufferStore::init(&client);
609 LspStore::init(&client);
610 SettingsObserver::init(&client);
611 }
612
613 pub fn local(
614 client: Arc<Client>,
615 node: Arc<dyn NodeRuntime>,
616 user_store: Model<UserStore>,
617 languages: Arc<LanguageRegistry>,
618 fs: Arc<dyn Fs>,
619 env: Option<HashMap<String, String>>,
620 cx: &mut AppContext,
621 ) -> Model<Self> {
622 cx.new_model(|cx: &mut ModelContext<Self>| {
623 let (tx, rx) = mpsc::unbounded();
624 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
625 .detach();
626 let tasks = Inventory::new(cx);
627 let global_snippets_dir = paths::config_dir().join("snippets");
628 let snippets =
629 SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
630
631 let worktree_store = cx.new_model(|_| WorktreeStore::new(false, fs.clone()));
632 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
633 .detach();
634
635 let buffer_store =
636 cx.new_model(|cx| BufferStore::new(worktree_store.clone(), None, cx));
637 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
638 .detach();
639
640 let settings_observer = cx.new_model(|cx| {
641 SettingsObserver::new_local(fs.clone(), worktree_store.clone(), cx)
642 });
643
644 let environment = ProjectEnvironment::new(&worktree_store, env, cx);
645 let lsp_store = cx.new_model(|cx| {
646 LspStore::new(
647 buffer_store.clone(),
648 worktree_store.clone(),
649 Some(environment.clone()),
650 languages.clone(),
651 Some(client.http_client()),
652 fs.clone(),
653 None,
654 None,
655 None,
656 cx,
657 )
658 });
659 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
660
661 Self {
662 buffer_ordered_messages_tx: tx,
663 collaborators: Default::default(),
664 worktree_store,
665 buffer_store,
666 lsp_store,
667 current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
668 join_project_response_message_id: 0,
669 client_state: ProjectClientState::Local,
670 client_subscriptions: Vec::new(),
671 _subscriptions: vec![
672 cx.observe_global::<SettingsStore>(Self::on_settings_changed),
673 cx.on_release(Self::release),
674 ],
675 active_entry: None,
676 snippets,
677 languages,
678 client,
679 user_store,
680 settings_observer,
681 fs,
682 ssh_session: None,
683 buffers_needing_diff: Default::default(),
684 git_diff_debouncer: DebouncedDelay::new(),
685 terminals: Terminals {
686 local_handles: Vec::new(),
687 },
688 node: Some(node),
689 default_prettier: DefaultPrettier::default(),
690 prettiers_per_worktree: HashMap::default(),
691 prettier_instances: HashMap::default(),
692 tasks,
693 hosted_project_id: None,
694 dev_server_project_id: None,
695 search_history: Self::new_search_history(),
696 environment,
697 remotely_created_buffers: Default::default(),
698 last_formatting_failure: None,
699 buffers_being_formatted: Default::default(),
700 search_included_history: Self::new_search_history(),
701 search_excluded_history: Self::new_search_history(),
702 }
703 })
704 }
705
706 pub fn ssh(
707 ssh: Arc<SshSession>,
708 client: Arc<Client>,
709 node: Arc<dyn NodeRuntime>,
710 user_store: Model<UserStore>,
711 languages: Arc<LanguageRegistry>,
712 fs: Arc<dyn Fs>,
713 cx: &mut AppContext,
714 ) -> Model<Self> {
715 let this = Self::local(client, node, user_store, languages, fs, None, cx);
716 this.update(cx, |this, cx| {
717 let client: AnyProtoClient = ssh.clone().into();
718
719 this.worktree_store.update(cx, |store, _cx| {
720 store.set_upstream_client(client.clone());
721 });
722 this.settings_observer = cx.new_model(|cx| {
723 SettingsObserver::new_ssh(ssh.clone().into(), this.worktree_store.clone(), cx)
724 });
725
726 ssh.subscribe_to_entity(SSH_PROJECT_ID, &cx.handle());
727 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.buffer_store);
728 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.worktree_store);
729 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.lsp_store);
730 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.settings_observer);
731 client.add_model_message_handler(Self::handle_update_worktree);
732 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
733 client.add_model_message_handler(BufferStore::handle_update_buffer_file);
734 client.add_model_message_handler(BufferStore::handle_update_diff_base);
735 LspStore::init(&client);
736 SettingsObserver::init(&client);
737
738 this.ssh_session = Some(ssh);
739 });
740 this
741 }
742
743 pub async fn remote(
744 remote_id: u64,
745 client: Arc<Client>,
746 user_store: Model<UserStore>,
747 languages: Arc<LanguageRegistry>,
748 fs: Arc<dyn Fs>,
749 cx: AsyncAppContext,
750 ) -> Result<Model<Self>> {
751 let project =
752 Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
753 cx.update(|cx| {
754 connection_manager::Manager::global(cx).update(cx, |manager, cx| {
755 manager.maintain_project_connection(&project, cx)
756 })
757 })?;
758 Ok(project)
759 }
760
761 pub async fn in_room(
762 remote_id: u64,
763 client: Arc<Client>,
764 user_store: Model<UserStore>,
765 languages: Arc<LanguageRegistry>,
766 fs: Arc<dyn Fs>,
767 cx: AsyncAppContext,
768 ) -> Result<Model<Self>> {
769 client.authenticate_and_connect(true, &cx).await?;
770
771 let subscriptions = [
772 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
773 EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
774 EntitySubscription::WorktreeStore(
775 client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
776 ),
777 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
778 EntitySubscription::SettingsObserver(
779 client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
780 ),
781 ];
782 let response = client
783 .request_envelope(proto::JoinProject {
784 project_id: remote_id,
785 })
786 .await?;
787 Self::from_join_project_response(
788 response,
789 subscriptions,
790 client,
791 user_store,
792 languages,
793 fs,
794 cx,
795 )
796 .await
797 }
798
799 async fn from_join_project_response(
800 response: TypedEnvelope<proto::JoinProjectResponse>,
801 subscriptions: [EntitySubscription; 5],
802 client: Arc<Client>,
803 user_store: Model<UserStore>,
804 languages: Arc<LanguageRegistry>,
805 fs: Arc<dyn Fs>,
806 mut cx: AsyncAppContext,
807 ) -> Result<Model<Self>> {
808 let remote_id = response.payload.project_id;
809 let role = response.payload.role();
810
811 let worktree_store = cx.new_model(|_| {
812 let mut store = WorktreeStore::new(true, fs.clone());
813 store.set_upstream_client(client.clone().into());
814 if let Some(dev_server_project_id) = response.payload.dev_server_project_id {
815 store.set_dev_server_project_id(DevServerProjectId(dev_server_project_id));
816 }
817 store
818 })?;
819 let buffer_store =
820 cx.new_model(|cx| BufferStore::new(worktree_store.clone(), Some(remote_id), cx))?;
821
822 let lsp_store = cx.new_model(|cx| {
823 let mut lsp_store = LspStore::new(
824 buffer_store.clone(),
825 worktree_store.clone(),
826 None,
827 languages.clone(),
828 Some(client.http_client()),
829 fs.clone(),
830 None,
831 Some(client.clone().into()),
832 Some(remote_id),
833 cx,
834 );
835 lsp_store.set_language_server_statuses_from_proto(response.payload.language_servers);
836 lsp_store
837 })?;
838
839 let settings_observer =
840 cx.new_model(|cx| SettingsObserver::new_remote(worktree_store.clone(), cx))?;
841
842 let this = cx.new_model(|cx| {
843 let replica_id = response.payload.replica_id as ReplicaId;
844 let tasks = Inventory::new(cx);
845 let global_snippets_dir = paths::config_dir().join("snippets");
846 let snippets =
847 SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
848
849 let mut worktrees = Vec::new();
850 for worktree in response.payload.worktrees {
851 let worktree =
852 Worktree::remote(remote_id, replica_id, worktree, client.clone().into(), cx);
853 worktrees.push(worktree);
854 }
855
856 let (tx, rx) = mpsc::unbounded();
857 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
858 .detach();
859
860 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
861 .detach();
862 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
863
864 let mut this = Self {
865 buffer_ordered_messages_tx: tx,
866 buffer_store: buffer_store.clone(),
867 worktree_store: worktree_store.clone(),
868 lsp_store: lsp_store.clone(),
869 current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
870 active_entry: None,
871 collaborators: Default::default(),
872 join_project_response_message_id: response.message_id,
873 languages,
874 user_store: user_store.clone(),
875 snippets,
876 fs,
877 ssh_session: None,
878 settings_observer: settings_observer.clone(),
879 client_subscriptions: Default::default(),
880 _subscriptions: vec![cx.on_release(Self::release)],
881 client: client.clone(),
882 client_state: ProjectClientState::Remote {
883 sharing_has_stopped: false,
884 capability: Capability::ReadWrite,
885 remote_id,
886 replica_id,
887 in_room: response.payload.dev_server_project_id.is_none(),
888 },
889 buffers_needing_diff: Default::default(),
890 git_diff_debouncer: DebouncedDelay::new(),
891 terminals: Terminals {
892 local_handles: Vec::new(),
893 },
894 node: None,
895 default_prettier: DefaultPrettier::default(),
896 prettiers_per_worktree: HashMap::default(),
897 prettier_instances: HashMap::default(),
898 tasks,
899 hosted_project_id: None,
900 dev_server_project_id: response
901 .payload
902 .dev_server_project_id
903 .map(DevServerProjectId),
904 search_history: Self::new_search_history(),
905 search_included_history: Self::new_search_history(),
906 search_excluded_history: Self::new_search_history(),
907 environment: ProjectEnvironment::new(&worktree_store, None, cx),
908 remotely_created_buffers: Arc::new(Mutex::new(RemotelyCreatedBuffers::default())),
909 last_formatting_failure: None,
910 buffers_being_formatted: Default::default(),
911 };
912 this.set_role(role, cx);
913 for worktree in worktrees {
914 this.add_worktree(&worktree, cx);
915 }
916 this
917 })?;
918
919 let subscriptions = subscriptions
920 .into_iter()
921 .map(|s| match s {
922 EntitySubscription::BufferStore(subscription) => {
923 subscription.set_model(&buffer_store, &mut cx)
924 }
925 EntitySubscription::WorktreeStore(subscription) => {
926 subscription.set_model(&worktree_store, &mut cx)
927 }
928 EntitySubscription::SettingsObserver(subscription) => {
929 subscription.set_model(&settings_observer, &mut cx)
930 }
931 EntitySubscription::Project(subscription) => subscription.set_model(&this, &mut cx),
932 EntitySubscription::LspStore(subscription) => {
933 subscription.set_model(&lsp_store, &mut cx)
934 }
935 })
936 .collect::<Vec<_>>();
937
938 let user_ids = response
939 .payload
940 .collaborators
941 .iter()
942 .map(|peer| peer.user_id)
943 .collect();
944 user_store
945 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
946 .await?;
947
948 this.update(&mut cx, |this, cx| {
949 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
950 this.client_subscriptions.extend(subscriptions);
951 anyhow::Ok(())
952 })??;
953
954 Ok(this)
955 }
956
957 pub async fn hosted(
958 remote_id: ProjectId,
959 user_store: Model<UserStore>,
960 client: Arc<Client>,
961 languages: Arc<LanguageRegistry>,
962 fs: Arc<dyn Fs>,
963 cx: AsyncAppContext,
964 ) -> Result<Model<Self>> {
965 client.authenticate_and_connect(true, &cx).await?;
966
967 let subscriptions = [
968 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id.0)?),
969 EntitySubscription::BufferStore(
970 client.subscribe_to_entity::<BufferStore>(remote_id.0)?,
971 ),
972 EntitySubscription::WorktreeStore(
973 client.subscribe_to_entity::<WorktreeStore>(remote_id.0)?,
974 ),
975 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id.0)?),
976 EntitySubscription::SettingsObserver(
977 client.subscribe_to_entity::<SettingsObserver>(remote_id.0)?,
978 ),
979 ];
980 let response = client
981 .request_envelope(proto::JoinHostedProject {
982 project_id: remote_id.0,
983 })
984 .await?;
985 Self::from_join_project_response(
986 response,
987 subscriptions,
988 client,
989 user_store,
990 languages,
991 fs,
992 cx,
993 )
994 .await
995 }
996
997 fn new_search_history() -> SearchHistory {
998 SearchHistory::new(
999 Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1000 search_history::QueryInsertionBehavior::AlwaysInsert,
1001 )
1002 }
1003
1004 fn release(&mut self, cx: &mut AppContext) {
1005 match &self.client_state {
1006 ProjectClientState::Local => {}
1007 ProjectClientState::Shared { .. } => {
1008 let _ = self.unshare_internal(cx);
1009 }
1010 ProjectClientState::Remote { remote_id, .. } => {
1011 let _ = self.client.send(proto::LeaveProject {
1012 project_id: *remote_id,
1013 });
1014 self.disconnected_from_host_internal(cx);
1015 }
1016 }
1017 }
1018
1019 #[cfg(any(test, feature = "test-support"))]
1020 pub async fn example(
1021 root_paths: impl IntoIterator<Item = &Path>,
1022 cx: &mut AsyncAppContext,
1023 ) -> Model<Project> {
1024 use clock::FakeSystemClock;
1025
1026 let fs = Arc::new(RealFs::default());
1027 let languages = LanguageRegistry::test(cx.background_executor().clone());
1028 let clock = Arc::new(FakeSystemClock::default());
1029 let http_client = http_client::FakeHttpClient::with_404_response();
1030 let client = cx
1031 .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1032 .unwrap();
1033 let user_store = cx
1034 .new_model(|cx| UserStore::new(client.clone(), cx))
1035 .unwrap();
1036 let project = cx
1037 .update(|cx| {
1038 Project::local(
1039 client,
1040 node_runtime::FakeNodeRuntime::new(),
1041 user_store,
1042 Arc::new(languages),
1043 fs,
1044 None,
1045 cx,
1046 )
1047 })
1048 .unwrap();
1049 for path in root_paths {
1050 let (tree, _) = project
1051 .update(cx, |project, cx| {
1052 project.find_or_create_worktree(path, true, cx)
1053 })
1054 .unwrap()
1055 .await
1056 .unwrap();
1057 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1058 .unwrap()
1059 .await;
1060 }
1061 project
1062 }
1063
1064 #[cfg(any(test, feature = "test-support"))]
1065 pub async fn test(
1066 fs: Arc<dyn Fs>,
1067 root_paths: impl IntoIterator<Item = &Path>,
1068 cx: &mut gpui::TestAppContext,
1069 ) -> Model<Project> {
1070 use clock::FakeSystemClock;
1071
1072 let languages = LanguageRegistry::test(cx.executor());
1073 let clock = Arc::new(FakeSystemClock::default());
1074 let http_client = http_client::FakeHttpClient::with_404_response();
1075 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1076 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
1077 let project = cx.update(|cx| {
1078 Project::local(
1079 client,
1080 node_runtime::FakeNodeRuntime::new(),
1081 user_store,
1082 Arc::new(languages),
1083 fs,
1084 None,
1085 cx,
1086 )
1087 });
1088 for path in root_paths {
1089 let (tree, _) = project
1090 .update(cx, |project, cx| {
1091 project.find_or_create_worktree(path, true, cx)
1092 })
1093 .await
1094 .unwrap();
1095
1096 project.update(cx, |project, cx| {
1097 let tree_id = tree.read(cx).id();
1098 project.environment.update(cx, |environment, _| {
1099 environment.set_cached(&[(tree_id, HashMap::default())])
1100 });
1101 });
1102
1103 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1104 .await;
1105 }
1106 project
1107 }
1108
1109 pub fn lsp_store(&self) -> Model<LspStore> {
1110 self.lsp_store.clone()
1111 }
1112
1113 pub fn worktree_store(&self) -> Model<WorktreeStore> {
1114 self.worktree_store.clone()
1115 }
1116
1117 fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
1118 let mut language_servers_to_start = Vec::new();
1119 let mut language_formatters_to_check = Vec::new();
1120 for buffer in self.buffer_store.read(cx).buffers() {
1121 let buffer = buffer.read(cx);
1122 let buffer_file = File::from_dyn(buffer.file());
1123 let buffer_language = buffer.language();
1124 let settings = language_settings(buffer_language, buffer.file(), cx);
1125 if let Some(language) = buffer_language {
1126 if settings.enable_language_server {
1127 if let Some(file) = buffer_file {
1128 language_servers_to_start
1129 .push((file.worktree.clone(), Arc::clone(language)));
1130 }
1131 }
1132 language_formatters_to_check
1133 .push((buffer_file.map(|f| f.worktree_id(cx)), settings.clone()));
1134 }
1135 }
1136
1137 let mut language_servers_to_stop = Vec::new();
1138 let mut language_servers_to_restart = Vec::new();
1139 let languages = self.languages.to_vec();
1140
1141 let new_lsp_settings = ProjectSettings::get_global(cx).lsp.clone();
1142 let current_lsp_settings = &self.current_lsp_settings;
1143 for (worktree_id, started_lsp_name) in self.lsp_store.read(cx).started_language_servers() {
1144 let language = languages.iter().find_map(|l| {
1145 let adapter = self
1146 .languages
1147 .lsp_adapters(l)
1148 .iter()
1149 .find(|adapter| adapter.name == started_lsp_name)?
1150 .clone();
1151 Some((l, adapter))
1152 });
1153 if let Some((language, adapter)) = language {
1154 let worktree = self.worktree_for_id(worktree_id, cx);
1155 let file = worktree.as_ref().and_then(|tree| {
1156 tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
1157 });
1158 if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
1159 language_servers_to_stop.push((worktree_id, started_lsp_name.clone()));
1160 } else if let Some(worktree) = worktree {
1161 let server_name = &adapter.name.0;
1162 match (
1163 current_lsp_settings.get(server_name),
1164 new_lsp_settings.get(server_name),
1165 ) {
1166 (None, None) => {}
1167 (Some(_), None) | (None, Some(_)) => {
1168 language_servers_to_restart.push((worktree, Arc::clone(language)));
1169 }
1170 (Some(current_lsp_settings), Some(new_lsp_settings)) => {
1171 if current_lsp_settings != new_lsp_settings {
1172 language_servers_to_restart.push((worktree, Arc::clone(language)));
1173 }
1174 }
1175 }
1176 }
1177 }
1178 }
1179 self.current_lsp_settings = new_lsp_settings;
1180
1181 // Stop all newly-disabled language servers.
1182 self.lsp_store.update(cx, |lsp_store, cx| {
1183 for (worktree_id, adapter_name) in language_servers_to_stop {
1184 lsp_store
1185 .stop_language_server(worktree_id, adapter_name, cx)
1186 .detach();
1187 }
1188 });
1189
1190 let mut prettier_plugins_by_worktree = HashMap::default();
1191 for (worktree, language_settings) in language_formatters_to_check {
1192 if let Some(plugins) =
1193 prettier_support::prettier_plugins_for_language(&language_settings)
1194 {
1195 prettier_plugins_by_worktree
1196 .entry(worktree)
1197 .or_insert_with(HashSet::default)
1198 .extend(plugins.iter().cloned());
1199 }
1200 }
1201 for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
1202 self.install_default_prettier(
1203 worktree,
1204 prettier_plugins.into_iter().map(Arc::from),
1205 cx,
1206 );
1207 }
1208
1209 // Start all the newly-enabled language servers.
1210 self.lsp_store.update(cx, |lsp_store, cx| {
1211 for (worktree, language) in language_servers_to_start {
1212 lsp_store.start_language_servers(&worktree, language, cx);
1213 }
1214
1215 // Restart all language servers with changed initialization options.
1216 for (worktree, language) in language_servers_to_restart {
1217 lsp_store.restart_language_servers(worktree, language, cx);
1218 }
1219 });
1220
1221 cx.notify();
1222 }
1223
1224 pub fn buffer_for_id(&self, remote_id: BufferId, cx: &AppContext) -> Option<Model<Buffer>> {
1225 self.buffer_store.read(cx).get(remote_id)
1226 }
1227
1228 pub fn languages(&self) -> &Arc<LanguageRegistry> {
1229 &self.languages
1230 }
1231
1232 pub fn client(&self) -> Arc<Client> {
1233 self.client.clone()
1234 }
1235
1236 pub fn user_store(&self) -> Model<UserStore> {
1237 self.user_store.clone()
1238 }
1239
1240 pub fn node_runtime(&self) -> Option<&Arc<dyn NodeRuntime>> {
1241 self.node.as_ref()
1242 }
1243
1244 pub fn opened_buffers(&self, cx: &AppContext) -> Vec<Model<Buffer>> {
1245 self.buffer_store.read(cx).buffers().collect()
1246 }
1247
1248 pub fn cli_environment(&self, cx: &AppContext) -> Option<HashMap<String, String>> {
1249 self.environment.read(cx).get_cli_environment()
1250 }
1251
1252 #[cfg(any(test, feature = "test-support"))]
1253 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
1254 self.buffer_store
1255 .read(cx)
1256 .get_by_path(&path.into(), cx)
1257 .is_some()
1258 }
1259
1260 pub fn fs(&self) -> &Arc<dyn Fs> {
1261 &self.fs
1262 }
1263
1264 pub fn remote_id(&self) -> Option<u64> {
1265 match self.client_state {
1266 ProjectClientState::Local => None,
1267 ProjectClientState::Shared { remote_id, .. }
1268 | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1269 }
1270 }
1271
1272 pub fn hosted_project_id(&self) -> Option<ProjectId> {
1273 self.hosted_project_id
1274 }
1275
1276 pub fn dev_server_project_id(&self) -> Option<DevServerProjectId> {
1277 self.dev_server_project_id
1278 }
1279
1280 pub fn supports_remote_terminal(&self, cx: &AppContext) -> bool {
1281 let Some(id) = self.dev_server_project_id else {
1282 return false;
1283 };
1284 let Some(server) = dev_server_projects::Store::global(cx)
1285 .read(cx)
1286 .dev_server_for_project(id)
1287 else {
1288 return false;
1289 };
1290 server.ssh_connection_string.is_some()
1291 }
1292
1293 pub fn ssh_connection_string(&self, cx: &ModelContext<Self>) -> Option<SharedString> {
1294 if self.is_local_or_ssh() {
1295 return None;
1296 }
1297
1298 let dev_server_id = self.dev_server_project_id()?;
1299 dev_server_projects::Store::global(cx)
1300 .read(cx)
1301 .dev_server_for_project(dev_server_id)?
1302 .ssh_connection_string
1303 .clone()
1304 }
1305
1306 pub fn replica_id(&self) -> ReplicaId {
1307 match self.client_state {
1308 ProjectClientState::Remote { replica_id, .. } => replica_id,
1309 _ => 0,
1310 }
1311 }
1312
1313 fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
1314 cx.notify();
1315
1316 let ProjectClientState::Shared { remote_id } = self.client_state else {
1317 return;
1318 };
1319 let project_id = remote_id;
1320
1321 let update_project = self.client.request(proto::UpdateProject {
1322 project_id,
1323 worktrees: self.worktree_metadata_protos(cx),
1324 });
1325 cx.spawn(|this, mut cx| async move {
1326 update_project.await?;
1327 this.update(&mut cx, |this, cx| {
1328 let client = this.client.clone();
1329 let worktrees = this.worktree_store.read(cx).worktrees().collect::<Vec<_>>();
1330
1331 for worktree in worktrees {
1332 worktree.update(cx, |worktree, cx| {
1333 let client = client.clone();
1334 worktree.observe_updates(project_id, cx, {
1335 move |update| client.request(update).map(|result| result.is_ok())
1336 });
1337
1338 this.lsp_store.update(cx, |lsp_store, _| {
1339 lsp_store.send_diagnostic_summaries(worktree)
1340 })
1341 })?;
1342 }
1343
1344 anyhow::Ok(())
1345 })
1346 })
1347 .detach_and_log_err(cx);
1348 }
1349
1350 pub fn task_inventory(&self) -> &Model<Inventory> {
1351 &self.tasks
1352 }
1353
1354 pub fn snippets(&self) -> &Model<SnippetProvider> {
1355 &self.snippets
1356 }
1357
1358 pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1359 match kind {
1360 SearchInputKind::Query => &self.search_history,
1361 SearchInputKind::Include => &self.search_included_history,
1362 SearchInputKind::Exclude => &self.search_excluded_history,
1363 }
1364 }
1365
1366 pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1367 match kind {
1368 SearchInputKind::Query => &mut self.search_history,
1369 SearchInputKind::Include => &mut self.search_included_history,
1370 SearchInputKind::Exclude => &mut self.search_excluded_history,
1371 }
1372 }
1373
1374 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1375 &self.collaborators
1376 }
1377
1378 pub fn host(&self) -> Option<&Collaborator> {
1379 self.collaborators.values().find(|c| c.replica_id == 0)
1380 }
1381
1382 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut AppContext) {
1383 self.worktree_store.update(cx, |store, _| {
1384 store.set_worktrees_reordered(worktrees_reordered);
1385 });
1386 }
1387
1388 /// Collect all worktrees, including ones that don't appear in the project panel
1389 pub fn worktrees<'a>(
1390 &self,
1391 cx: &'a AppContext,
1392 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1393 self.worktree_store.read(cx).worktrees()
1394 }
1395
1396 /// Collect all user-visible worktrees, the ones that appear in the project panel.
1397 pub fn visible_worktrees<'a>(
1398 &'a self,
1399 cx: &'a AppContext,
1400 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1401 self.worktree_store.read(cx).visible_worktrees(cx)
1402 }
1403
1404 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1405 self.visible_worktrees(cx)
1406 .map(|tree| tree.read(cx).root_name())
1407 }
1408
1409 pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
1410 self.worktree_store.read(cx).worktree_for_id(id, cx)
1411 }
1412
1413 pub fn worktree_for_entry(
1414 &self,
1415 entry_id: ProjectEntryId,
1416 cx: &AppContext,
1417 ) -> Option<Model<Worktree>> {
1418 self.worktree_store
1419 .read(cx)
1420 .worktree_for_entry(entry_id, cx)
1421 }
1422
1423 pub fn worktree_id_for_entry(
1424 &self,
1425 entry_id: ProjectEntryId,
1426 cx: &AppContext,
1427 ) -> Option<WorktreeId> {
1428 self.worktree_for_entry(entry_id, cx)
1429 .map(|worktree| worktree.read(cx).id())
1430 }
1431
1432 /// Checks if the entry is the root of a worktree.
1433 pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &AppContext) -> bool {
1434 self.worktree_for_entry(entry_id, cx)
1435 .map(|worktree| {
1436 worktree
1437 .read(cx)
1438 .root_entry()
1439 .is_some_and(|e| e.id == entry_id)
1440 })
1441 .unwrap_or(false)
1442 }
1443
1444 pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &AppContext) -> Option<bool> {
1445 paths
1446 .iter()
1447 .map(|path| self.visibility_for_path(path, cx))
1448 .max()
1449 .flatten()
1450 }
1451
1452 pub fn visibility_for_path(&self, path: &Path, cx: &AppContext) -> Option<bool> {
1453 self.worktrees(cx)
1454 .filter_map(|worktree| {
1455 let worktree = worktree.read(cx);
1456 worktree
1457 .as_local()?
1458 .contains_abs_path(path)
1459 .then(|| worktree.is_visible())
1460 })
1461 .max()
1462 }
1463
1464 pub fn create_entry(
1465 &mut self,
1466 project_path: impl Into<ProjectPath>,
1467 is_directory: bool,
1468 cx: &mut ModelContext<Self>,
1469 ) -> Task<Result<CreatedEntry>> {
1470 let project_path = project_path.into();
1471 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1472 return Task::ready(Err(anyhow!(format!(
1473 "No worktree for path {project_path:?}"
1474 ))));
1475 };
1476 worktree.update(cx, |worktree, cx| {
1477 worktree.create_entry(project_path.path, is_directory, cx)
1478 })
1479 }
1480
1481 pub fn copy_entry(
1482 &mut self,
1483 entry_id: ProjectEntryId,
1484 relative_worktree_source_path: Option<PathBuf>,
1485 new_path: impl Into<Arc<Path>>,
1486 cx: &mut ModelContext<Self>,
1487 ) -> Task<Result<Option<Entry>>> {
1488 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1489 return Task::ready(Ok(None));
1490 };
1491 worktree.update(cx, |worktree, cx| {
1492 worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1493 })
1494 }
1495
1496 pub fn rename_entry(
1497 &mut self,
1498 entry_id: ProjectEntryId,
1499 new_path: impl Into<Arc<Path>>,
1500 cx: &mut ModelContext<Self>,
1501 ) -> Task<Result<CreatedEntry>> {
1502 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1503 return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1504 };
1505 worktree.update(cx, |worktree, cx| {
1506 worktree.rename_entry(entry_id, new_path, cx)
1507 })
1508 }
1509
1510 pub fn delete_entry(
1511 &mut self,
1512 entry_id: ProjectEntryId,
1513 trash: bool,
1514 cx: &mut ModelContext<Self>,
1515 ) -> Option<Task<Result<()>>> {
1516 let worktree = self.worktree_for_entry(entry_id, cx)?;
1517 worktree.update(cx, |worktree, cx| {
1518 worktree.delete_entry(entry_id, trash, cx)
1519 })
1520 }
1521
1522 pub fn expand_entry(
1523 &mut self,
1524 worktree_id: WorktreeId,
1525 entry_id: ProjectEntryId,
1526 cx: &mut ModelContext<Self>,
1527 ) -> Option<Task<Result<()>>> {
1528 let worktree = self.worktree_for_id(worktree_id, cx)?;
1529 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1530 }
1531
1532 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1533 if !matches!(self.client_state, ProjectClientState::Local) {
1534 if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1535 if *in_room || self.dev_server_project_id.is_none() {
1536 return Err(anyhow!("project was already shared"));
1537 } else {
1538 *in_room = true;
1539 return Ok(());
1540 }
1541 } else {
1542 return Err(anyhow!("project was already shared"));
1543 }
1544 }
1545 self.client_subscriptions.extend([
1546 self.client
1547 .subscribe_to_entity(project_id)?
1548 .set_model(&cx.handle(), &mut cx.to_async()),
1549 self.client
1550 .subscribe_to_entity(project_id)?
1551 .set_model(&self.worktree_store, &mut cx.to_async()),
1552 self.client
1553 .subscribe_to_entity(project_id)?
1554 .set_model(&self.buffer_store, &mut cx.to_async()),
1555 self.client
1556 .subscribe_to_entity(project_id)?
1557 .set_model(&self.lsp_store, &mut cx.to_async()),
1558 self.client
1559 .subscribe_to_entity(project_id)?
1560 .set_model(&self.settings_observer, &mut cx.to_async()),
1561 ]);
1562
1563 self.buffer_store.update(cx, |buffer_store, cx| {
1564 buffer_store.shared(project_id, self.client.clone().into(), cx)
1565 });
1566 self.worktree_store.update(cx, |worktree_store, cx| {
1567 worktree_store.set_shared(true, cx);
1568 });
1569 self.lsp_store.update(cx, |lsp_store, cx| {
1570 lsp_store.shared(project_id, self.client.clone().into(), cx)
1571 });
1572 self.settings_observer.update(cx, |settings_observer, cx| {
1573 settings_observer.shared(project_id, self.client.clone().into(), cx)
1574 });
1575
1576 self.client_state = ProjectClientState::Shared {
1577 remote_id: project_id,
1578 };
1579
1580 self.metadata_changed(cx);
1581 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1582 cx.notify();
1583 Ok(())
1584 }
1585
1586 pub fn reshared(
1587 &mut self,
1588 message: proto::ResharedProject,
1589 cx: &mut ModelContext<Self>,
1590 ) -> Result<()> {
1591 self.buffer_store
1592 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
1593 self.set_collaborators_from_proto(message.collaborators, cx)?;
1594 self.metadata_changed(cx);
1595 cx.emit(Event::Reshared);
1596 Ok(())
1597 }
1598
1599 pub fn rejoined(
1600 &mut self,
1601 message: proto::RejoinedProject,
1602 message_id: u32,
1603 cx: &mut ModelContext<Self>,
1604 ) -> Result<()> {
1605 cx.update_global::<SettingsStore, _>(|store, cx| {
1606 self.worktree_store.update(cx, |worktree_store, cx| {
1607 for worktree in worktree_store.worktrees() {
1608 store
1609 .clear_local_settings(worktree.read(cx).id(), cx)
1610 .log_err();
1611 }
1612 });
1613 });
1614
1615 self.join_project_response_message_id = message_id;
1616 self.set_worktrees_from_proto(message.worktrees, cx)?;
1617 self.set_collaborators_from_proto(message.collaborators, cx)?;
1618 self.lsp_store.update(cx, |lsp_store, _| {
1619 lsp_store.set_language_server_statuses_from_proto(message.language_servers)
1620 });
1621 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1622 .unwrap();
1623 cx.emit(Event::Rejoined);
1624 cx.notify();
1625 Ok(())
1626 }
1627
1628 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1629 self.unshare_internal(cx)?;
1630 self.metadata_changed(cx);
1631 cx.notify();
1632 Ok(())
1633 }
1634
1635 fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1636 if self.is_via_collab() {
1637 if self.dev_server_project_id().is_some() {
1638 if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1639 *in_room = false
1640 }
1641 return Ok(());
1642 } else {
1643 return Err(anyhow!("attempted to unshare a remote project"));
1644 }
1645 }
1646
1647 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1648 self.client_state = ProjectClientState::Local;
1649 self.collaborators.clear();
1650 self.client_subscriptions.clear();
1651 self.worktree_store.update(cx, |store, cx| {
1652 store.set_shared(false, cx);
1653 });
1654 self.buffer_store.update(cx, |buffer_store, cx| {
1655 buffer_store.forget_shared_buffers();
1656 buffer_store.unshared(cx)
1657 });
1658 self.settings_observer.update(cx, |settings_observer, cx| {
1659 settings_observer.unshared(cx);
1660 });
1661 self.client
1662 .send(proto::UnshareProject {
1663 project_id: remote_id,
1664 })
1665 .ok();
1666 Ok(())
1667 } else {
1668 Err(anyhow!("attempted to unshare an unshared project"))
1669 }
1670 }
1671
1672 pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1673 if self.is_disconnected() {
1674 return;
1675 }
1676 self.disconnected_from_host_internal(cx);
1677 cx.emit(Event::DisconnectedFromHost);
1678 cx.notify();
1679 }
1680
1681 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
1682 let new_capability =
1683 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1684 Capability::ReadWrite
1685 } else {
1686 Capability::ReadOnly
1687 };
1688 if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1689 if *capability == new_capability {
1690 return;
1691 }
1692
1693 *capability = new_capability;
1694 for buffer in self.opened_buffers(cx) {
1695 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1696 }
1697 }
1698 }
1699
1700 fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1701 if let ProjectClientState::Remote {
1702 sharing_has_stopped,
1703 ..
1704 } = &mut self.client_state
1705 {
1706 *sharing_has_stopped = true;
1707 self.collaborators.clear();
1708 self.worktree_store.update(cx, |store, cx| {
1709 store.disconnected_from_host(cx);
1710 });
1711 self.buffer_store.update(cx, |buffer_store, cx| {
1712 buffer_store.disconnected_from_host(cx)
1713 });
1714 self.lsp_store
1715 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
1716 }
1717 }
1718
1719 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1720 cx.emit(Event::Closed);
1721 }
1722
1723 pub fn is_disconnected(&self) -> bool {
1724 match &self.client_state {
1725 ProjectClientState::Remote {
1726 sharing_has_stopped,
1727 ..
1728 } => *sharing_has_stopped,
1729 _ => false,
1730 }
1731 }
1732
1733 pub fn capability(&self) -> Capability {
1734 match &self.client_state {
1735 ProjectClientState::Remote { capability, .. } => *capability,
1736 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1737 }
1738 }
1739
1740 pub fn is_read_only(&self) -> bool {
1741 self.is_disconnected() || self.capability() == Capability::ReadOnly
1742 }
1743
1744 pub fn is_local(&self) -> bool {
1745 match &self.client_state {
1746 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1747 self.ssh_session.is_none()
1748 }
1749 ProjectClientState::Remote { .. } => false,
1750 }
1751 }
1752
1753 pub fn is_local_or_ssh(&self) -> bool {
1754 match &self.client_state {
1755 ProjectClientState::Local | ProjectClientState::Shared { .. } => true,
1756 ProjectClientState::Remote { .. } => false,
1757 }
1758 }
1759
1760 pub fn is_via_collab(&self) -> bool {
1761 match &self.client_state {
1762 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
1763 ProjectClientState::Remote { .. } => true,
1764 }
1765 }
1766
1767 pub fn create_buffer(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Model<Buffer>>> {
1768 self.buffer_store.update(cx, |buffer_store, cx| {
1769 buffer_store.create_buffer(
1770 if self.is_via_collab() {
1771 Some((self.client.clone().into(), self.remote_id().unwrap()))
1772 } else {
1773 None
1774 },
1775 cx,
1776 )
1777 })
1778 }
1779
1780 pub fn create_local_buffer(
1781 &mut self,
1782 text: &str,
1783 language: Option<Arc<Language>>,
1784 cx: &mut ModelContext<Self>,
1785 ) -> Model<Buffer> {
1786 if self.is_via_collab() {
1787 panic!("called create_local_buffer on a remote project")
1788 }
1789 self.buffer_store.update(cx, |buffer_store, cx| {
1790 buffer_store.create_local_buffer(text, language, cx)
1791 })
1792 }
1793
1794 pub fn open_path(
1795 &mut self,
1796 path: ProjectPath,
1797 cx: &mut ModelContext<Self>,
1798 ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
1799 let task = self.open_buffer(path.clone(), cx);
1800 cx.spawn(move |_, cx| async move {
1801 let buffer = task.await?;
1802 let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1803 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1804 })?;
1805
1806 let buffer: &AnyModel = &buffer;
1807 Ok((project_entry_id, buffer.clone()))
1808 })
1809 }
1810
1811 pub fn open_local_buffer(
1812 &mut self,
1813 abs_path: impl AsRef<Path>,
1814 cx: &mut ModelContext<Self>,
1815 ) -> Task<Result<Model<Buffer>>> {
1816 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1817 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1818 } else {
1819 Task::ready(Err(anyhow!("no such path")))
1820 }
1821 }
1822
1823 pub fn open_buffer(
1824 &mut self,
1825 path: impl Into<ProjectPath>,
1826 cx: &mut ModelContext<Self>,
1827 ) -> Task<Result<Model<Buffer>>> {
1828 if self.is_via_collab() && self.is_disconnected() {
1829 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1830 }
1831
1832 self.buffer_store.update(cx, |buffer_store, cx| {
1833 buffer_store.open_buffer(path.into(), cx)
1834 })
1835 }
1836
1837 pub fn open_buffer_by_id(
1838 &mut self,
1839 id: BufferId,
1840 cx: &mut ModelContext<Self>,
1841 ) -> Task<Result<Model<Buffer>>> {
1842 if let Some(buffer) = self.buffer_for_id(id, cx) {
1843 Task::ready(Ok(buffer))
1844 } else if self.is_local_or_ssh() {
1845 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1846 } else if let Some(project_id) = self.remote_id() {
1847 let request = self.client.request(proto::OpenBufferById {
1848 project_id,
1849 id: id.into(),
1850 });
1851 cx.spawn(move |this, mut cx| async move {
1852 let buffer_id = BufferId::new(request.await?.buffer_id)?;
1853 this.update(&mut cx, |this, cx| {
1854 this.wait_for_remote_buffer(buffer_id, cx)
1855 })?
1856 .await
1857 })
1858 } else {
1859 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1860 }
1861 }
1862
1863 pub fn save_buffers(
1864 &self,
1865 buffers: HashSet<Model<Buffer>>,
1866 cx: &mut ModelContext<Self>,
1867 ) -> Task<Result<()>> {
1868 cx.spawn(move |this, mut cx| async move {
1869 let save_tasks = buffers.into_iter().filter_map(|buffer| {
1870 this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
1871 .ok()
1872 });
1873 try_join_all(save_tasks).await?;
1874 Ok(())
1875 })
1876 }
1877
1878 pub fn save_buffer(
1879 &self,
1880 buffer: Model<Buffer>,
1881 cx: &mut ModelContext<Self>,
1882 ) -> Task<Result<()>> {
1883 self.buffer_store
1884 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
1885 }
1886
1887 pub fn save_buffer_as(
1888 &mut self,
1889 buffer: Model<Buffer>,
1890 path: ProjectPath,
1891 cx: &mut ModelContext<Self>,
1892 ) -> Task<Result<()>> {
1893 self.buffer_store.update(cx, |buffer_store, cx| {
1894 buffer_store.save_buffer_as(buffer.clone(), path, cx)
1895 })
1896 }
1897
1898 pub fn get_open_buffer(
1899 &mut self,
1900 path: &ProjectPath,
1901 cx: &mut ModelContext<Self>,
1902 ) -> Option<Model<Buffer>> {
1903 self.buffer_store.read(cx).get_by_path(path, cx)
1904 }
1905
1906 fn register_buffer(
1907 &mut self,
1908 buffer: &Model<Buffer>,
1909 cx: &mut ModelContext<Self>,
1910 ) -> Result<()> {
1911 {
1912 let mut remotely_created_buffers = self.remotely_created_buffers.lock();
1913 if remotely_created_buffers.retain_count > 0 {
1914 remotely_created_buffers.buffers.push(buffer.clone())
1915 }
1916 }
1917
1918 self.request_buffer_diff_recalculation(buffer, cx);
1919
1920 cx.subscribe(buffer, |this, buffer, event, cx| {
1921 this.on_buffer_event(buffer, event, cx);
1922 })
1923 .detach();
1924
1925 Ok(())
1926 }
1927
1928 async fn send_buffer_ordered_messages(
1929 this: WeakModel<Self>,
1930 rx: UnboundedReceiver<BufferOrderedMessage>,
1931 mut cx: AsyncAppContext,
1932 ) -> Result<()> {
1933 const MAX_BATCH_SIZE: usize = 128;
1934
1935 let mut operations_by_buffer_id = HashMap::default();
1936 async fn flush_operations(
1937 this: &WeakModel<Project>,
1938 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
1939 needs_resync_with_host: &mut bool,
1940 is_local: bool,
1941 cx: &mut AsyncAppContext,
1942 ) -> Result<()> {
1943 for (buffer_id, operations) in operations_by_buffer_id.drain() {
1944 let request = this.update(cx, |this, _| {
1945 let project_id = this.remote_id()?;
1946 Some(this.client.request(proto::UpdateBuffer {
1947 buffer_id: buffer_id.into(),
1948 project_id,
1949 operations,
1950 }))
1951 })?;
1952 if let Some(request) = request {
1953 if request.await.is_err() && !is_local {
1954 *needs_resync_with_host = true;
1955 break;
1956 }
1957 }
1958 }
1959 Ok(())
1960 }
1961
1962 let mut needs_resync_with_host = false;
1963 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
1964
1965 while let Some(changes) = changes.next().await {
1966 let is_local = this.update(&mut cx, |this, _| this.is_local_or_ssh())?;
1967
1968 for change in changes {
1969 match change {
1970 BufferOrderedMessage::Operation {
1971 buffer_id,
1972 operation,
1973 } => {
1974 if needs_resync_with_host {
1975 continue;
1976 }
1977
1978 operations_by_buffer_id
1979 .entry(buffer_id)
1980 .or_insert(Vec::new())
1981 .push(operation);
1982 }
1983
1984 BufferOrderedMessage::Resync => {
1985 operations_by_buffer_id.clear();
1986 if this
1987 .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
1988 .await
1989 .is_ok()
1990 {
1991 needs_resync_with_host = false;
1992 }
1993 }
1994
1995 BufferOrderedMessage::LanguageServerUpdate {
1996 language_server_id,
1997 message,
1998 } => {
1999 flush_operations(
2000 &this,
2001 &mut operations_by_buffer_id,
2002 &mut needs_resync_with_host,
2003 is_local,
2004 &mut cx,
2005 )
2006 .await?;
2007
2008 this.update(&mut cx, |this, _| {
2009 if let Some(project_id) = this.remote_id() {
2010 this.client
2011 .send(proto::UpdateLanguageServer {
2012 project_id,
2013 language_server_id: language_server_id.0 as u64,
2014 variant: Some(message),
2015 })
2016 .log_err();
2017 }
2018 })?;
2019 }
2020 }
2021 }
2022
2023 flush_operations(
2024 &this,
2025 &mut operations_by_buffer_id,
2026 &mut needs_resync_with_host,
2027 is_local,
2028 &mut cx,
2029 )
2030 .await?;
2031 }
2032
2033 Ok(())
2034 }
2035
2036 fn on_buffer_store_event(
2037 &mut self,
2038 _: Model<BufferStore>,
2039 event: &BufferStoreEvent,
2040 cx: &mut ModelContext<Self>,
2041 ) {
2042 match event {
2043 BufferStoreEvent::BufferAdded(buffer) => {
2044 self.register_buffer(buffer, cx).log_err();
2045 }
2046 BufferStoreEvent::BufferChangedFilePath { .. } => {}
2047 BufferStoreEvent::BufferDropped(buffer_id) => {
2048 if let Some(ref ssh_session) = self.ssh_session {
2049 ssh_session
2050 .send(proto::CloseBuffer {
2051 project_id: 0,
2052 buffer_id: buffer_id.to_proto(),
2053 })
2054 .log_err();
2055 }
2056 }
2057 }
2058 }
2059
2060 fn on_lsp_store_event(
2061 &mut self,
2062 _: Model<LspStore>,
2063 event: &LspStoreEvent,
2064 cx: &mut ModelContext<Self>,
2065 ) {
2066 match event {
2067 LspStoreEvent::DiagnosticsUpdated {
2068 language_server_id,
2069 path,
2070 } => cx.emit(Event::DiagnosticsUpdated {
2071 path: path.clone(),
2072 language_server_id: *language_server_id,
2073 }),
2074 LspStoreEvent::LanguageServerAdded(language_server_id) => {
2075 cx.emit(Event::LanguageServerAdded(*language_server_id))
2076 }
2077 LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2078 cx.emit(Event::LanguageServerAdded(*language_server_id))
2079 }
2080 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2081 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2082 ),
2083 LspStoreEvent::LanguageDetected {
2084 buffer,
2085 new_language,
2086 } => {
2087 let Some(new_language) = new_language else {
2088 cx.emit(Event::LanguageNotFound(buffer.clone()));
2089 return;
2090 };
2091 let buffer_file = buffer.read(cx).file().cloned();
2092 let settings =
2093 language_settings(Some(new_language), buffer_file.as_ref(), cx).clone();
2094 let buffer_file = File::from_dyn(buffer_file.as_ref());
2095 let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
2096 if let Some(prettier_plugins) =
2097 prettier_support::prettier_plugins_for_language(&settings)
2098 {
2099 self.install_default_prettier(
2100 worktree,
2101 prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
2102 cx,
2103 );
2104 };
2105 }
2106 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2107 LspStoreEvent::LanguageServerPrompt(prompt) => {
2108 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2109 }
2110 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2111 cx.emit(Event::DiskBasedDiagnosticsStarted {
2112 language_server_id: *language_server_id,
2113 });
2114 if self.is_local_or_ssh() {
2115 self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
2116 language_server_id: *language_server_id,
2117 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2118 Default::default(),
2119 ),
2120 })
2121 .ok();
2122 }
2123 }
2124 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2125 cx.emit(Event::DiskBasedDiagnosticsFinished {
2126 language_server_id: *language_server_id,
2127 });
2128 if self.is_local_or_ssh() {
2129 self.enqueue_buffer_ordered_message(
2130 BufferOrderedMessage::LanguageServerUpdate {
2131 language_server_id: *language_server_id,
2132 message:
2133 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2134 Default::default(),
2135 ),
2136 },
2137 )
2138 .ok();
2139 }
2140 }
2141 LspStoreEvent::LanguageServerUpdate {
2142 language_server_id,
2143 message,
2144 } => {
2145 if self.is_local_or_ssh() {
2146 self.enqueue_buffer_ordered_message(
2147 BufferOrderedMessage::LanguageServerUpdate {
2148 language_server_id: *language_server_id,
2149 message: message.clone(),
2150 },
2151 )
2152 .ok();
2153 }
2154 }
2155 LspStoreEvent::Notification(message) => cx.emit(Event::Notification(message.clone())),
2156 LspStoreEvent::SnippetEdit {
2157 buffer_id,
2158 edits,
2159 most_recent_edit,
2160 } => {
2161 if most_recent_edit.replica_id == self.replica_id() {
2162 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2163 }
2164 }
2165 LspStoreEvent::StartFormattingLocalBuffer(buffer_id) => {
2166 self.buffers_being_formatted.insert(*buffer_id);
2167 }
2168 LspStoreEvent::FinishFormattingLocalBuffer(buffer_id) => {
2169 self.buffers_being_formatted.remove(buffer_id);
2170 }
2171 }
2172 }
2173
2174 fn on_worktree_store_event(
2175 &mut self,
2176 _: Model<WorktreeStore>,
2177 event: &WorktreeStoreEvent,
2178 cx: &mut ModelContext<Self>,
2179 ) {
2180 match event {
2181 WorktreeStoreEvent::WorktreeAdded(worktree) => {
2182 self.on_worktree_added(worktree, cx);
2183 cx.emit(Event::WorktreeAdded);
2184 }
2185 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2186 self.on_worktree_removed(*id, cx);
2187 cx.emit(Event::WorktreeRemoved(*id));
2188 }
2189 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2190 }
2191 }
2192
2193 fn on_worktree_added(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
2194 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2195 cx.subscribe(worktree, |this, worktree, event, cx| {
2196 let is_local = worktree.read(cx).is_local();
2197 match event {
2198 worktree::Event::UpdatedEntries(changes) => {
2199 if is_local {
2200 this.update_local_worktree_settings(&worktree, changes, cx);
2201 this.update_prettier_settings(&worktree, changes, cx);
2202 }
2203
2204 cx.emit(Event::WorktreeUpdatedEntries(
2205 worktree.read(cx).id(),
2206 changes.clone(),
2207 ));
2208
2209 let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
2210 this.client()
2211 .telemetry()
2212 .report_discovered_project_events(worktree_id, changes);
2213 }
2214 worktree::Event::UpdatedGitRepositories(_) => {
2215 cx.emit(Event::WorktreeUpdatedGitRepositories);
2216 }
2217 worktree::Event::DeletedEntry(id) => cx.emit(Event::DeletedEntry(*id)),
2218 }
2219 })
2220 .detach();
2221 self.metadata_changed(cx);
2222 }
2223
2224 fn on_worktree_removed(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
2225 if let Some(dev_server_project_id) = self.dev_server_project_id {
2226 let paths: Vec<String> = self
2227 .visible_worktrees(cx)
2228 .filter_map(|worktree| {
2229 if worktree.read(cx).id() == id_to_remove {
2230 None
2231 } else {
2232 Some(worktree.read(cx).abs_path().to_string_lossy().to_string())
2233 }
2234 })
2235 .collect();
2236 if !paths.is_empty() {
2237 let request = self.client.request(proto::UpdateDevServerProject {
2238 dev_server_project_id: dev_server_project_id.0,
2239 paths,
2240 });
2241 cx.background_executor()
2242 .spawn(request)
2243 .detach_and_log_err(cx);
2244 }
2245 return;
2246 }
2247
2248 let mut prettier_instances_to_clean = FuturesUnordered::new();
2249 if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
2250 for path in prettier_paths.iter().flatten() {
2251 if let Some(prettier_instance) = self.prettier_instances.remove(path) {
2252 prettier_instances_to_clean.push(async move {
2253 prettier_instance
2254 .server()
2255 .await
2256 .map(|server| server.server_id())
2257 });
2258 }
2259 }
2260 }
2261 cx.spawn(|project, mut cx| async move {
2262 while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
2263 if let Some(prettier_server_id) = prettier_server_id {
2264 project
2265 .update(&mut cx, |project, cx| {
2266 project.lsp_store.update(cx, |lsp_store, cx| {
2267 lsp_store.unregister_supplementary_language_server(
2268 prettier_server_id,
2269 cx,
2270 );
2271 });
2272 })
2273 .ok();
2274 }
2275 }
2276 })
2277 .detach();
2278
2279 self.task_inventory().update(cx, |inventory, _| {
2280 inventory.remove_worktree_sources(id_to_remove);
2281 });
2282
2283 self.metadata_changed(cx);
2284 }
2285
2286 fn on_buffer_event(
2287 &mut self,
2288 buffer: Model<Buffer>,
2289 event: &BufferEvent,
2290 cx: &mut ModelContext<Self>,
2291 ) -> Option<()> {
2292 if matches!(
2293 event,
2294 BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2295 ) {
2296 self.request_buffer_diff_recalculation(&buffer, cx);
2297 }
2298
2299 let buffer_id = buffer.read(cx).remote_id();
2300 match event {
2301 BufferEvent::Operation(operation) => {
2302 let operation = language::proto::serialize_operation(operation);
2303
2304 if let Some(ssh) = &self.ssh_session {
2305 ssh.send(proto::UpdateBuffer {
2306 project_id: 0,
2307 buffer_id: buffer_id.to_proto(),
2308 operations: vec![operation.clone()],
2309 })
2310 .ok();
2311 }
2312
2313 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2314 buffer_id,
2315 operation,
2316 })
2317 .ok();
2318 }
2319
2320 BufferEvent::Reloaded => {
2321 if self.is_local_or_ssh() {
2322 if let Some(project_id) = self.remote_id() {
2323 let buffer = buffer.read(cx);
2324 self.client
2325 .send(proto::BufferReloaded {
2326 project_id,
2327 buffer_id: buffer.remote_id().to_proto(),
2328 version: serialize_version(&buffer.version()),
2329 mtime: buffer.saved_mtime().map(|t| t.into()),
2330 line_ending: serialize_line_ending(buffer.line_ending()) as i32,
2331 })
2332 .log_err();
2333 }
2334 }
2335 }
2336
2337 _ => {}
2338 }
2339
2340 None
2341 }
2342
2343 fn request_buffer_diff_recalculation(
2344 &mut self,
2345 buffer: &Model<Buffer>,
2346 cx: &mut ModelContext<Self>,
2347 ) {
2348 self.buffers_needing_diff.insert(buffer.downgrade());
2349 let first_insertion = self.buffers_needing_diff.len() == 1;
2350
2351 let settings = ProjectSettings::get_global(cx);
2352 let delay = if let Some(delay) = settings.git.gutter_debounce {
2353 delay
2354 } else {
2355 if first_insertion {
2356 let this = cx.weak_model();
2357 cx.defer(move |cx| {
2358 if let Some(this) = this.upgrade() {
2359 this.update(cx, |this, cx| {
2360 this.recalculate_buffer_diffs(cx).detach();
2361 });
2362 }
2363 });
2364 }
2365 return;
2366 };
2367
2368 const MIN_DELAY: u64 = 50;
2369 let delay = delay.max(MIN_DELAY);
2370 let duration = Duration::from_millis(delay);
2371
2372 self.git_diff_debouncer
2373 .fire_new(duration, cx, move |this, cx| {
2374 this.recalculate_buffer_diffs(cx)
2375 });
2376 }
2377
2378 fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2379 let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2380 cx.spawn(move |this, mut cx| async move {
2381 let tasks: Vec<_> = buffers
2382 .iter()
2383 .filter_map(|buffer| {
2384 let buffer = buffer.upgrade()?;
2385 buffer
2386 .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
2387 .ok()
2388 .flatten()
2389 })
2390 .collect();
2391
2392 futures::future::join_all(tasks).await;
2393
2394 this.update(&mut cx, |this, cx| {
2395 if this.buffers_needing_diff.is_empty() {
2396 // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2397 for buffer in buffers {
2398 if let Some(buffer) = buffer.upgrade() {
2399 buffer.update(cx, |_, cx| cx.notify());
2400 }
2401 }
2402 } else {
2403 this.recalculate_buffer_diffs(cx).detach();
2404 }
2405 })
2406 .ok();
2407 })
2408 }
2409
2410 pub fn set_language_for_buffer(
2411 &mut self,
2412 buffer: &Model<Buffer>,
2413 new_language: Arc<Language>,
2414 cx: &mut ModelContext<Self>,
2415 ) {
2416 self.lsp_store.update(cx, |lsp_store, cx| {
2417 lsp_store.set_language_for_buffer(buffer, new_language, cx)
2418 })
2419 }
2420
2421 pub fn restart_language_servers_for_buffers(
2422 &mut self,
2423 buffers: impl IntoIterator<Item = Model<Buffer>>,
2424 cx: &mut ModelContext<Self>,
2425 ) {
2426 self.lsp_store.update(cx, |lsp_store, cx| {
2427 lsp_store.restart_language_servers_for_buffers(buffers, cx)
2428 })
2429 }
2430
2431 pub fn cancel_language_server_work_for_buffers(
2432 &mut self,
2433 buffers: impl IntoIterator<Item = Model<Buffer>>,
2434 cx: &mut ModelContext<Self>,
2435 ) {
2436 self.lsp_store.update(cx, |lsp_store, cx| {
2437 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2438 })
2439 }
2440
2441 pub fn cancel_language_server_work(
2442 &mut self,
2443 server_id: LanguageServerId,
2444 token_to_cancel: Option<String>,
2445 cx: &mut ModelContext<Self>,
2446 ) {
2447 self.lsp_store.update(cx, |lsp_store, cx| {
2448 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2449 })
2450 }
2451
2452 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2453 self.buffer_ordered_messages_tx
2454 .unbounded_send(message)
2455 .map_err(|e| anyhow!(e))
2456 }
2457
2458 pub fn language_server_statuses<'a>(
2459 &'a self,
2460 cx: &'a AppContext,
2461 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2462 self.lsp_store.read(cx).language_server_statuses()
2463 }
2464
2465 pub fn last_formatting_failure(&self) -> Option<&str> {
2466 self.last_formatting_failure.as_deref()
2467 }
2468
2469 pub fn update_diagnostics(
2470 &mut self,
2471 language_server_id: LanguageServerId,
2472 params: lsp::PublishDiagnosticsParams,
2473 disk_based_sources: &[String],
2474 cx: &mut ModelContext<Self>,
2475 ) -> Result<()> {
2476 self.lsp_store.update(cx, |lsp_store, cx| {
2477 lsp_store.update_diagnostics(language_server_id, params, disk_based_sources, cx)
2478 })
2479 }
2480
2481 pub fn update_diagnostic_entries(
2482 &mut self,
2483 server_id: LanguageServerId,
2484 abs_path: PathBuf,
2485 version: Option<i32>,
2486 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2487 cx: &mut ModelContext<Project>,
2488 ) -> Result<(), anyhow::Error> {
2489 self.lsp_store.update(cx, |lsp_store, cx| {
2490 lsp_store.update_diagnostic_entries(server_id, abs_path, version, diagnostics, cx)
2491 })
2492 }
2493
2494 pub fn reload_buffers(
2495 &self,
2496 buffers: HashSet<Model<Buffer>>,
2497 push_to_history: bool,
2498 cx: &mut ModelContext<Self>,
2499 ) -> Task<Result<ProjectTransaction>> {
2500 let mut local_buffers = Vec::new();
2501 let mut remote_buffers = None;
2502 for buffer_handle in buffers {
2503 let buffer = buffer_handle.read(cx);
2504 if buffer.is_dirty() {
2505 if let Some(file) = File::from_dyn(buffer.file()) {
2506 if file.is_local() {
2507 local_buffers.push(buffer_handle);
2508 } else {
2509 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2510 }
2511 }
2512 }
2513 }
2514
2515 let remote_buffers = self.remote_id().zip(remote_buffers);
2516 let client = self.client.clone();
2517
2518 cx.spawn(move |this, mut cx| async move {
2519 let mut project_transaction = ProjectTransaction::default();
2520
2521 if let Some((project_id, remote_buffers)) = remote_buffers {
2522 let response = client
2523 .request(proto::ReloadBuffers {
2524 project_id,
2525 buffer_ids: remote_buffers
2526 .iter()
2527 .filter_map(|buffer| {
2528 buffer
2529 .update(&mut cx, |buffer, _| buffer.remote_id().into())
2530 .ok()
2531 })
2532 .collect(),
2533 })
2534 .await?
2535 .transaction
2536 .ok_or_else(|| anyhow!("missing transaction"))?;
2537 BufferStore::deserialize_project_transaction(
2538 this.read_with(&cx, |this, _| this.buffer_store.downgrade())?,
2539 response,
2540 push_to_history,
2541 cx.clone(),
2542 )
2543 .await?;
2544 }
2545
2546 for buffer in local_buffers {
2547 let transaction = buffer
2548 .update(&mut cx, |buffer, cx| buffer.reload(cx))?
2549 .await?;
2550 buffer.update(&mut cx, |buffer, cx| {
2551 if let Some(transaction) = transaction {
2552 if !push_to_history {
2553 buffer.forget_transaction(transaction.id);
2554 }
2555 project_transaction.0.insert(cx.handle(), transaction);
2556 }
2557 })?;
2558 }
2559
2560 Ok(project_transaction)
2561 })
2562 }
2563
2564 pub fn format(
2565 &mut self,
2566 buffers: HashSet<Model<Buffer>>,
2567 push_to_history: bool,
2568 trigger: FormatTrigger,
2569 cx: &mut ModelContext<Project>,
2570 ) -> Task<anyhow::Result<ProjectTransaction>> {
2571 if self.is_local_or_ssh() {
2572 let buffers_with_paths = buffers
2573 .into_iter()
2574 .map(|buffer_handle| {
2575 let buffer = buffer_handle.read(cx);
2576 let buffer_abs_path = File::from_dyn(buffer.file())
2577 .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
2578 (buffer_handle, buffer_abs_path)
2579 })
2580 .collect::<Vec<_>>();
2581
2582 cx.spawn(move |project, mut cx| async move {
2583 let result = Self::format_locally(
2584 project.clone(),
2585 buffers_with_paths,
2586 push_to_history,
2587 trigger,
2588 cx.clone(),
2589 )
2590 .await;
2591
2592 project.update(&mut cx, |project, _| match &result {
2593 Ok(_) => project.last_formatting_failure = None,
2594 Err(error) => {
2595 project.last_formatting_failure.replace(error.to_string());
2596 }
2597 })?;
2598
2599 result
2600 })
2601 } else {
2602 let remote_id = self.remote_id();
2603 let client = self.client.clone();
2604 cx.spawn(move |this, mut cx| async move {
2605 if let Some(project_id) = remote_id {
2606 let response = client
2607 .request(proto::FormatBuffers {
2608 project_id,
2609 trigger: trigger as i32,
2610 buffer_ids: buffers
2611 .iter()
2612 .map(|buffer| {
2613 buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
2614 })
2615 .collect::<Result<_>>()?,
2616 })
2617 .await?
2618 .transaction
2619 .ok_or_else(|| anyhow!("missing transaction"))?;
2620 BufferStore::deserialize_project_transaction(
2621 this.read_with(&cx, |this, _| this.buffer_store.downgrade())?,
2622 response,
2623 push_to_history,
2624 cx,
2625 )
2626 .await
2627 } else {
2628 Ok(ProjectTransaction::default())
2629 }
2630 })
2631 }
2632 }
2633
2634 async fn format_locally(
2635 project: WeakModel<Project>,
2636 mut buffers_with_paths: Vec<(Model<Buffer>, Option<PathBuf>)>,
2637 push_to_history: bool,
2638 trigger: FormatTrigger,
2639 mut cx: AsyncAppContext,
2640 ) -> anyhow::Result<ProjectTransaction> {
2641 // Do not allow multiple concurrent formatting requests for the
2642 // same buffer.
2643 let lsp_store = project.update(&mut cx, |this, cx| {
2644 buffers_with_paths.retain(|(buffer, _)| {
2645 this.buffers_being_formatted
2646 .insert(buffer.read(cx).remote_id())
2647 });
2648 this.lsp_store.downgrade()
2649 })?;
2650
2651 let _cleanup = defer({
2652 let this = project.clone();
2653 let mut cx = cx.clone();
2654 let buffers = &buffers_with_paths;
2655 move || {
2656 this.update(&mut cx, |this, cx| {
2657 for (buffer, _) in buffers {
2658 this.buffers_being_formatted
2659 .remove(&buffer.read(cx).remote_id());
2660 }
2661 })
2662 .ok();
2663 }
2664 });
2665
2666 let mut project_transaction = ProjectTransaction::default();
2667 for (buffer, buffer_abs_path) in &buffers_with_paths {
2668 let (primary_adapter_and_server, adapters_and_servers) =
2669 project.update(&mut cx, |project, cx| {
2670 let buffer = buffer.read(cx);
2671
2672 let adapters_and_servers = project
2673 .language_servers_for_buffer(buffer, cx)
2674 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
2675 .collect::<Vec<_>>();
2676
2677 let primary_adapter = project
2678 .lsp_store
2679 .read(cx)
2680 .primary_language_server_for_buffer(buffer, cx)
2681 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()));
2682
2683 (primary_adapter, adapters_and_servers)
2684 })?;
2685
2686 let settings = buffer.update(&mut cx, |buffer, cx| {
2687 language_settings(buffer.language(), buffer.file(), cx).clone()
2688 })?;
2689
2690 let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
2691 let ensure_final_newline = settings.ensure_final_newline_on_save;
2692
2693 // First, format buffer's whitespace according to the settings.
2694 let trailing_whitespace_diff = if remove_trailing_whitespace {
2695 Some(
2696 buffer
2697 .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
2698 .await,
2699 )
2700 } else {
2701 None
2702 };
2703 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
2704 buffer.finalize_last_transaction();
2705 buffer.start_transaction();
2706 if let Some(diff) = trailing_whitespace_diff {
2707 buffer.apply_diff(diff, cx);
2708 }
2709 if ensure_final_newline {
2710 buffer.ensure_final_newline(cx);
2711 }
2712 buffer.end_transaction(cx)
2713 })?;
2714
2715 // Apply the `code_actions_on_format` before we run the formatter.
2716 let code_actions = deserialize_code_actions(&settings.code_actions_on_format);
2717 #[allow(clippy::nonminimal_bool)]
2718 if !code_actions.is_empty()
2719 && !(trigger == FormatTrigger::Save && settings.format_on_save == FormatOnSave::Off)
2720 {
2721 LspStore::execute_code_actions_on_servers(
2722 &lsp_store,
2723 &adapters_and_servers,
2724 code_actions,
2725 buffer,
2726 push_to_history,
2727 &mut project_transaction,
2728 &mut cx,
2729 )
2730 .await?;
2731 }
2732
2733 // Apply language-specific formatting using either the primary language server
2734 // or external command.
2735 // Except for code actions, which are applied with all connected language servers.
2736 let primary_language_server =
2737 primary_adapter_and_server.map(|(_adapter, server)| server.clone());
2738 let server_and_buffer = primary_language_server
2739 .as_ref()
2740 .zip(buffer_abs_path.as_ref());
2741
2742 let prettier_settings = buffer.read_with(&cx, |buffer, cx| {
2743 language_settings(buffer.language(), buffer.file(), cx)
2744 .prettier
2745 .clone()
2746 })?;
2747
2748 let mut format_operations: Vec<FormatOperation> = vec![];
2749 {
2750 match trigger {
2751 FormatTrigger::Save => {
2752 match &settings.format_on_save {
2753 FormatOnSave::Off => {
2754 // nothing
2755 }
2756 FormatOnSave::On => {
2757 match &settings.formatter {
2758 SelectedFormatter::Auto => {
2759 // do the auto-format: prefer prettier, fallback to primary language server
2760 let diff = {
2761 if prettier_settings.allowed {
2762 Self::perform_format(
2763 &Formatter::Prettier,
2764 server_and_buffer,
2765 project.clone(),
2766 buffer,
2767 buffer_abs_path,
2768 &settings,
2769 &adapters_and_servers,
2770 push_to_history,
2771 &mut project_transaction,
2772 &mut cx,
2773 )
2774 .await
2775 } else {
2776 Self::perform_format(
2777 &Formatter::LanguageServer { name: None },
2778 server_and_buffer,
2779 project.clone(),
2780 buffer,
2781 buffer_abs_path,
2782 &settings,
2783 &adapters_and_servers,
2784 push_to_history,
2785 &mut project_transaction,
2786 &mut cx,
2787 )
2788 .await
2789 }
2790 }
2791 .log_err()
2792 .flatten();
2793 if let Some(op) = diff {
2794 format_operations.push(op);
2795 }
2796 }
2797 SelectedFormatter::List(formatters) => {
2798 for formatter in formatters.as_ref() {
2799 let diff = Self::perform_format(
2800 formatter,
2801 server_and_buffer,
2802 project.clone(),
2803 buffer,
2804 buffer_abs_path,
2805 &settings,
2806 &adapters_and_servers,
2807 push_to_history,
2808 &mut project_transaction,
2809 &mut cx,
2810 )
2811 .await
2812 .log_err()
2813 .flatten();
2814 if let Some(op) = diff {
2815 format_operations.push(op);
2816 }
2817
2818 // format with formatter
2819 }
2820 }
2821 }
2822 }
2823 FormatOnSave::List(formatters) => {
2824 for formatter in formatters.as_ref() {
2825 let diff = Self::perform_format(
2826 formatter,
2827 server_and_buffer,
2828 project.clone(),
2829 buffer,
2830 buffer_abs_path,
2831 &settings,
2832 &adapters_and_servers,
2833 push_to_history,
2834 &mut project_transaction,
2835 &mut cx,
2836 )
2837 .await
2838 .log_err()
2839 .flatten();
2840 if let Some(op) = diff {
2841 format_operations.push(op);
2842 }
2843 }
2844 }
2845 }
2846 }
2847 FormatTrigger::Manual => {
2848 match &settings.formatter {
2849 SelectedFormatter::Auto => {
2850 // do the auto-format: prefer prettier, fallback to primary language server
2851 let diff = {
2852 if prettier_settings.allowed {
2853 Self::perform_format(
2854 &Formatter::Prettier,
2855 server_and_buffer,
2856 project.clone(),
2857 buffer,
2858 buffer_abs_path,
2859 &settings,
2860 &adapters_and_servers,
2861 push_to_history,
2862 &mut project_transaction,
2863 &mut cx,
2864 )
2865 .await
2866 } else {
2867 Self::perform_format(
2868 &Formatter::LanguageServer { name: None },
2869 server_and_buffer,
2870 project.clone(),
2871 buffer,
2872 buffer_abs_path,
2873 &settings,
2874 &adapters_and_servers,
2875 push_to_history,
2876 &mut project_transaction,
2877 &mut cx,
2878 )
2879 .await
2880 }
2881 }
2882 .log_err()
2883 .flatten();
2884
2885 if let Some(op) = diff {
2886 format_operations.push(op)
2887 }
2888 }
2889 SelectedFormatter::List(formatters) => {
2890 for formatter in formatters.as_ref() {
2891 // format with formatter
2892 let diff = Self::perform_format(
2893 formatter,
2894 server_and_buffer,
2895 project.clone(),
2896 buffer,
2897 buffer_abs_path,
2898 &settings,
2899 &adapters_and_servers,
2900 push_to_history,
2901 &mut project_transaction,
2902 &mut cx,
2903 )
2904 .await
2905 .log_err()
2906 .flatten();
2907 if let Some(op) = diff {
2908 format_operations.push(op);
2909 }
2910 }
2911 }
2912 }
2913 }
2914 }
2915 }
2916
2917 buffer.update(&mut cx, |b, cx| {
2918 // If the buffer had its whitespace formatted and was edited while the language-specific
2919 // formatting was being computed, avoid applying the language-specific formatting, because
2920 // it can't be grouped with the whitespace formatting in the undo history.
2921 if let Some(transaction_id) = whitespace_transaction_id {
2922 if b.peek_undo_stack()
2923 .map_or(true, |e| e.transaction_id() != transaction_id)
2924 {
2925 format_operations.clear();
2926 }
2927 }
2928
2929 // Apply any language-specific formatting, and group the two formatting operations
2930 // in the buffer's undo history.
2931 for operation in format_operations {
2932 match operation {
2933 FormatOperation::Lsp(edits) => {
2934 b.edit(edits, None, cx);
2935 }
2936 FormatOperation::External(diff) => {
2937 b.apply_diff(diff, cx);
2938 }
2939 FormatOperation::Prettier(diff) => {
2940 b.apply_diff(diff, cx);
2941 }
2942 }
2943
2944 if let Some(transaction_id) = whitespace_transaction_id {
2945 b.group_until_transaction(transaction_id);
2946 } else if let Some(transaction) = project_transaction.0.get(buffer) {
2947 b.group_until_transaction(transaction.id)
2948 }
2949 }
2950
2951 if let Some(transaction) = b.finalize_last_transaction().cloned() {
2952 if !push_to_history {
2953 b.forget_transaction(transaction.id);
2954 }
2955 project_transaction.0.insert(buffer.clone(), transaction);
2956 }
2957 })?;
2958 }
2959
2960 Ok(project_transaction)
2961 }
2962
2963 #[allow(clippy::too_many_arguments)]
2964 async fn perform_format(
2965 formatter: &Formatter,
2966 primary_server_and_buffer: Option<(&Arc<LanguageServer>, &PathBuf)>,
2967 project: WeakModel<Project>,
2968 buffer: &Model<Buffer>,
2969 buffer_abs_path: &Option<PathBuf>,
2970 settings: &LanguageSettings,
2971 adapters_and_servers: &[(Arc<CachedLspAdapter>, Arc<LanguageServer>)],
2972 push_to_history: bool,
2973 transaction: &mut ProjectTransaction,
2974 cx: &mut AsyncAppContext,
2975 ) -> Result<Option<FormatOperation>, anyhow::Error> {
2976 let result = match formatter {
2977 Formatter::LanguageServer { name } => {
2978 if let Some((language_server, buffer_abs_path)) = primary_server_and_buffer {
2979 let language_server = if let Some(name) = name {
2980 adapters_and_servers
2981 .iter()
2982 .find_map(|(adapter, server)| {
2983 adapter.name.0.as_ref().eq(name.as_str()).then_some(server)
2984 })
2985 .unwrap_or(language_server)
2986 } else {
2987 language_server
2988 };
2989
2990 let lsp_store = project.update(cx, |p, _| p.lsp_store.downgrade())?;
2991 Some(FormatOperation::Lsp(
2992 LspStore::format_via_lsp(
2993 &lsp_store,
2994 buffer,
2995 buffer_abs_path,
2996 language_server,
2997 settings,
2998 cx,
2999 )
3000 .await
3001 .context("failed to format via language server")?,
3002 ))
3003 } else {
3004 None
3005 }
3006 }
3007 Formatter::Prettier => prettier_support::format_with_prettier(&project, buffer, cx)
3008 .await
3009 .transpose()
3010 .ok()
3011 .flatten(),
3012 Formatter::External { command, arguments } => {
3013 let buffer_abs_path = buffer_abs_path.as_ref().map(|path| path.as_path());
3014 Self::format_via_external_command(buffer, buffer_abs_path, command, arguments, cx)
3015 .await
3016 .context(format!(
3017 "failed to format via external command {:?}",
3018 command
3019 ))?
3020 .map(FormatOperation::External)
3021 }
3022 Formatter::CodeActions(code_actions) => {
3023 let code_actions = deserialize_code_actions(code_actions);
3024 let lsp_store = project.update(cx, |p, _| p.lsp_store.downgrade())?;
3025 if !code_actions.is_empty() {
3026 LspStore::execute_code_actions_on_servers(
3027 &lsp_store,
3028 adapters_and_servers,
3029 code_actions,
3030 buffer,
3031 push_to_history,
3032 transaction,
3033 cx,
3034 )
3035 .await?;
3036 }
3037 None
3038 }
3039 };
3040 anyhow::Ok(result)
3041 }
3042
3043 async fn format_via_external_command(
3044 buffer: &Model<Buffer>,
3045 buffer_abs_path: Option<&Path>,
3046 command: &str,
3047 arguments: &[String],
3048 cx: &mut AsyncAppContext,
3049 ) -> Result<Option<Diff>> {
3050 let working_dir_path = buffer.update(cx, |buffer, cx| {
3051 let file = File::from_dyn(buffer.file())?;
3052 let worktree = file.worktree.read(cx);
3053 let mut worktree_path = worktree.abs_path().to_path_buf();
3054 if worktree.root_entry()?.is_file() {
3055 worktree_path.pop();
3056 }
3057 Some(worktree_path)
3058 })?;
3059
3060 let mut child = smol::process::Command::new(command);
3061 #[cfg(target_os = "windows")]
3062 {
3063 use smol::process::windows::CommandExt;
3064 child.creation_flags(windows::Win32::System::Threading::CREATE_NO_WINDOW.0);
3065 }
3066
3067 if let Some(working_dir_path) = working_dir_path {
3068 child.current_dir(working_dir_path);
3069 }
3070
3071 let mut child = child
3072 .args(arguments.iter().map(|arg| {
3073 if let Some(buffer_abs_path) = buffer_abs_path {
3074 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3075 } else {
3076 arg.replace("{buffer_path}", "Untitled")
3077 }
3078 }))
3079 .stdin(smol::process::Stdio::piped())
3080 .stdout(smol::process::Stdio::piped())
3081 .stderr(smol::process::Stdio::piped())
3082 .spawn()?;
3083
3084 let stdin = child
3085 .stdin
3086 .as_mut()
3087 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3088 let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
3089 for chunk in text.chunks() {
3090 stdin.write_all(chunk.as_bytes()).await?;
3091 }
3092 stdin.flush().await?;
3093
3094 let output = child.output().await?;
3095 if !output.status.success() {
3096 return Err(anyhow!(
3097 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3098 output.status.code(),
3099 String::from_utf8_lossy(&output.stdout),
3100 String::from_utf8_lossy(&output.stderr),
3101 ));
3102 }
3103
3104 let stdout = String::from_utf8(output.stdout)?;
3105 Ok(Some(
3106 buffer
3107 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
3108 .await,
3109 ))
3110 }
3111
3112 #[inline(never)]
3113 fn definition_impl(
3114 &self,
3115 buffer: &Model<Buffer>,
3116 position: PointUtf16,
3117 cx: &mut ModelContext<Self>,
3118 ) -> Task<Result<Vec<LocationLink>>> {
3119 self.request_lsp(
3120 buffer.clone(),
3121 LanguageServerToQuery::Primary,
3122 GetDefinition { position },
3123 cx,
3124 )
3125 }
3126 pub fn definition<T: ToPointUtf16>(
3127 &self,
3128 buffer: &Model<Buffer>,
3129 position: T,
3130 cx: &mut ModelContext<Self>,
3131 ) -> Task<Result<Vec<LocationLink>>> {
3132 let position = position.to_point_utf16(buffer.read(cx));
3133 self.definition_impl(buffer, position, cx)
3134 }
3135
3136 fn declaration_impl(
3137 &self,
3138 buffer: &Model<Buffer>,
3139 position: PointUtf16,
3140 cx: &mut ModelContext<Self>,
3141 ) -> Task<Result<Vec<LocationLink>>> {
3142 self.request_lsp(
3143 buffer.clone(),
3144 LanguageServerToQuery::Primary,
3145 GetDeclaration { position },
3146 cx,
3147 )
3148 }
3149
3150 pub fn declaration<T: ToPointUtf16>(
3151 &self,
3152 buffer: &Model<Buffer>,
3153 position: T,
3154 cx: &mut ModelContext<Self>,
3155 ) -> Task<Result<Vec<LocationLink>>> {
3156 let position = position.to_point_utf16(buffer.read(cx));
3157 self.declaration_impl(buffer, position, cx)
3158 }
3159
3160 fn type_definition_impl(
3161 &self,
3162 buffer: &Model<Buffer>,
3163 position: PointUtf16,
3164 cx: &mut ModelContext<Self>,
3165 ) -> Task<Result<Vec<LocationLink>>> {
3166 self.request_lsp(
3167 buffer.clone(),
3168 LanguageServerToQuery::Primary,
3169 GetTypeDefinition { position },
3170 cx,
3171 )
3172 }
3173
3174 pub fn type_definition<T: ToPointUtf16>(
3175 &self,
3176 buffer: &Model<Buffer>,
3177 position: T,
3178 cx: &mut ModelContext<Self>,
3179 ) -> Task<Result<Vec<LocationLink>>> {
3180 let position = position.to_point_utf16(buffer.read(cx));
3181 self.type_definition_impl(buffer, position, cx)
3182 }
3183
3184 pub fn implementation<T: ToPointUtf16>(
3185 &self,
3186 buffer: &Model<Buffer>,
3187 position: T,
3188 cx: &mut ModelContext<Self>,
3189 ) -> Task<Result<Vec<LocationLink>>> {
3190 let position = position.to_point_utf16(buffer.read(cx));
3191 self.request_lsp(
3192 buffer.clone(),
3193 LanguageServerToQuery::Primary,
3194 GetImplementation { position },
3195 cx,
3196 )
3197 }
3198
3199 pub fn references<T: ToPointUtf16>(
3200 &self,
3201 buffer: &Model<Buffer>,
3202 position: T,
3203 cx: &mut ModelContext<Self>,
3204 ) -> Task<Result<Vec<Location>>> {
3205 let position = position.to_point_utf16(buffer.read(cx));
3206 self.request_lsp(
3207 buffer.clone(),
3208 LanguageServerToQuery::Primary,
3209 GetReferences { position },
3210 cx,
3211 )
3212 }
3213
3214 fn document_highlights_impl(
3215 &self,
3216 buffer: &Model<Buffer>,
3217 position: PointUtf16,
3218 cx: &mut ModelContext<Self>,
3219 ) -> Task<Result<Vec<DocumentHighlight>>> {
3220 self.request_lsp(
3221 buffer.clone(),
3222 LanguageServerToQuery::Primary,
3223 GetDocumentHighlights { position },
3224 cx,
3225 )
3226 }
3227
3228 pub fn document_highlights<T: ToPointUtf16>(
3229 &self,
3230 buffer: &Model<Buffer>,
3231 position: T,
3232 cx: &mut ModelContext<Self>,
3233 ) -> Task<Result<Vec<DocumentHighlight>>> {
3234 let position = position.to_point_utf16(buffer.read(cx));
3235 self.document_highlights_impl(buffer, position, cx)
3236 }
3237
3238 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3239 self.lsp_store
3240 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3241 }
3242
3243 pub fn open_buffer_for_symbol(
3244 &mut self,
3245 symbol: &Symbol,
3246 cx: &mut ModelContext<Self>,
3247 ) -> Task<Result<Model<Buffer>>> {
3248 self.lsp_store.update(cx, |lsp_store, cx| {
3249 lsp_store.open_buffer_for_symbol(symbol, cx)
3250 })
3251 }
3252
3253 pub fn open_local_buffer_via_lsp(
3254 &mut self,
3255 abs_path: lsp::Url,
3256 language_server_id: LanguageServerId,
3257 language_server_name: LanguageServerName,
3258 cx: &mut ModelContext<Self>,
3259 ) -> Task<Result<Model<Buffer>>> {
3260 self.lsp_store.update(cx, |lsp_store, cx| {
3261 lsp_store.open_local_buffer_via_lsp(
3262 abs_path,
3263 language_server_id,
3264 language_server_name,
3265 cx,
3266 )
3267 })
3268 }
3269
3270 pub fn signature_help<T: ToPointUtf16>(
3271 &self,
3272 buffer: &Model<Buffer>,
3273 position: T,
3274 cx: &mut ModelContext<Self>,
3275 ) -> Task<Vec<SignatureHelp>> {
3276 self.lsp_store.update(cx, |lsp_store, cx| {
3277 lsp_store.signature_help(buffer, position, cx)
3278 })
3279 }
3280
3281 pub fn hover<T: ToPointUtf16>(
3282 &self,
3283 buffer: &Model<Buffer>,
3284 position: T,
3285 cx: &mut ModelContext<Self>,
3286 ) -> Task<Vec<Hover>> {
3287 let position = position.to_point_utf16(buffer.read(cx));
3288 self.lsp_store
3289 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3290 }
3291
3292 pub fn linked_edit(
3293 &self,
3294 buffer: &Model<Buffer>,
3295 position: Anchor,
3296 cx: &mut ModelContext<Self>,
3297 ) -> Task<Result<Vec<Range<Anchor>>>> {
3298 self.lsp_store.update(cx, |lsp_store, cx| {
3299 lsp_store.linked_edit(buffer, position, cx)
3300 })
3301 }
3302
3303 pub fn completions<T: ToOffset + ToPointUtf16>(
3304 &self,
3305 buffer: &Model<Buffer>,
3306 position: T,
3307 context: CompletionContext,
3308 cx: &mut ModelContext<Self>,
3309 ) -> Task<Result<Vec<Completion>>> {
3310 let position = position.to_point_utf16(buffer.read(cx));
3311 self.lsp_store.update(cx, |lsp_store, cx| {
3312 lsp_store.completions(buffer, position, context, cx)
3313 })
3314 }
3315
3316 pub fn resolve_completions(
3317 &self,
3318 buffer: Model<Buffer>,
3319 completion_indices: Vec<usize>,
3320 completions: Arc<RwLock<Box<[Completion]>>>,
3321 cx: &mut ModelContext<Self>,
3322 ) -> Task<Result<bool>> {
3323 self.lsp_store.update(cx, |lsp_store, cx| {
3324 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
3325 })
3326 }
3327
3328 pub fn apply_additional_edits_for_completion(
3329 &self,
3330 buffer_handle: Model<Buffer>,
3331 completion: Completion,
3332 push_to_history: bool,
3333 cx: &mut ModelContext<Self>,
3334 ) -> Task<Result<Option<Transaction>>> {
3335 self.lsp_store.update(cx, |lsp_store, cx| {
3336 lsp_store.apply_additional_edits_for_completion(
3337 buffer_handle,
3338 completion,
3339 push_to_history,
3340 cx,
3341 )
3342 })
3343 }
3344
3345 pub fn code_actions<T: Clone + ToOffset>(
3346 &mut self,
3347 buffer_handle: &Model<Buffer>,
3348 range: Range<T>,
3349 cx: &mut ModelContext<Self>,
3350 ) -> Task<Vec<CodeAction>> {
3351 let buffer = buffer_handle.read(cx);
3352 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3353 self.lsp_store.update(cx, |lsp_store, cx| {
3354 lsp_store.code_actions(buffer_handle, range, cx)
3355 })
3356 }
3357
3358 pub fn apply_code_action(
3359 &self,
3360 buffer_handle: Model<Buffer>,
3361 action: CodeAction,
3362 push_to_history: bool,
3363 cx: &mut ModelContext<Self>,
3364 ) -> Task<Result<ProjectTransaction>> {
3365 self.lsp_store.update(cx, |lsp_store, cx| {
3366 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3367 })
3368 }
3369
3370 fn prepare_rename_impl(
3371 &mut self,
3372 buffer: Model<Buffer>,
3373 position: PointUtf16,
3374 cx: &mut ModelContext<Self>,
3375 ) -> Task<Result<Option<Range<Anchor>>>> {
3376 self.request_lsp(
3377 buffer,
3378 LanguageServerToQuery::Primary,
3379 PrepareRename { position },
3380 cx,
3381 )
3382 }
3383 pub fn prepare_rename<T: ToPointUtf16>(
3384 &mut self,
3385 buffer: Model<Buffer>,
3386 position: T,
3387 cx: &mut ModelContext<Self>,
3388 ) -> Task<Result<Option<Range<Anchor>>>> {
3389 let position = position.to_point_utf16(buffer.read(cx));
3390 self.prepare_rename_impl(buffer, position, cx)
3391 }
3392
3393 fn perform_rename_impl(
3394 &mut self,
3395 buffer: Model<Buffer>,
3396 position: PointUtf16,
3397 new_name: String,
3398 push_to_history: bool,
3399 cx: &mut ModelContext<Self>,
3400 ) -> Task<Result<ProjectTransaction>> {
3401 let position = position.to_point_utf16(buffer.read(cx));
3402 self.request_lsp(
3403 buffer,
3404 LanguageServerToQuery::Primary,
3405 PerformRename {
3406 position,
3407 new_name,
3408 push_to_history,
3409 },
3410 cx,
3411 )
3412 }
3413 pub fn perform_rename<T: ToPointUtf16>(
3414 &mut self,
3415 buffer: Model<Buffer>,
3416 position: T,
3417 new_name: String,
3418 push_to_history: bool,
3419 cx: &mut ModelContext<Self>,
3420 ) -> Task<Result<ProjectTransaction>> {
3421 let position = position.to_point_utf16(buffer.read(cx));
3422 self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
3423 }
3424
3425 pub fn on_type_format<T: ToPointUtf16>(
3426 &mut self,
3427 buffer: Model<Buffer>,
3428 position: T,
3429 trigger: String,
3430 push_to_history: bool,
3431 cx: &mut ModelContext<Self>,
3432 ) -> Task<Result<Option<Transaction>>> {
3433 self.lsp_store.update(cx, |lsp_store, cx| {
3434 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3435 })
3436 }
3437
3438 pub fn inlay_hints<T: ToOffset>(
3439 &mut self,
3440 buffer_handle: Model<Buffer>,
3441 range: Range<T>,
3442 cx: &mut ModelContext<Self>,
3443 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3444 let buffer = buffer_handle.read(cx);
3445 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3446 self.lsp_store.update(cx, |lsp_store, cx| {
3447 lsp_store.inlay_hints(buffer_handle, range, cx)
3448 })
3449 }
3450
3451 pub fn resolve_inlay_hint(
3452 &self,
3453 hint: InlayHint,
3454 buffer_handle: Model<Buffer>,
3455 server_id: LanguageServerId,
3456 cx: &mut ModelContext<Self>,
3457 ) -> Task<anyhow::Result<InlayHint>> {
3458 self.lsp_store.update(cx, |lsp_store, cx| {
3459 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3460 })
3461 }
3462
3463 pub fn search(
3464 &mut self,
3465 query: SearchQuery,
3466 cx: &mut ModelContext<Self>,
3467 ) -> Receiver<SearchResult> {
3468 let (result_tx, result_rx) = smol::channel::unbounded();
3469
3470 let matching_buffers_rx = if query.is_opened_only() {
3471 self.sort_candidate_buffers(&query, cx)
3472 } else {
3473 self.search_for_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3474 };
3475
3476 cx.spawn(|_, cx| async move {
3477 let mut range_count = 0;
3478 let mut buffer_count = 0;
3479 let mut limit_reached = false;
3480 let query = Arc::new(query);
3481 let mut chunks = matching_buffers_rx.ready_chunks(64);
3482
3483 // Now that we know what paths match the query, we will load at most
3484 // 64 buffers at a time to avoid overwhelming the main thread. For each
3485 // opened buffer, we will spawn a background task that retrieves all the
3486 // ranges in the buffer matched by the query.
3487 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3488 let mut chunk_results = Vec::new();
3489 for buffer in matching_buffer_chunk {
3490 let buffer = buffer.clone();
3491 let query = query.clone();
3492 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
3493 chunk_results.push(cx.background_executor().spawn(async move {
3494 let ranges = query
3495 .search(&snapshot, None)
3496 .await
3497 .iter()
3498 .map(|range| {
3499 snapshot.anchor_before(range.start)
3500 ..snapshot.anchor_after(range.end)
3501 })
3502 .collect::<Vec<_>>();
3503 anyhow::Ok((buffer, ranges))
3504 }));
3505 }
3506
3507 let chunk_results = futures::future::join_all(chunk_results).await;
3508 for result in chunk_results {
3509 if let Some((buffer, ranges)) = result.log_err() {
3510 range_count += ranges.len();
3511 buffer_count += 1;
3512 result_tx
3513 .send(SearchResult::Buffer { buffer, ranges })
3514 .await?;
3515 if buffer_count > MAX_SEARCH_RESULT_FILES
3516 || range_count > MAX_SEARCH_RESULT_RANGES
3517 {
3518 limit_reached = true;
3519 break 'outer;
3520 }
3521 }
3522 }
3523 }
3524
3525 if limit_reached {
3526 result_tx.send(SearchResult::LimitReached).await?;
3527 }
3528
3529 anyhow::Ok(())
3530 })
3531 .detach();
3532
3533 result_rx
3534 }
3535
3536 fn search_for_candidate_buffers(
3537 &mut self,
3538 query: &SearchQuery,
3539 limit: usize,
3540 cx: &mut ModelContext<Project>,
3541 ) -> Receiver<Model<Buffer>> {
3542 if self.is_local() {
3543 let fs = self.fs.clone();
3544 self.buffer_store.update(cx, |buffer_store, cx| {
3545 buffer_store.find_search_candidates(query, limit, fs, cx)
3546 })
3547 } else {
3548 self.search_for_candidate_buffers_remote(query, limit, cx)
3549 }
3550 }
3551
3552 fn sort_candidate_buffers(
3553 &mut self,
3554 search_query: &SearchQuery,
3555 cx: &mut ModelContext<Project>,
3556 ) -> Receiver<Model<Buffer>> {
3557 let worktree_store = self.worktree_store.read(cx);
3558 let mut buffers = search_query
3559 .buffers()
3560 .into_iter()
3561 .flatten()
3562 .filter(|buffer| {
3563 let b = buffer.read(cx);
3564 if let Some(file) = b.file() {
3565 if !search_query.file_matches(file.path()) {
3566 return false;
3567 }
3568 if let Some(entry) = b
3569 .entry_id(cx)
3570 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3571 {
3572 if entry.is_ignored && !search_query.include_ignored() {
3573 return false;
3574 }
3575 }
3576 }
3577 true
3578 })
3579 .collect::<Vec<_>>();
3580 let (tx, rx) = smol::channel::unbounded();
3581 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3582 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3583 (None, Some(_)) => std::cmp::Ordering::Less,
3584 (Some(_), None) => std::cmp::Ordering::Greater,
3585 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3586 });
3587 for buffer in buffers {
3588 tx.send_blocking(buffer.clone()).unwrap()
3589 }
3590
3591 rx
3592 }
3593
3594 fn search_for_candidate_buffers_remote(
3595 &mut self,
3596 query: &SearchQuery,
3597 limit: usize,
3598 cx: &mut ModelContext<Project>,
3599 ) -> Receiver<Model<Buffer>> {
3600 let (tx, rx) = smol::channel::unbounded();
3601
3602 let (client, remote_id): (AnyProtoClient, _) =
3603 if let Some(ssh_session) = self.ssh_session.clone() {
3604 (ssh_session.into(), 0)
3605 } else if let Some(remote_id) = self.remote_id() {
3606 (self.client.clone().into(), remote_id)
3607 } else {
3608 return rx;
3609 };
3610
3611 let request = client.request(proto::FindSearchCandidates {
3612 project_id: remote_id,
3613 query: Some(query.to_proto()),
3614 limit: limit as _,
3615 });
3616 let guard = self.retain_remotely_created_buffers(cx);
3617
3618 cx.spawn(move |this, mut cx| async move {
3619 let response = request.await?;
3620 for buffer_id in response.buffer_ids {
3621 let buffer_id = BufferId::new(buffer_id)?;
3622 let buffer = this
3623 .update(&mut cx, |this, cx| {
3624 this.wait_for_remote_buffer(buffer_id, cx)
3625 })?
3626 .await?;
3627 let _ = tx.send(buffer).await;
3628 }
3629
3630 drop(guard);
3631 anyhow::Ok(())
3632 })
3633 .detach_and_log_err(cx);
3634 rx
3635 }
3636
3637 pub fn request_lsp<R: LspCommand>(
3638 &self,
3639 buffer_handle: Model<Buffer>,
3640 server: LanguageServerToQuery,
3641 request: R,
3642 cx: &mut ModelContext<Self>,
3643 ) -> Task<Result<R::Response>>
3644 where
3645 <R::LspRequest as lsp::request::Request>::Result: Send,
3646 <R::LspRequest as lsp::request::Request>::Params: Send,
3647 {
3648 self.lsp_store.update(cx, |lsp_store, cx| {
3649 lsp_store.request_lsp(buffer_handle, server, request, cx)
3650 })
3651 }
3652
3653 /// Move a worktree to a new position in the worktree order.
3654 ///
3655 /// The worktree will moved to the opposite side of the destination worktree.
3656 ///
3657 /// # Example
3658 ///
3659 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3660 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3661 ///
3662 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3663 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3664 ///
3665 /// # Errors
3666 ///
3667 /// An error will be returned if the worktree or destination worktree are not found.
3668 pub fn move_worktree(
3669 &mut self,
3670 source: WorktreeId,
3671 destination: WorktreeId,
3672 cx: &mut ModelContext<'_, Self>,
3673 ) -> Result<()> {
3674 self.worktree_store.update(cx, |worktree_store, cx| {
3675 worktree_store.move_worktree(source, destination, cx)
3676 })
3677 }
3678
3679 pub fn find_or_create_worktree(
3680 &mut self,
3681 abs_path: impl AsRef<Path>,
3682 visible: bool,
3683 cx: &mut ModelContext<Self>,
3684 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
3685 let abs_path = abs_path.as_ref();
3686 if let Some((tree, relative_path)) = self.find_worktree(abs_path, cx) {
3687 Task::ready(Ok((tree, relative_path)))
3688 } else {
3689 let worktree = self.create_worktree(abs_path, visible, cx);
3690 cx.background_executor()
3691 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
3692 }
3693 }
3694
3695 pub fn find_worktree(
3696 &self,
3697 abs_path: &Path,
3698 cx: &AppContext,
3699 ) -> Option<(Model<Worktree>, PathBuf)> {
3700 self.worktree_store.read_with(cx, |worktree_store, cx| {
3701 worktree_store.find_worktree(abs_path, cx)
3702 })
3703 }
3704
3705 pub fn is_shared(&self) -> bool {
3706 match &self.client_state {
3707 ProjectClientState::Shared { .. } => true,
3708 ProjectClientState::Local => false,
3709 ProjectClientState::Remote { in_room, .. } => *in_room,
3710 }
3711 }
3712
3713 // Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3714 pub fn resolve_existing_file_path(
3715 &self,
3716 path: &str,
3717 buffer: &Model<Buffer>,
3718 cx: &mut ModelContext<Self>,
3719 ) -> Task<Option<ResolvedPath>> {
3720 // TODO: ssh based remoting.
3721 if self.ssh_session.is_some() {
3722 return Task::ready(None);
3723 }
3724
3725 if self.is_local_or_ssh() {
3726 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3727
3728 if expanded.is_absolute() {
3729 let fs = self.fs.clone();
3730 cx.background_executor().spawn(async move {
3731 let path = expanded.as_path();
3732 let exists = fs.is_file(path).await;
3733
3734 exists.then(|| ResolvedPath::AbsPath(expanded))
3735 })
3736 } else {
3737 self.resolve_path_in_worktrees(expanded, buffer, cx)
3738 }
3739 } else {
3740 let path = PathBuf::from(path);
3741 if path.is_absolute() || path.starts_with("~") {
3742 return Task::ready(None);
3743 }
3744
3745 self.resolve_path_in_worktrees(path, buffer, cx)
3746 }
3747 }
3748
3749 fn resolve_path_in_worktrees(
3750 &self,
3751 path: PathBuf,
3752 buffer: &Model<Buffer>,
3753 cx: &mut ModelContext<Self>,
3754 ) -> Task<Option<ResolvedPath>> {
3755 let mut candidates = vec![path.clone()];
3756
3757 if let Some(file) = buffer.read(cx).file() {
3758 if let Some(dir) = file.path().parent() {
3759 let joined = dir.to_path_buf().join(path);
3760 candidates.push(joined);
3761 }
3762 }
3763
3764 let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3765 cx.spawn(|_, mut cx| async move {
3766 for worktree in worktrees {
3767 for candidate in candidates.iter() {
3768 let path = worktree
3769 .update(&mut cx, |worktree, _| {
3770 let root_entry_path = &worktree.root_entry()?.path;
3771
3772 let resolved = resolve_path(root_entry_path, candidate);
3773
3774 let stripped =
3775 resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3776
3777 worktree.entry_for_path(stripped).map(|entry| {
3778 ResolvedPath::ProjectPath(ProjectPath {
3779 worktree_id: worktree.id(),
3780 path: entry.path.clone(),
3781 })
3782 })
3783 })
3784 .ok()?;
3785
3786 if path.is_some() {
3787 return path;
3788 }
3789 }
3790 }
3791 None
3792 })
3793 }
3794
3795 pub fn list_directory(
3796 &self,
3797 query: String,
3798 cx: &mut ModelContext<Self>,
3799 ) -> Task<Result<Vec<PathBuf>>> {
3800 if self.is_local_or_ssh() {
3801 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3802 } else if let Some(dev_server) = self.dev_server_project_id().and_then(|id| {
3803 dev_server_projects::Store::global(cx)
3804 .read(cx)
3805 .dev_server_for_project(id)
3806 }) {
3807 let request = proto::ListRemoteDirectory {
3808 dev_server_id: dev_server.id.0,
3809 path: query,
3810 };
3811 let response = self.client.request(request);
3812 cx.background_executor().spawn(async move {
3813 let response = response.await?;
3814 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3815 })
3816 } else {
3817 Task::ready(Err(anyhow!("cannot list directory in remote project")))
3818 }
3819 }
3820
3821 fn create_worktree(
3822 &mut self,
3823 abs_path: impl AsRef<Path>,
3824 visible: bool,
3825 cx: &mut ModelContext<Self>,
3826 ) -> Task<Result<Model<Worktree>>> {
3827 self.worktree_store.update(cx, |worktree_store, cx| {
3828 worktree_store.create_worktree(abs_path, visible, cx)
3829 })
3830 }
3831
3832 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
3833 self.worktree_store.update(cx, |worktree_store, cx| {
3834 worktree_store.remove_worktree(id_to_remove, cx);
3835 });
3836 }
3837
3838 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
3839 self.worktree_store.update(cx, |worktree_store, cx| {
3840 worktree_store.add(worktree, cx);
3841 });
3842 }
3843
3844 fn update_local_worktree_settings(
3845 &mut self,
3846 worktree: &Model<Worktree>,
3847 changes: &UpdatedEntriesSet,
3848 cx: &mut ModelContext<Self>,
3849 ) {
3850 if worktree.read(cx).is_remote() {
3851 return;
3852 }
3853 let remote_worktree_id = worktree.read(cx).id();
3854
3855 for (path, _, change) in changes.iter() {
3856 let removed = change == &PathChange::Removed;
3857 let abs_path = match worktree.read(cx).absolutize(path) {
3858 Ok(abs_path) => abs_path,
3859 Err(e) => {
3860 log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
3861 continue;
3862 }
3863 };
3864
3865 if path.ends_with(local_tasks_file_relative_path()) {
3866 self.task_inventory().update(cx, |task_inventory, cx| {
3867 if removed {
3868 task_inventory.remove_local_static_source(&abs_path);
3869 } else {
3870 let fs = self.fs.clone();
3871 let task_abs_path = abs_path.clone();
3872 let tasks_file_rx =
3873 watch_config_file(cx.background_executor(), fs, task_abs_path);
3874 task_inventory.add_source(
3875 TaskSourceKind::Worktree {
3876 id: remote_worktree_id,
3877 abs_path,
3878 id_base: "local_tasks_for_worktree".into(),
3879 },
3880 |tx, cx| StaticSource::new(TrackedFile::new(tasks_file_rx, tx, cx)),
3881 cx,
3882 );
3883 }
3884 })
3885 } else if path.ends_with(local_vscode_tasks_file_relative_path()) {
3886 self.task_inventory().update(cx, |task_inventory, cx| {
3887 if removed {
3888 task_inventory.remove_local_static_source(&abs_path);
3889 } else {
3890 let fs = self.fs.clone();
3891 let task_abs_path = abs_path.clone();
3892 let tasks_file_rx =
3893 watch_config_file(cx.background_executor(), fs, task_abs_path);
3894 task_inventory.add_source(
3895 TaskSourceKind::Worktree {
3896 id: remote_worktree_id,
3897 abs_path,
3898 id_base: "local_vscode_tasks_for_worktree".into(),
3899 },
3900 |tx, cx| {
3901 StaticSource::new(TrackedFile::new_convertible::<
3902 task::VsCodeTaskFile,
3903 >(
3904 tasks_file_rx, tx, cx
3905 ))
3906 },
3907 cx,
3908 );
3909 }
3910 })
3911 }
3912 }
3913 }
3914
3915 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
3916 let new_active_entry = entry.and_then(|project_path| {
3917 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3918 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3919 Some(entry.id)
3920 });
3921 if new_active_entry != self.active_entry {
3922 self.active_entry = new_active_entry;
3923 self.lsp_store.update(cx, |lsp_store, _| {
3924 lsp_store.set_active_entry(new_active_entry);
3925 });
3926 cx.emit(Event::ActiveEntryChanged(new_active_entry));
3927 }
3928 }
3929
3930 pub fn language_servers_running_disk_based_diagnostics<'a>(
3931 &'a self,
3932 cx: &'a AppContext,
3933 ) -> impl Iterator<Item = LanguageServerId> + 'a {
3934 self.lsp_store
3935 .read(cx)
3936 .language_servers_running_disk_based_diagnostics()
3937 }
3938
3939 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
3940 let mut summary = DiagnosticSummary::default();
3941 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
3942 summary.error_count += path_summary.error_count;
3943 summary.warning_count += path_summary.warning_count;
3944 }
3945 summary
3946 }
3947
3948 pub fn diagnostic_summaries<'a>(
3949 &'a self,
3950 include_ignored: bool,
3951 cx: &'a AppContext,
3952 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3953 self.lsp_store
3954 .read(cx)
3955 .diagnostic_summaries(include_ignored, cx)
3956 }
3957
3958 pub fn active_entry(&self) -> Option<ProjectEntryId> {
3959 self.active_entry
3960 }
3961
3962 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
3963 self.worktree_store.read(cx).entry_for_path(path, cx)
3964 }
3965
3966 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
3967 let worktree = self.worktree_for_entry(entry_id, cx)?;
3968 let worktree = worktree.read(cx);
3969 let worktree_id = worktree.id();
3970 let path = worktree.entry_for_id(entry_id)?.path.clone();
3971 Some(ProjectPath { worktree_id, path })
3972 }
3973
3974 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
3975 let workspace_root = self
3976 .worktree_for_id(project_path.worktree_id, cx)?
3977 .read(cx)
3978 .abs_path();
3979 let project_path = project_path.path.as_ref();
3980
3981 Some(if project_path == Path::new("") {
3982 workspace_root.to_path_buf()
3983 } else {
3984 workspace_root.join(project_path)
3985 })
3986 }
3987
3988 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3989 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3990 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3991 /// the first visible worktree that has an entry for that relative path.
3992 ///
3993 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3994 /// root name from paths.
3995 ///
3996 /// # Arguments
3997 ///
3998 /// * `path` - A full path that starts with a worktree root name, or alternatively a
3999 /// relative path within a visible worktree.
4000 /// * `cx` - A reference to the `AppContext`.
4001 ///
4002 /// # Returns
4003 ///
4004 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4005 pub fn find_project_path(&self, path: &Path, cx: &AppContext) -> Option<ProjectPath> {
4006 let worktree_store = self.worktree_store.read(cx);
4007
4008 for worktree in worktree_store.visible_worktrees(cx) {
4009 let worktree_root_name = worktree.read(cx).root_name();
4010 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4011 return Some(ProjectPath {
4012 worktree_id: worktree.read(cx).id(),
4013 path: relative_path.into(),
4014 });
4015 }
4016 }
4017
4018 for worktree in worktree_store.visible_worktrees(cx) {
4019 let worktree = worktree.read(cx);
4020 if let Some(entry) = worktree.entry_for_path(path) {
4021 return Some(ProjectPath {
4022 worktree_id: worktree.id(),
4023 path: entry.path.clone(),
4024 });
4025 }
4026 }
4027
4028 None
4029 }
4030
4031 pub fn get_workspace_root(
4032 &self,
4033 project_path: &ProjectPath,
4034 cx: &AppContext,
4035 ) -> Option<PathBuf> {
4036 Some(
4037 self.worktree_for_id(project_path.worktree_id, cx)?
4038 .read(cx)
4039 .abs_path()
4040 .to_path_buf(),
4041 )
4042 }
4043
4044 pub fn get_repo(
4045 &self,
4046 project_path: &ProjectPath,
4047 cx: &AppContext,
4048 ) -> Option<Arc<dyn GitRepository>> {
4049 self.worktree_for_id(project_path.worktree_id, cx)?
4050 .read(cx)
4051 .as_local()?
4052 .local_git_repo(&project_path.path)
4053 }
4054
4055 pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
4056 let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
4057 let root_entry = worktree.root_git_entry()?;
4058 worktree.get_local_repo(&root_entry)?.repo().clone().into()
4059 }
4060
4061 pub fn blame_buffer(
4062 &self,
4063 buffer: &Model<Buffer>,
4064 version: Option<clock::Global>,
4065 cx: &AppContext,
4066 ) -> Task<Result<Blame>> {
4067 self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
4068 }
4069
4070 // RPC message handlers
4071
4072 async fn handle_unshare_project(
4073 this: Model<Self>,
4074 _: TypedEnvelope<proto::UnshareProject>,
4075 mut cx: AsyncAppContext,
4076 ) -> Result<()> {
4077 this.update(&mut cx, |this, cx| {
4078 if this.is_local_or_ssh() {
4079 this.unshare(cx)?;
4080 } else {
4081 this.disconnected_from_host(cx);
4082 }
4083 Ok(())
4084 })?
4085 }
4086
4087 async fn handle_add_collaborator(
4088 this: Model<Self>,
4089 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4090 mut cx: AsyncAppContext,
4091 ) -> Result<()> {
4092 let collaborator = envelope
4093 .payload
4094 .collaborator
4095 .take()
4096 .ok_or_else(|| anyhow!("empty collaborator"))?;
4097
4098 let collaborator = Collaborator::from_proto(collaborator)?;
4099 this.update(&mut cx, |this, cx| {
4100 this.buffer_store.update(cx, |buffer_store, _| {
4101 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4102 });
4103 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4104 this.collaborators
4105 .insert(collaborator.peer_id, collaborator);
4106 cx.notify();
4107 })?;
4108
4109 Ok(())
4110 }
4111
4112 async fn handle_update_project_collaborator(
4113 this: Model<Self>,
4114 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4115 mut cx: AsyncAppContext,
4116 ) -> Result<()> {
4117 let old_peer_id = envelope
4118 .payload
4119 .old_peer_id
4120 .ok_or_else(|| anyhow!("missing old peer id"))?;
4121 let new_peer_id = envelope
4122 .payload
4123 .new_peer_id
4124 .ok_or_else(|| anyhow!("missing new peer id"))?;
4125 this.update(&mut cx, |this, cx| {
4126 let collaborator = this
4127 .collaborators
4128 .remove(&old_peer_id)
4129 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4130 let is_host = collaborator.replica_id == 0;
4131 this.collaborators.insert(new_peer_id, collaborator);
4132
4133 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4134 this.buffer_store.update(cx, |buffer_store, _| {
4135 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4136 });
4137
4138 if is_host {
4139 this.buffer_store
4140 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4141 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4142 .unwrap();
4143 cx.emit(Event::HostReshared);
4144 }
4145
4146 cx.emit(Event::CollaboratorUpdated {
4147 old_peer_id,
4148 new_peer_id,
4149 });
4150 cx.notify();
4151 Ok(())
4152 })?
4153 }
4154
4155 async fn handle_remove_collaborator(
4156 this: Model<Self>,
4157 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4158 mut cx: AsyncAppContext,
4159 ) -> Result<()> {
4160 this.update(&mut cx, |this, cx| {
4161 let peer_id = envelope
4162 .payload
4163 .peer_id
4164 .ok_or_else(|| anyhow!("invalid peer id"))?;
4165 let replica_id = this
4166 .collaborators
4167 .remove(&peer_id)
4168 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4169 .replica_id;
4170 this.buffer_store.update(cx, |buffer_store, cx| {
4171 buffer_store.forget_shared_buffers_for(&peer_id);
4172 for buffer in buffer_store.buffers() {
4173 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4174 }
4175 });
4176
4177 cx.emit(Event::CollaboratorLeft(peer_id));
4178 cx.notify();
4179 Ok(())
4180 })?
4181 }
4182
4183 async fn handle_update_project(
4184 this: Model<Self>,
4185 envelope: TypedEnvelope<proto::UpdateProject>,
4186 mut cx: AsyncAppContext,
4187 ) -> Result<()> {
4188 this.update(&mut cx, |this, cx| {
4189 // Don't handle messages that were sent before the response to us joining the project
4190 if envelope.message_id > this.join_project_response_message_id {
4191 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4192 }
4193 Ok(())
4194 })?
4195 }
4196
4197 async fn handle_update_worktree(
4198 this: Model<Self>,
4199 envelope: TypedEnvelope<proto::UpdateWorktree>,
4200 mut cx: AsyncAppContext,
4201 ) -> Result<()> {
4202 this.update(&mut cx, |this, cx| {
4203 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4204 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4205 worktree.update(cx, |worktree, _| {
4206 let worktree = worktree.as_remote_mut().unwrap();
4207 worktree.update_from_remote(envelope.payload);
4208 });
4209 }
4210 Ok(())
4211 })?
4212 }
4213
4214 async fn handle_update_buffer(
4215 this: Model<Self>,
4216 envelope: TypedEnvelope<proto::UpdateBuffer>,
4217 cx: AsyncAppContext,
4218 ) -> Result<proto::Ack> {
4219 let buffer_store = this.read_with(&cx, |this, cx| {
4220 if let Some(ssh) = &this.ssh_session {
4221 let mut payload = envelope.payload.clone();
4222 payload.project_id = 0;
4223 cx.background_executor()
4224 .spawn(ssh.request(payload))
4225 .detach_and_log_err(cx);
4226 }
4227 this.buffer_store.clone()
4228 })?;
4229 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4230 }
4231
4232 fn retain_remotely_created_buffers(
4233 &mut self,
4234 cx: &mut ModelContext<Self>,
4235 ) -> RemotelyCreatedBufferGuard {
4236 {
4237 let mut remotely_created_buffers = self.remotely_created_buffers.lock();
4238 if remotely_created_buffers.retain_count == 0 {
4239 remotely_created_buffers.buffers = self.buffer_store.read(cx).buffers().collect();
4240 }
4241 remotely_created_buffers.retain_count += 1;
4242 }
4243 RemotelyCreatedBufferGuard {
4244 remote_buffers: Arc::downgrade(&self.remotely_created_buffers),
4245 }
4246 }
4247
4248 async fn handle_create_buffer_for_peer(
4249 this: Model<Self>,
4250 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4251 mut cx: AsyncAppContext,
4252 ) -> Result<()> {
4253 this.update(&mut cx, |this, cx| {
4254 this.buffer_store.update(cx, |buffer_store, cx| {
4255 buffer_store.handle_create_buffer_for_peer(
4256 envelope,
4257 this.replica_id(),
4258 this.capability(),
4259 cx,
4260 )
4261 })
4262 })?
4263 }
4264
4265 async fn handle_reload_buffers(
4266 this: Model<Self>,
4267 envelope: TypedEnvelope<proto::ReloadBuffers>,
4268 mut cx: AsyncAppContext,
4269 ) -> Result<proto::ReloadBuffersResponse> {
4270 let sender_id = envelope.original_sender_id()?;
4271 let reload = this.update(&mut cx, |this, cx| {
4272 let mut buffers = HashSet::default();
4273 for buffer_id in &envelope.payload.buffer_ids {
4274 let buffer_id = BufferId::new(*buffer_id)?;
4275 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
4276 }
4277 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
4278 })??;
4279
4280 let project_transaction = reload.await?;
4281 let project_transaction = this.update(&mut cx, |this, cx| {
4282 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4283 })?;
4284 Ok(proto::ReloadBuffersResponse {
4285 transaction: Some(project_transaction),
4286 })
4287 }
4288
4289 async fn handle_synchronize_buffers(
4290 this: Model<Self>,
4291 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4292 mut cx: AsyncAppContext,
4293 ) -> Result<proto::SynchronizeBuffersResponse> {
4294 let response = this.update(&mut cx, |this, cx| {
4295 let client = this.client.clone();
4296 this.buffer_store.update(cx, |this, cx| {
4297 this.handle_synchronize_buffers(envelope, cx, client)
4298 })
4299 })??;
4300
4301 Ok(response)
4302 }
4303
4304 async fn handle_format_buffers(
4305 this: Model<Self>,
4306 envelope: TypedEnvelope<proto::FormatBuffers>,
4307 mut cx: AsyncAppContext,
4308 ) -> Result<proto::FormatBuffersResponse> {
4309 let sender_id = envelope.original_sender_id()?;
4310 let format = this.update(&mut cx, |this, cx| {
4311 let mut buffers = HashSet::default();
4312 for buffer_id in &envelope.payload.buffer_ids {
4313 let buffer_id = BufferId::new(*buffer_id)?;
4314 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
4315 }
4316 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
4317 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
4318 })??;
4319
4320 let project_transaction = format.await?;
4321 let project_transaction = this.update(&mut cx, |this, cx| {
4322 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4323 })?;
4324 Ok(proto::FormatBuffersResponse {
4325 transaction: Some(project_transaction),
4326 })
4327 }
4328
4329 async fn handle_task_context_for_location(
4330 project: Model<Self>,
4331 envelope: TypedEnvelope<proto::TaskContextForLocation>,
4332 mut cx: AsyncAppContext,
4333 ) -> Result<proto::TaskContext> {
4334 let location = envelope
4335 .payload
4336 .location
4337 .context("no location given for task context handling")?;
4338 let location = cx
4339 .update(|cx| deserialize_location(&project, location, cx))?
4340 .await?;
4341 let context_task = project.update(&mut cx, |project, cx| {
4342 let captured_variables = {
4343 let mut variables = TaskVariables::default();
4344 for range in location
4345 .buffer
4346 .read(cx)
4347 .snapshot()
4348 .runnable_ranges(location.range.clone())
4349 {
4350 for (capture_name, value) in range.extra_captures {
4351 variables.insert(VariableName::Custom(capture_name.into()), value);
4352 }
4353 }
4354 variables
4355 };
4356 project.task_context_for_location(captured_variables, location, cx)
4357 })?;
4358 let task_context = context_task.await.unwrap_or_default();
4359 Ok(proto::TaskContext {
4360 project_env: task_context.project_env.into_iter().collect(),
4361 cwd: task_context
4362 .cwd
4363 .map(|cwd| cwd.to_string_lossy().to_string()),
4364 task_variables: task_context
4365 .task_variables
4366 .into_iter()
4367 .map(|(variable_name, variable_value)| (variable_name.to_string(), variable_value))
4368 .collect(),
4369 })
4370 }
4371
4372 async fn handle_task_templates(
4373 project: Model<Self>,
4374 envelope: TypedEnvelope<proto::TaskTemplates>,
4375 mut cx: AsyncAppContext,
4376 ) -> Result<proto::TaskTemplatesResponse> {
4377 let worktree = envelope.payload.worktree_id.map(WorktreeId::from_proto);
4378 let location = match envelope.payload.location {
4379 Some(location) => Some(
4380 cx.update(|cx| deserialize_location(&project, location, cx))?
4381 .await
4382 .context("task templates request location deserializing")?,
4383 ),
4384 None => None,
4385 };
4386
4387 let templates = project
4388 .update(&mut cx, |project, cx| {
4389 project.task_templates(worktree, location, cx)
4390 })?
4391 .await
4392 .context("receiving task templates")?
4393 .into_iter()
4394 .map(|(kind, template)| {
4395 let kind = Some(match kind {
4396 TaskSourceKind::UserInput => proto::task_source_kind::Kind::UserInput(
4397 proto::task_source_kind::UserInput {},
4398 ),
4399 TaskSourceKind::Worktree {
4400 id,
4401 abs_path,
4402 id_base,
4403 } => {
4404 proto::task_source_kind::Kind::Worktree(proto::task_source_kind::Worktree {
4405 id: id.to_proto(),
4406 abs_path: abs_path.to_string_lossy().to_string(),
4407 id_base: id_base.to_string(),
4408 })
4409 }
4410 TaskSourceKind::AbsPath { id_base, abs_path } => {
4411 proto::task_source_kind::Kind::AbsPath(proto::task_source_kind::AbsPath {
4412 abs_path: abs_path.to_string_lossy().to_string(),
4413 id_base: id_base.to_string(),
4414 })
4415 }
4416 TaskSourceKind::Language { name } => {
4417 proto::task_source_kind::Kind::Language(proto::task_source_kind::Language {
4418 name: name.to_string(),
4419 })
4420 }
4421 });
4422 let kind = Some(proto::TaskSourceKind { kind });
4423 let template = Some(proto::TaskTemplate {
4424 label: template.label,
4425 command: template.command,
4426 args: template.args,
4427 env: template.env.into_iter().collect(),
4428 cwd: template.cwd,
4429 use_new_terminal: template.use_new_terminal,
4430 allow_concurrent_runs: template.allow_concurrent_runs,
4431 reveal: match template.reveal {
4432 RevealStrategy::Always => proto::RevealStrategy::RevealAlways as i32,
4433 RevealStrategy::Never => proto::RevealStrategy::RevealNever as i32,
4434 },
4435 hide: match template.hide {
4436 HideStrategy::Always => proto::HideStrategy::HideAlways as i32,
4437 HideStrategy::Never => proto::HideStrategy::HideNever as i32,
4438 HideStrategy::OnSuccess => proto::HideStrategy::HideOnSuccess as i32,
4439 },
4440 shell: Some(proto::Shell {
4441 shell_type: Some(match template.shell {
4442 Shell::System => proto::shell::ShellType::System(proto::System {}),
4443 Shell::Program(program) => proto::shell::ShellType::Program(program),
4444 Shell::WithArguments { program, args } => {
4445 proto::shell::ShellType::WithArguments(
4446 proto::shell::WithArguments { program, args },
4447 )
4448 }
4449 }),
4450 }),
4451 tags: template.tags,
4452 });
4453 proto::TemplatePair { kind, template }
4454 })
4455 .collect();
4456
4457 Ok(proto::TaskTemplatesResponse { templates })
4458 }
4459
4460 async fn handle_search_project(
4461 this: Model<Self>,
4462 envelope: TypedEnvelope<proto::SearchProject>,
4463 mut cx: AsyncAppContext,
4464 ) -> Result<proto::SearchProjectResponse> {
4465 let peer_id = envelope.original_sender_id()?;
4466 let query = SearchQuery::from_proto_v1(envelope.payload)?;
4467 let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
4468
4469 cx.spawn(move |mut cx| async move {
4470 let mut locations = Vec::new();
4471 let mut limit_reached = false;
4472 while let Some(result) = result.next().await {
4473 match result {
4474 SearchResult::Buffer { buffer, ranges } => {
4475 for range in ranges {
4476 let start = serialize_anchor(&range.start);
4477 let end = serialize_anchor(&range.end);
4478 let buffer_id = this.update(&mut cx, |this, cx| {
4479 this.create_buffer_for_peer(&buffer, peer_id, cx).into()
4480 })?;
4481 locations.push(proto::Location {
4482 buffer_id,
4483 start: Some(start),
4484 end: Some(end),
4485 });
4486 }
4487 }
4488 SearchResult::LimitReached => limit_reached = true,
4489 }
4490 }
4491 Ok(proto::SearchProjectResponse {
4492 locations,
4493 limit_reached,
4494 // will restart
4495 })
4496 })
4497 .await
4498 }
4499
4500 async fn handle_search_candidate_buffers(
4501 this: Model<Self>,
4502 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4503 mut cx: AsyncAppContext,
4504 ) -> Result<proto::FindSearchCandidatesResponse> {
4505 let peer_id = envelope.original_sender_id()?;
4506 let message = envelope.payload;
4507 let query = SearchQuery::from_proto(
4508 message
4509 .query
4510 .ok_or_else(|| anyhow!("missing query field"))?,
4511 )?;
4512 let mut results = this.update(&mut cx, |this, cx| {
4513 this.search_for_candidate_buffers(&query, message.limit as _, cx)
4514 })?;
4515
4516 let mut response = proto::FindSearchCandidatesResponse {
4517 buffer_ids: Vec::new(),
4518 };
4519
4520 while let Some(buffer) = results.next().await {
4521 this.update(&mut cx, |this, cx| {
4522 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4523 response.buffer_ids.push(buffer_id.to_proto());
4524 })?;
4525 }
4526
4527 Ok(response)
4528 }
4529
4530 async fn handle_open_buffer_by_id(
4531 this: Model<Self>,
4532 envelope: TypedEnvelope<proto::OpenBufferById>,
4533 mut cx: AsyncAppContext,
4534 ) -> Result<proto::OpenBufferResponse> {
4535 let peer_id = envelope.original_sender_id()?;
4536 let buffer_id = BufferId::new(envelope.payload.id)?;
4537 let buffer = this
4538 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4539 .await?;
4540 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4541 }
4542
4543 async fn handle_open_buffer_by_path(
4544 this: Model<Self>,
4545 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4546 mut cx: AsyncAppContext,
4547 ) -> Result<proto::OpenBufferResponse> {
4548 let peer_id = envelope.original_sender_id()?;
4549 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4550 let open_buffer = this.update(&mut cx, |this, cx| {
4551 this.open_buffer(
4552 ProjectPath {
4553 worktree_id,
4554 path: PathBuf::from(envelope.payload.path).into(),
4555 },
4556 cx,
4557 )
4558 })?;
4559
4560 let buffer = open_buffer.await?;
4561 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4562 }
4563
4564 async fn handle_open_new_buffer(
4565 this: Model<Self>,
4566 envelope: TypedEnvelope<proto::OpenNewBuffer>,
4567 mut cx: AsyncAppContext,
4568 ) -> Result<proto::OpenBufferResponse> {
4569 let buffer = this.update(&mut cx, |this, cx| this.create_local_buffer("", None, cx))?;
4570 let peer_id = envelope.original_sender_id()?;
4571
4572 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4573 }
4574
4575 fn respond_to_open_buffer_request(
4576 this: Model<Self>,
4577 buffer: Model<Buffer>,
4578 peer_id: proto::PeerId,
4579 cx: &mut AsyncAppContext,
4580 ) -> Result<proto::OpenBufferResponse> {
4581 this.update(cx, |this, cx| {
4582 let is_private = buffer
4583 .read(cx)
4584 .file()
4585 .map(|f| f.is_private())
4586 .unwrap_or_default();
4587 if is_private {
4588 Err(anyhow!(ErrorCode::UnsharedItem))
4589 } else {
4590 Ok(proto::OpenBufferResponse {
4591 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4592 })
4593 }
4594 })?
4595 }
4596
4597 fn serialize_project_transaction_for_peer(
4598 &mut self,
4599 project_transaction: ProjectTransaction,
4600 peer_id: proto::PeerId,
4601 cx: &mut AppContext,
4602 ) -> proto::ProjectTransaction {
4603 self.buffer_store.update(cx, |buffer_store, cx| {
4604 buffer_store.serialize_project_transaction_for_peer(project_transaction, peer_id, cx)
4605 })
4606 }
4607
4608 fn create_buffer_for_peer(
4609 &mut self,
4610 buffer: &Model<Buffer>,
4611 peer_id: proto::PeerId,
4612 cx: &mut AppContext,
4613 ) -> BufferId {
4614 self.buffer_store
4615 .update(cx, |buffer_store, cx| {
4616 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4617 })
4618 .detach_and_log_err(cx);
4619 buffer.read(cx).remote_id()
4620 }
4621
4622 fn wait_for_remote_buffer(
4623 &mut self,
4624 id: BufferId,
4625 cx: &mut ModelContext<Self>,
4626 ) -> Task<Result<Model<Buffer>>> {
4627 self.buffer_store.update(cx, |buffer_store, cx| {
4628 buffer_store.wait_for_remote_buffer(id, cx)
4629 })
4630 }
4631
4632 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
4633 let project_id = match self.client_state {
4634 ProjectClientState::Remote {
4635 sharing_has_stopped,
4636 remote_id,
4637 ..
4638 } => {
4639 if sharing_has_stopped {
4640 return Task::ready(Err(anyhow!(
4641 "can't synchronize remote buffers on a readonly project"
4642 )));
4643 } else {
4644 remote_id
4645 }
4646 }
4647 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4648 return Task::ready(Err(anyhow!(
4649 "can't synchronize remote buffers on a local project"
4650 )))
4651 }
4652 };
4653
4654 let client = self.client.clone();
4655 cx.spawn(move |this, mut cx| async move {
4656 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
4657 this.buffer_store.read(cx).buffer_version_info(cx)
4658 })?;
4659 let response = client
4660 .request(proto::SynchronizeBuffers {
4661 project_id,
4662 buffers,
4663 })
4664 .await?;
4665
4666 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
4667 response
4668 .buffers
4669 .into_iter()
4670 .map(|buffer| {
4671 let client = client.clone();
4672 let buffer_id = match BufferId::new(buffer.id) {
4673 Ok(id) => id,
4674 Err(e) => {
4675 return Task::ready(Err(e));
4676 }
4677 };
4678 let remote_version = language::proto::deserialize_version(&buffer.version);
4679 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4680 let operations =
4681 buffer.read(cx).serialize_ops(Some(remote_version), cx);
4682 cx.background_executor().spawn(async move {
4683 let operations = operations.await;
4684 for chunk in split_operations(operations) {
4685 client
4686 .request(proto::UpdateBuffer {
4687 project_id,
4688 buffer_id: buffer_id.into(),
4689 operations: chunk,
4690 })
4691 .await?;
4692 }
4693 anyhow::Ok(())
4694 })
4695 } else {
4696 Task::ready(Ok(()))
4697 }
4698 })
4699 .collect::<Vec<_>>()
4700 })?;
4701
4702 // Any incomplete buffers have open requests waiting. Request that the host sends
4703 // creates these buffers for us again to unblock any waiting futures.
4704 for id in incomplete_buffer_ids {
4705 cx.background_executor()
4706 .spawn(client.request(proto::OpenBufferById {
4707 project_id,
4708 id: id.into(),
4709 }))
4710 .detach();
4711 }
4712
4713 futures::future::join_all(send_updates_for_buffers)
4714 .await
4715 .into_iter()
4716 .collect()
4717 })
4718 }
4719
4720 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
4721 self.worktrees(cx)
4722 .map(|worktree| {
4723 let worktree = worktree.read(cx);
4724 proto::WorktreeMetadata {
4725 id: worktree.id().to_proto(),
4726 root_name: worktree.root_name().into(),
4727 visible: worktree.is_visible(),
4728 abs_path: worktree.abs_path().to_string_lossy().into(),
4729 }
4730 })
4731 .collect()
4732 }
4733
4734 fn set_worktrees_from_proto(
4735 &mut self,
4736 worktrees: Vec<proto::WorktreeMetadata>,
4737 cx: &mut ModelContext<Project>,
4738 ) -> Result<()> {
4739 self.metadata_changed(cx);
4740 self.worktree_store.update(cx, |worktree_store, cx| {
4741 worktree_store.set_worktrees_from_proto(
4742 worktrees,
4743 self.replica_id(),
4744 self.remote_id().ok_or_else(|| anyhow!("invalid project"))?,
4745 self.client.clone().into(),
4746 cx,
4747 )
4748 })
4749 }
4750
4751 fn set_collaborators_from_proto(
4752 &mut self,
4753 messages: Vec<proto::Collaborator>,
4754 cx: &mut ModelContext<Self>,
4755 ) -> Result<()> {
4756 let mut collaborators = HashMap::default();
4757 for message in messages {
4758 let collaborator = Collaborator::from_proto(message)?;
4759 collaborators.insert(collaborator.peer_id, collaborator);
4760 }
4761 for old_peer_id in self.collaborators.keys() {
4762 if !collaborators.contains_key(old_peer_id) {
4763 cx.emit(Event::CollaboratorLeft(*old_peer_id));
4764 }
4765 }
4766 self.collaborators = collaborators;
4767 Ok(())
4768 }
4769
4770 pub fn language_servers<'a>(
4771 &'a self,
4772 cx: &'a AppContext,
4773 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
4774 self.lsp_store.read(cx).language_servers()
4775 }
4776
4777 pub fn supplementary_language_servers<'a>(
4778 &'a self,
4779 cx: &'a AppContext,
4780 ) -> impl '_ + Iterator<Item = (&'a LanguageServerId, &'a LanguageServerName)> {
4781 self.lsp_store.read(cx).supplementary_language_servers()
4782 }
4783
4784 pub fn language_server_adapter_for_id(
4785 &self,
4786 id: LanguageServerId,
4787 cx: &AppContext,
4788 ) -> Option<Arc<CachedLspAdapter>> {
4789 self.lsp_store.read(cx).language_server_adapter_for_id(id)
4790 }
4791
4792 pub fn language_server_for_id(
4793 &self,
4794 id: LanguageServerId,
4795 cx: &AppContext,
4796 ) -> Option<Arc<LanguageServer>> {
4797 self.lsp_store.read(cx).language_server_for_id(id)
4798 }
4799
4800 pub fn language_servers_for_buffer<'a>(
4801 &'a self,
4802 buffer: &'a Buffer,
4803 cx: &'a AppContext,
4804 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4805 self.lsp_store
4806 .read(cx)
4807 .language_servers_for_buffer(buffer, cx)
4808 }
4809
4810 pub fn language_server_for_buffer<'a>(
4811 &'a self,
4812 buffer: &'a Buffer,
4813 server_id: LanguageServerId,
4814 cx: &'a AppContext,
4815 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4816 self.lsp_store
4817 .read(cx)
4818 .language_server_for_buffer(buffer, server_id, cx)
4819 }
4820
4821 pub fn task_context_for_location(
4822 &self,
4823 captured_variables: TaskVariables,
4824 location: Location,
4825 cx: &mut ModelContext<'_, Project>,
4826 ) -> Task<Option<TaskContext>> {
4827 if self.is_local_or_ssh() {
4828 let (worktree_id, worktree_abs_path) = if let Some(worktree) = self.task_worktree(cx) {
4829 (
4830 Some(worktree.read(cx).id()),
4831 Some(worktree.read(cx).abs_path()),
4832 )
4833 } else {
4834 (None, None)
4835 };
4836
4837 cx.spawn(|project, mut cx| async move {
4838 let mut task_variables = cx
4839 .update(|cx| {
4840 combine_task_variables(
4841 captured_variables,
4842 location,
4843 BasicContextProvider::new(project.upgrade()?),
4844 cx,
4845 )
4846 .log_err()
4847 })
4848 .ok()
4849 .flatten()?;
4850 // Remove all custom entries starting with _, as they're not intended for use by the end user.
4851 task_variables.sweep();
4852
4853 let project_env = project
4854 .update(&mut cx, |project, cx| {
4855 let worktree_abs_path = worktree_abs_path.clone();
4856 project.environment.update(cx, |environment, cx| {
4857 environment.get_environment(worktree_id, worktree_abs_path, cx)
4858 })
4859 })
4860 .ok()?
4861 .await;
4862
4863 Some(TaskContext {
4864 project_env: project_env.unwrap_or_default(),
4865 cwd: worktree_abs_path.map(|p| p.to_path_buf()),
4866 task_variables,
4867 })
4868 })
4869 } else if let Some(project_id) = self
4870 .remote_id()
4871 .filter(|_| self.ssh_connection_string(cx).is_some())
4872 {
4873 let task_context = self.client().request(proto::TaskContextForLocation {
4874 project_id,
4875 location: Some(proto::Location {
4876 buffer_id: location.buffer.read(cx).remote_id().into(),
4877 start: Some(serialize_anchor(&location.range.start)),
4878 end: Some(serialize_anchor(&location.range.end)),
4879 }),
4880 });
4881 cx.background_executor().spawn(async move {
4882 let task_context = task_context.await.log_err()?;
4883 Some(TaskContext {
4884 project_env: task_context.project_env.into_iter().collect(),
4885 cwd: task_context.cwd.map(PathBuf::from),
4886 task_variables: task_context
4887 .task_variables
4888 .into_iter()
4889 .filter_map(
4890 |(variable_name, variable_value)| match variable_name.parse() {
4891 Ok(variable_name) => Some((variable_name, variable_value)),
4892 Err(()) => {
4893 log::error!("Unknown variable name: {variable_name}");
4894 None
4895 }
4896 },
4897 )
4898 .collect(),
4899 })
4900 })
4901 } else {
4902 Task::ready(None)
4903 }
4904 }
4905
4906 pub fn task_templates(
4907 &self,
4908 worktree: Option<WorktreeId>,
4909 location: Option<Location>,
4910 cx: &mut ModelContext<Self>,
4911 ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
4912 if self.is_local_or_ssh() {
4913 let (file, language) = location
4914 .map(|location| {
4915 let buffer = location.buffer.read(cx);
4916 (
4917 buffer.file().cloned(),
4918 buffer.language_at(location.range.start),
4919 )
4920 })
4921 .unwrap_or_default();
4922 Task::ready(Ok(self
4923 .task_inventory()
4924 .read(cx)
4925 .list_tasks(file, language, worktree, cx)))
4926 } else if let Some(project_id) = self
4927 .remote_id()
4928 .filter(|_| self.ssh_connection_string(cx).is_some())
4929 {
4930 let remote_templates =
4931 self.query_remote_task_templates(project_id, worktree, location.as_ref(), cx);
4932 cx.background_executor().spawn(remote_templates)
4933 } else {
4934 Task::ready(Ok(Vec::new()))
4935 }
4936 }
4937
4938 pub fn query_remote_task_templates(
4939 &self,
4940 project_id: u64,
4941 worktree: Option<WorktreeId>,
4942 location: Option<&Location>,
4943 cx: &AppContext,
4944 ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
4945 let client = self.client();
4946 let location = location.map(|location| serialize_location(location, cx));
4947 cx.spawn(|_| async move {
4948 let response = client
4949 .request(proto::TaskTemplates {
4950 project_id,
4951 worktree_id: worktree.map(|id| id.to_proto()),
4952 location,
4953 })
4954 .await?;
4955
4956 Ok(response
4957 .templates
4958 .into_iter()
4959 .filter_map(|template_pair| {
4960 let task_source_kind = match template_pair.kind?.kind? {
4961 proto::task_source_kind::Kind::UserInput(_) => TaskSourceKind::UserInput,
4962 proto::task_source_kind::Kind::Worktree(worktree) => {
4963 TaskSourceKind::Worktree {
4964 id: WorktreeId::from_proto(worktree.id),
4965 abs_path: PathBuf::from(worktree.abs_path),
4966 id_base: Cow::Owned(worktree.id_base),
4967 }
4968 }
4969 proto::task_source_kind::Kind::AbsPath(abs_path) => {
4970 TaskSourceKind::AbsPath {
4971 id_base: Cow::Owned(abs_path.id_base),
4972 abs_path: PathBuf::from(abs_path.abs_path),
4973 }
4974 }
4975 proto::task_source_kind::Kind::Language(language) => {
4976 TaskSourceKind::Language {
4977 name: language.name.into(),
4978 }
4979 }
4980 };
4981
4982 let proto_template = template_pair.template?;
4983 let reveal = match proto::RevealStrategy::from_i32(proto_template.reveal)
4984 .unwrap_or(proto::RevealStrategy::RevealAlways)
4985 {
4986 proto::RevealStrategy::RevealAlways => RevealStrategy::Always,
4987 proto::RevealStrategy::RevealNever => RevealStrategy::Never,
4988 };
4989 let hide = match proto::HideStrategy::from_i32(proto_template.hide)
4990 .unwrap_or(proto::HideStrategy::HideNever)
4991 {
4992 proto::HideStrategy::HideAlways => HideStrategy::Always,
4993 proto::HideStrategy::HideNever => HideStrategy::Never,
4994 proto::HideStrategy::HideOnSuccess => HideStrategy::OnSuccess,
4995 };
4996 let shell = match proto_template
4997 .shell
4998 .and_then(|shell| shell.shell_type)
4999 .unwrap_or(proto::shell::ShellType::System(proto::System {}))
5000 {
5001 proto::shell::ShellType::System(_) => Shell::System,
5002 proto::shell::ShellType::Program(program) => Shell::Program(program),
5003 proto::shell::ShellType::WithArguments(with_arguments) => {
5004 Shell::WithArguments {
5005 program: with_arguments.program,
5006 args: with_arguments.args,
5007 }
5008 }
5009 };
5010 let task_template = TaskTemplate {
5011 label: proto_template.label,
5012 command: proto_template.command,
5013 args: proto_template.args,
5014 env: proto_template.env.into_iter().collect(),
5015 cwd: proto_template.cwd,
5016 use_new_terminal: proto_template.use_new_terminal,
5017 allow_concurrent_runs: proto_template.allow_concurrent_runs,
5018 reveal,
5019 hide,
5020 shell,
5021 tags: proto_template.tags,
5022 };
5023 Some((task_source_kind, task_template))
5024 })
5025 .collect())
5026 })
5027 }
5028
5029 fn task_worktree(&self, cx: &AppContext) -> Option<Model<Worktree>> {
5030 let available_worktrees = self
5031 .worktrees(cx)
5032 .filter(|worktree| {
5033 let worktree = worktree.read(cx);
5034 worktree.is_visible()
5035 && worktree.is_local()
5036 && worktree.root_entry().map_or(false, |e| e.is_dir())
5037 })
5038 .collect::<Vec<_>>();
5039
5040 match available_worktrees.len() {
5041 0 => None,
5042 1 => Some(available_worktrees[0].clone()),
5043 _ => self.active_entry().and_then(|entry_id| {
5044 available_worktrees.into_iter().find_map(|worktree| {
5045 if worktree.read(cx).contains_entry(entry_id) {
5046 Some(worktree)
5047 } else {
5048 None
5049 }
5050 })
5051 }),
5052 }
5053 }
5054}
5055
5056fn combine_task_variables(
5057 mut captured_variables: TaskVariables,
5058 location: Location,
5059 baseline: BasicContextProvider,
5060 cx: &mut AppContext,
5061) -> anyhow::Result<TaskVariables> {
5062 let language_context_provider = location
5063 .buffer
5064 .read(cx)
5065 .language()
5066 .and_then(|language| language.context_provider());
5067 let baseline = baseline
5068 .build_context(&captured_variables, &location, cx)
5069 .context("building basic default context")?;
5070 captured_variables.extend(baseline);
5071 if let Some(provider) = language_context_provider {
5072 captured_variables.extend(
5073 provider
5074 .build_context(&captured_variables, &location, cx)
5075 .context("building provider context")?,
5076 );
5077 }
5078 Ok(captured_variables)
5079}
5080
5081fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
5082 code_actions
5083 .iter()
5084 .flat_map(|(kind, enabled)| {
5085 if *enabled {
5086 Some(kind.clone().into())
5087 } else {
5088 None
5089 }
5090 })
5091 .collect()
5092}
5093
5094pub struct PathMatchCandidateSet {
5095 pub snapshot: Snapshot,
5096 pub include_ignored: bool,
5097 pub include_root_name: bool,
5098 pub candidates: Candidates,
5099}
5100
5101pub enum Candidates {
5102 /// Only consider directories.
5103 Directories,
5104 /// Only consider files.
5105 Files,
5106 /// Consider directories and files.
5107 Entries,
5108}
5109
5110impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5111 type Candidates = PathMatchCandidateSetIter<'a>;
5112
5113 fn id(&self) -> usize {
5114 self.snapshot.id().to_usize()
5115 }
5116
5117 fn len(&self) -> usize {
5118 match self.candidates {
5119 Candidates::Files => {
5120 if self.include_ignored {
5121 self.snapshot.file_count()
5122 } else {
5123 self.snapshot.visible_file_count()
5124 }
5125 }
5126
5127 Candidates::Directories => {
5128 if self.include_ignored {
5129 self.snapshot.dir_count()
5130 } else {
5131 self.snapshot.visible_dir_count()
5132 }
5133 }
5134
5135 Candidates::Entries => {
5136 if self.include_ignored {
5137 self.snapshot.entry_count()
5138 } else {
5139 self.snapshot.visible_entry_count()
5140 }
5141 }
5142 }
5143 }
5144
5145 fn prefix(&self) -> Arc<str> {
5146 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5147 self.snapshot.root_name().into()
5148 } else if self.include_root_name {
5149 format!("{}/", self.snapshot.root_name()).into()
5150 } else {
5151 Arc::default()
5152 }
5153 }
5154
5155 fn candidates(&'a self, start: usize) -> Self::Candidates {
5156 PathMatchCandidateSetIter {
5157 traversal: match self.candidates {
5158 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5159 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5160 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5161 },
5162 }
5163 }
5164}
5165
5166pub struct PathMatchCandidateSetIter<'a> {
5167 traversal: Traversal<'a>,
5168}
5169
5170impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5171 type Item = fuzzy::PathMatchCandidate<'a>;
5172
5173 fn next(&mut self) -> Option<Self::Item> {
5174 self.traversal
5175 .next()
5176 .map(|entry| fuzzy::PathMatchCandidate {
5177 is_dir: entry.kind.is_dir(),
5178 path: &entry.path,
5179 char_bag: entry.char_bag,
5180 })
5181 }
5182}
5183
5184impl EventEmitter<Event> for Project {}
5185
5186impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5187 fn from(val: &'a ProjectPath) -> Self {
5188 SettingsLocation {
5189 worktree_id: val.worktree_id,
5190 path: val.path.as_ref(),
5191 }
5192 }
5193}
5194
5195impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5196 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5197 Self {
5198 worktree_id,
5199 path: path.as_ref().into(),
5200 }
5201 }
5202}
5203
5204pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5205 let mut path_components = path.components();
5206 let mut base_components = base.components();
5207 let mut components: Vec<Component> = Vec::new();
5208 loop {
5209 match (path_components.next(), base_components.next()) {
5210 (None, None) => break,
5211 (Some(a), None) => {
5212 components.push(a);
5213 components.extend(path_components.by_ref());
5214 break;
5215 }
5216 (None, _) => components.push(Component::ParentDir),
5217 (Some(a), Some(b)) if components.is_empty() && a == b => (),
5218 (Some(a), Some(Component::CurDir)) => components.push(a),
5219 (Some(a), Some(_)) => {
5220 components.push(Component::ParentDir);
5221 for _ in base_components {
5222 components.push(Component::ParentDir);
5223 }
5224 components.push(a);
5225 components.extend(path_components.by_ref());
5226 break;
5227 }
5228 }
5229 }
5230 components.iter().map(|c| c.as_os_str()).collect()
5231}
5232
5233fn resolve_path(base: &Path, path: &Path) -> PathBuf {
5234 let mut result = base.to_path_buf();
5235 for component in path.components() {
5236 match component {
5237 Component::ParentDir => {
5238 result.pop();
5239 }
5240 Component::CurDir => (),
5241 _ => result.push(component),
5242 }
5243 }
5244 result
5245}
5246
5247/// ResolvedPath is a path that has been resolved to either a ProjectPath
5248/// or an AbsPath and that *exists*.
5249#[derive(Debug, Clone)]
5250pub enum ResolvedPath {
5251 ProjectPath(ProjectPath),
5252 AbsPath(PathBuf),
5253}
5254
5255impl Item for Buffer {
5256 fn try_open(
5257 project: &Model<Project>,
5258 path: &ProjectPath,
5259 cx: &mut AppContext,
5260 ) -> Option<Task<Result<Model<Self>>>> {
5261 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5262 }
5263
5264 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
5265 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5266 }
5267
5268 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
5269 File::from_dyn(self.file()).map(|file| ProjectPath {
5270 worktree_id: file.worktree_id(cx),
5271 path: file.path().clone(),
5272 })
5273 }
5274}
5275
5276impl Completion {
5277 /// A key that can be used to sort completions when displaying
5278 /// them to the user.
5279 pub fn sort_key(&self) -> (usize, &str) {
5280 let kind_key = match self.lsp_completion.kind {
5281 Some(lsp::CompletionItemKind::KEYWORD) => 0,
5282 Some(lsp::CompletionItemKind::VARIABLE) => 1,
5283 _ => 2,
5284 };
5285 (kind_key, &self.label.text[self.label.filter_range.clone()])
5286 }
5287
5288 /// Whether this completion is a snippet.
5289 pub fn is_snippet(&self) -> bool {
5290 self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5291 }
5292}
5293
5294#[derive(Debug)]
5295pub struct NoRepositoryError {}
5296
5297impl std::fmt::Display for NoRepositoryError {
5298 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5299 write!(f, "no git repository for worktree found")
5300 }
5301}
5302
5303impl std::error::Error for NoRepositoryError {}
5304
5305fn serialize_location(location: &Location, cx: &AppContext) -> proto::Location {
5306 proto::Location {
5307 buffer_id: location.buffer.read(cx).remote_id().into(),
5308 start: Some(serialize_anchor(&location.range.start)),
5309 end: Some(serialize_anchor(&location.range.end)),
5310 }
5311}
5312
5313fn deserialize_location(
5314 project: &Model<Project>,
5315 location: proto::Location,
5316 cx: &mut AppContext,
5317) -> Task<Result<Location>> {
5318 let buffer_id = match BufferId::new(location.buffer_id) {
5319 Ok(id) => id,
5320 Err(e) => return Task::ready(Err(e)),
5321 };
5322 let buffer_task = project.update(cx, |project, cx| {
5323 project.wait_for_remote_buffer(buffer_id, cx)
5324 });
5325 cx.spawn(|_| async move {
5326 let buffer = buffer_task.await?;
5327 let start = location
5328 .start
5329 .and_then(deserialize_anchor)
5330 .context("missing task context location start")?;
5331 let end = location
5332 .end
5333 .and_then(deserialize_anchor)
5334 .context("missing task context location end")?;
5335 Ok(Location {
5336 buffer,
5337 range: start..end,
5338 })
5339 })
5340}
5341
5342pub fn sort_worktree_entries(entries: &mut [Entry]) {
5343 entries.sort_by(|entry_a, entry_b| {
5344 compare_paths(
5345 (&entry_a.path, entry_a.is_file()),
5346 (&entry_b.path, entry_b.is_file()),
5347 )
5348 });
5349}