1pub mod buffer_store;
2mod color_extractor;
3pub mod connection_manager;
4pub mod debounced_delay;
5pub mod lsp_command;
6pub mod lsp_ext_command;
7pub mod lsp_store;
8pub mod prettier_store;
9pub mod project_settings;
10pub mod search;
11mod task_inventory;
12pub mod task_store;
13pub mod terminals;
14pub mod worktree_store;
15
16#[cfg(test)]
17mod project_tests;
18
19mod direnv;
20mod environment;
21pub use environment::EnvironmentErrorMessage;
22pub mod search_history;
23mod yarn;
24
25use anyhow::{anyhow, Context as _, Result};
26use buffer_store::{BufferStore, BufferStoreEvent};
27use client::{
28 proto, Client, Collaborator, DevServerProjectId, PendingEntitySubscription, ProjectId,
29 TypedEnvelope, UserStore,
30};
31use clock::ReplicaId;
32use collections::{BTreeSet, HashMap, HashSet};
33use debounced_delay::DebouncedDelay;
34pub use environment::ProjectEnvironment;
35use futures::{
36 channel::mpsc::{self, UnboundedReceiver},
37 future::try_join_all,
38 StreamExt,
39};
40
41use git::{blame::Blame, repository::GitRepository};
42use gpui::{
43 AnyModel, AppContext, AsyncAppContext, BorrowAppContext, Context as _, EventEmitter, Hsla,
44 Model, ModelContext, SharedString, Task, WeakModel, WindowContext,
45};
46use itertools::Itertools;
47use language::{
48 language_settings::InlayHintKind, proto::split_operations, Buffer, BufferEvent,
49 CachedLspAdapter, Capability, CodeLabel, DiagnosticEntry, Documentation, File as _, Language,
50 LanguageRegistry, LanguageServerName, PointUtf16, ToOffset, ToPointUtf16, Transaction,
51 Unclipped,
52};
53use lsp::{
54 CompletionContext, CompletionItemKind, DocumentHighlightKind, LanguageServer, LanguageServerId,
55 MessageActionItem,
56};
57use lsp_command::*;
58use node_runtime::NodeRuntime;
59use parking_lot::{Mutex, RwLock};
60pub use prettier_store::PrettierStore;
61use project_settings::{ProjectSettings, SettingsObserver, SettingsObserverEvent};
62use remote::{SshConnectionOptions, SshRemoteClient};
63use rpc::{
64 proto::{LanguageServerPromptResponse, SSH_PROJECT_ID},
65 AnyProtoClient, ErrorCode,
66};
67use search::{SearchInputKind, SearchQuery, SearchResult};
68use search_history::SearchHistory;
69use settings::{InvalidSettingsError, Settings, SettingsLocation, SettingsStore};
70use smol::channel::Receiver;
71use snippet::Snippet;
72use snippet_provider::SnippetProvider;
73use std::{
74 borrow::Cow,
75 ops::Range,
76 path::{Component, Path, PathBuf},
77 str,
78 sync::Arc,
79 time::Duration,
80};
81use task_store::TaskStore;
82use terminals::Terminals;
83use text::{Anchor, BufferId};
84use util::{paths::compare_paths, ResultExt as _};
85use worktree::{CreatedEntry, Snapshot, Traversal};
86use worktree_store::{WorktreeStore, WorktreeStoreEvent};
87
88pub use fs::*;
89pub use language::Location;
90#[cfg(any(test, feature = "test-support"))]
91pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
92pub use task_inventory::{
93 BasicContextProvider, ContextProviderWithTasks, Inventory, TaskSourceKind,
94};
95pub use worktree::{
96 Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId, RepositoryEntry,
97 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
98 FS_WATCH_LATENCY,
99};
100
101pub use buffer_store::ProjectTransaction;
102pub use lsp_store::{
103 DiagnosticSummary, LanguageServerLogType, LanguageServerProgress, LanguageServerPromptRequest,
104 LanguageServerStatus, LanguageServerToQuery, LspStore, LspStoreEvent,
105 SERVER_PROGRESS_THROTTLE_TIMEOUT,
106};
107
108const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
109const MAX_SEARCH_RESULT_FILES: usize = 5_000;
110const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
111
112pub trait Item {
113 fn try_open(
114 project: &Model<Project>,
115 path: &ProjectPath,
116 cx: &mut AppContext,
117 ) -> Option<Task<Result<Model<Self>>>>
118 where
119 Self: Sized;
120 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
121 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
122}
123
124#[derive(Clone)]
125pub enum OpenedBufferEvent {
126 Disconnected,
127 Ok(BufferId),
128 Err(BufferId, Arc<anyhow::Error>),
129}
130
131/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
132/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
133/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
134///
135/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
136pub struct Project {
137 active_entry: Option<ProjectEntryId>,
138 buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
139 languages: Arc<LanguageRegistry>,
140 client: Arc<client::Client>,
141 join_project_response_message_id: u32,
142 task_store: Model<TaskStore>,
143 user_store: Model<UserStore>,
144 fs: Arc<dyn Fs>,
145 ssh_client: Option<Model<SshRemoteClient>>,
146 client_state: ProjectClientState,
147 collaborators: HashMap<proto::PeerId, Collaborator>,
148 client_subscriptions: Vec<client::Subscription>,
149 worktree_store: Model<WorktreeStore>,
150 buffer_store: Model<BufferStore>,
151 lsp_store: Model<LspStore>,
152 _subscriptions: Vec<gpui::Subscription>,
153 buffers_needing_diff: HashSet<WeakModel<Buffer>>,
154 git_diff_debouncer: DebouncedDelay<Self>,
155 remotely_created_models: Arc<Mutex<RemotelyCreatedModels>>,
156 terminals: Terminals,
157 node: Option<NodeRuntime>,
158 hosted_project_id: Option<ProjectId>,
159 dev_server_project_id: Option<client::DevServerProjectId>,
160 search_history: SearchHistory,
161 search_included_history: SearchHistory,
162 search_excluded_history: SearchHistory,
163 snippets: Model<SnippetProvider>,
164 environment: Model<ProjectEnvironment>,
165 settings_observer: Model<SettingsObserver>,
166}
167
168#[derive(Default)]
169struct RemotelyCreatedModels {
170 worktrees: Vec<Model<Worktree>>,
171 buffers: Vec<Model<Buffer>>,
172 retain_count: usize,
173}
174
175struct RemotelyCreatedModelGuard {
176 remote_models: std::sync::Weak<Mutex<RemotelyCreatedModels>>,
177}
178
179impl Drop for RemotelyCreatedModelGuard {
180 fn drop(&mut self) {
181 if let Some(remote_models) = self.remote_models.upgrade() {
182 let mut remote_models = remote_models.lock();
183 assert!(
184 remote_models.retain_count > 0,
185 "RemotelyCreatedModelGuard dropped too many times"
186 );
187 remote_models.retain_count -= 1;
188 if remote_models.retain_count == 0 {
189 remote_models.buffers.clear();
190 remote_models.worktrees.clear();
191 }
192 }
193 }
194}
195/// Message ordered with respect to buffer operations
196#[derive(Debug)]
197enum BufferOrderedMessage {
198 Operation {
199 buffer_id: BufferId,
200 operation: proto::Operation,
201 },
202 LanguageServerUpdate {
203 language_server_id: LanguageServerId,
204 message: proto::update_language_server::Variant,
205 },
206 Resync,
207}
208
209#[derive(Debug)]
210enum ProjectClientState {
211 Local,
212 Shared {
213 remote_id: u64,
214 },
215 Remote {
216 sharing_has_stopped: bool,
217 capability: Capability,
218 remote_id: u64,
219 replica_id: ReplicaId,
220 in_room: bool,
221 },
222}
223
224#[derive(Clone, Debug, PartialEq)]
225pub enum Event {
226 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
227 LanguageServerRemoved(LanguageServerId),
228 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
229 Toast {
230 notification_id: SharedString,
231 message: String,
232 },
233 HideToast {
234 notification_id: SharedString,
235 },
236 LanguageServerPrompt(LanguageServerPromptRequest),
237 LanguageNotFound(Model<Buffer>),
238 ActiveEntryChanged(Option<ProjectEntryId>),
239 ActivateProjectPanel,
240 WorktreeAdded,
241 WorktreeOrderChanged,
242 WorktreeRemoved(WorktreeId),
243 WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
244 WorktreeUpdatedGitRepositories,
245 DiskBasedDiagnosticsStarted {
246 language_server_id: LanguageServerId,
247 },
248 DiskBasedDiagnosticsFinished {
249 language_server_id: LanguageServerId,
250 },
251 DiagnosticsUpdated {
252 path: ProjectPath,
253 language_server_id: LanguageServerId,
254 },
255 RemoteIdChanged(Option<u64>),
256 DisconnectedFromHost,
257 DisconnectedFromSshRemote,
258 Closed,
259 DeletedEntry(ProjectEntryId),
260 CollaboratorUpdated {
261 old_peer_id: proto::PeerId,
262 new_peer_id: proto::PeerId,
263 },
264 CollaboratorJoined(proto::PeerId),
265 CollaboratorLeft(proto::PeerId),
266 HostReshared,
267 Reshared,
268 Rejoined,
269 RefreshInlayHints,
270 RevealInProjectPanel(ProjectEntryId),
271 SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
272}
273
274#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
275pub struct ProjectPath {
276 pub worktree_id: WorktreeId,
277 pub path: Arc<Path>,
278}
279
280impl ProjectPath {
281 pub fn from_proto(p: proto::ProjectPath) -> Self {
282 Self {
283 worktree_id: WorktreeId::from_proto(p.worktree_id),
284 path: Arc::from(PathBuf::from(p.path)),
285 }
286 }
287
288 pub fn to_proto(&self) -> proto::ProjectPath {
289 proto::ProjectPath {
290 worktree_id: self.worktree_id.to_proto(),
291 path: self.path.to_string_lossy().to_string(),
292 }
293 }
294}
295
296#[derive(Debug, Clone, PartialEq, Eq)]
297pub struct InlayHint {
298 pub position: language::Anchor,
299 pub label: InlayHintLabel,
300 pub kind: Option<InlayHintKind>,
301 pub padding_left: bool,
302 pub padding_right: bool,
303 pub tooltip: Option<InlayHintTooltip>,
304 pub resolve_state: ResolveState,
305}
306
307/// The user's intent behind a given completion confirmation
308#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
309pub enum CompletionIntent {
310 /// The user intends to 'commit' this result, if possible
311 /// completion confirmations should run side effects
312 Complete,
313 /// The user intends to continue 'composing' this completion
314 /// completion confirmations should not run side effects and
315 /// let the user continue composing their action
316 Compose,
317}
318
319impl CompletionIntent {
320 pub fn is_complete(&self) -> bool {
321 self == &Self::Complete
322 }
323
324 pub fn is_compose(&self) -> bool {
325 self == &Self::Compose
326 }
327}
328
329/// A completion provided by a language server
330#[derive(Clone)]
331pub struct Completion {
332 /// The range of the buffer that will be replaced.
333 pub old_range: Range<Anchor>,
334 /// The new text that will be inserted.
335 pub new_text: String,
336 /// A label for this completion that is shown in the menu.
337 pub label: CodeLabel,
338 /// The id of the language server that produced this completion.
339 pub server_id: LanguageServerId,
340 /// The documentation for this completion.
341 pub documentation: Option<Documentation>,
342 /// The raw completion provided by the language server.
343 pub lsp_completion: lsp::CompletionItem,
344 /// An optional callback to invoke when this completion is confirmed.
345 /// Returns, whether new completions should be retriggered after the current one.
346 /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
347 /// if no confirmation is provided or `false` is returned, the completion will be committed.
348 pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut WindowContext) -> bool>>,
349}
350
351impl std::fmt::Debug for Completion {
352 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
353 f.debug_struct("Completion")
354 .field("old_range", &self.old_range)
355 .field("new_text", &self.new_text)
356 .field("label", &self.label)
357 .field("server_id", &self.server_id)
358 .field("documentation", &self.documentation)
359 .field("lsp_completion", &self.lsp_completion)
360 .finish()
361 }
362}
363
364/// A completion provided by a language server
365#[derive(Clone, Debug)]
366pub(crate) struct CoreCompletion {
367 old_range: Range<Anchor>,
368 new_text: String,
369 server_id: LanguageServerId,
370 lsp_completion: lsp::CompletionItem,
371}
372
373/// A code action provided by a language server.
374#[derive(Clone, Debug)]
375pub struct CodeAction {
376 /// The id of the language server that produced this code action.
377 pub server_id: LanguageServerId,
378 /// The range of the buffer where this code action is applicable.
379 pub range: Range<Anchor>,
380 /// The raw code action provided by the language server.
381 pub lsp_action: lsp::CodeAction,
382}
383
384#[derive(Debug, Clone, PartialEq, Eq)]
385pub enum ResolveState {
386 Resolved,
387 CanResolve(LanguageServerId, Option<lsp::LSPAny>),
388 Resolving,
389}
390
391impl InlayHint {
392 pub fn text(&self) -> String {
393 match &self.label {
394 InlayHintLabel::String(s) => s.to_owned(),
395 InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
396 }
397 }
398}
399
400#[derive(Debug, Clone, PartialEq, Eq)]
401pub enum InlayHintLabel {
402 String(String),
403 LabelParts(Vec<InlayHintLabelPart>),
404}
405
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub struct InlayHintLabelPart {
408 pub value: String,
409 pub tooltip: Option<InlayHintLabelPartTooltip>,
410 pub location: Option<(LanguageServerId, lsp::Location)>,
411}
412
413#[derive(Debug, Clone, PartialEq, Eq)]
414pub enum InlayHintTooltip {
415 String(String),
416 MarkupContent(MarkupContent),
417}
418
419#[derive(Debug, Clone, PartialEq, Eq)]
420pub enum InlayHintLabelPartTooltip {
421 String(String),
422 MarkupContent(MarkupContent),
423}
424
425#[derive(Debug, Clone, PartialEq, Eq)]
426pub struct MarkupContent {
427 pub kind: HoverBlockKind,
428 pub value: String,
429}
430
431#[derive(Debug, Clone)]
432pub struct LocationLink {
433 pub origin: Option<Location>,
434 pub target: Location,
435}
436
437#[derive(Debug)]
438pub struct DocumentHighlight {
439 pub range: Range<language::Anchor>,
440 pub kind: DocumentHighlightKind,
441}
442
443#[derive(Clone, Debug)]
444pub struct Symbol {
445 pub language_server_name: LanguageServerName,
446 pub source_worktree_id: WorktreeId,
447 pub path: ProjectPath,
448 pub label: CodeLabel,
449 pub name: String,
450 pub kind: lsp::SymbolKind,
451 pub range: Range<Unclipped<PointUtf16>>,
452 pub signature: [u8; 32],
453}
454
455#[derive(Clone, Debug, PartialEq)]
456pub struct HoverBlock {
457 pub text: String,
458 pub kind: HoverBlockKind,
459}
460
461#[derive(Clone, Debug, PartialEq, Eq)]
462pub enum HoverBlockKind {
463 PlainText,
464 Markdown,
465 Code { language: String },
466}
467
468#[derive(Debug, Clone)]
469pub struct Hover {
470 pub contents: Vec<HoverBlock>,
471 pub range: Option<Range<language::Anchor>>,
472 pub language: Option<Arc<Language>>,
473}
474
475impl Hover {
476 pub fn is_empty(&self) -> bool {
477 self.contents.iter().all(|block| block.text.is_empty())
478 }
479}
480
481enum EntitySubscription {
482 Project(PendingEntitySubscription<Project>),
483 BufferStore(PendingEntitySubscription<BufferStore>),
484 WorktreeStore(PendingEntitySubscription<WorktreeStore>),
485 LspStore(PendingEntitySubscription<LspStore>),
486 SettingsObserver(PendingEntitySubscription<SettingsObserver>),
487}
488
489#[derive(Clone)]
490pub enum DirectoryLister {
491 Project(Model<Project>),
492 Local(Arc<dyn Fs>),
493}
494
495impl DirectoryLister {
496 pub fn is_local(&self, cx: &AppContext) -> bool {
497 match self {
498 DirectoryLister::Local(_) => true,
499 DirectoryLister::Project(project) => project.read(cx).is_local(),
500 }
501 }
502
503 pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &AppContext) -> Cow<'a, str> {
504 if self.is_local(cx) {
505 shellexpand::tilde(path)
506 } else {
507 Cow::from(path)
508 }
509 }
510
511 pub fn default_query(&self, cx: &mut AppContext) -> String {
512 if let DirectoryLister::Project(project) = self {
513 if let Some(worktree) = project.read(cx).visible_worktrees(cx).next() {
514 return worktree.read(cx).abs_path().to_string_lossy().to_string();
515 }
516 };
517 "~/".to_string()
518 }
519
520 pub fn list_directory(&self, path: String, cx: &mut AppContext) -> Task<Result<Vec<PathBuf>>> {
521 match self {
522 DirectoryLister::Project(project) => {
523 project.update(cx, |project, cx| project.list_directory(path, cx))
524 }
525 DirectoryLister::Local(fs) => {
526 let fs = fs.clone();
527 cx.background_executor().spawn(async move {
528 let mut results = vec![];
529 let expanded = shellexpand::tilde(&path);
530 let query = Path::new(expanded.as_ref());
531 let mut response = fs.read_dir(query).await?;
532 while let Some(path) = response.next().await {
533 if let Some(file_name) = path?.file_name() {
534 results.push(PathBuf::from(file_name.to_os_string()));
535 }
536 }
537 Ok(results)
538 })
539 }
540 }
541 }
542}
543
544#[cfg(any(test, feature = "test-support"))]
545pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
546 trigger_kind: lsp::CompletionTriggerKind::INVOKED,
547 trigger_character: None,
548};
549
550impl Project {
551 pub fn init_settings(cx: &mut AppContext) {
552 WorktreeSettings::register(cx);
553 ProjectSettings::register(cx);
554 }
555
556 pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
557 connection_manager::init(client.clone(), cx);
558 Self::init_settings(cx);
559
560 let client: AnyProtoClient = client.clone().into();
561 client.add_model_message_handler(Self::handle_add_collaborator);
562 client.add_model_message_handler(Self::handle_update_project_collaborator);
563 client.add_model_message_handler(Self::handle_remove_collaborator);
564 client.add_model_message_handler(Self::handle_update_project);
565 client.add_model_message_handler(Self::handle_unshare_project);
566 client.add_model_request_handler(Self::handle_update_buffer);
567 client.add_model_message_handler(Self::handle_update_worktree);
568 client.add_model_request_handler(Self::handle_synchronize_buffers);
569
570 client.add_model_request_handler(Self::handle_search_candidate_buffers);
571 client.add_model_request_handler(Self::handle_open_buffer_by_id);
572 client.add_model_request_handler(Self::handle_open_buffer_by_path);
573 client.add_model_request_handler(Self::handle_open_new_buffer);
574 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
575
576 WorktreeStore::init(&client);
577 BufferStore::init(&client);
578 LspStore::init(&client);
579 SettingsObserver::init(&client);
580 TaskStore::init(Some(&client));
581 }
582
583 pub fn local(
584 client: Arc<Client>,
585 node: NodeRuntime,
586 user_store: Model<UserStore>,
587 languages: Arc<LanguageRegistry>,
588 fs: Arc<dyn Fs>,
589 env: Option<HashMap<String, String>>,
590 cx: &mut AppContext,
591 ) -> Model<Self> {
592 cx.new_model(|cx: &mut ModelContext<Self>| {
593 let (tx, rx) = mpsc::unbounded();
594 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
595 .detach();
596 let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
597 let worktree_store = cx.new_model(|_| WorktreeStore::local(false, fs.clone()));
598 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
599 .detach();
600
601 let buffer_store = cx.new_model(|cx| BufferStore::local(worktree_store.clone(), cx));
602 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
603 .detach();
604
605 let prettier_store = cx.new_model(|cx| {
606 PrettierStore::new(
607 node.clone(),
608 fs.clone(),
609 languages.clone(),
610 worktree_store.clone(),
611 cx,
612 )
613 });
614
615 let environment = ProjectEnvironment::new(&worktree_store, env, cx);
616
617 let task_store = cx.new_model(|cx| {
618 TaskStore::local(
619 fs.clone(),
620 buffer_store.downgrade(),
621 worktree_store.clone(),
622 environment.clone(),
623 cx,
624 )
625 });
626
627 let settings_observer = cx.new_model(|cx| {
628 SettingsObserver::new_local(
629 fs.clone(),
630 worktree_store.clone(),
631 task_store.clone(),
632 cx,
633 )
634 });
635 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
636 .detach();
637
638 let lsp_store = cx.new_model(|cx| {
639 LspStore::new_local(
640 buffer_store.clone(),
641 worktree_store.clone(),
642 prettier_store.clone(),
643 environment.clone(),
644 languages.clone(),
645 client.http_client(),
646 fs.clone(),
647 cx,
648 )
649 });
650 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
651
652 Self {
653 buffer_ordered_messages_tx: tx,
654 collaborators: Default::default(),
655 worktree_store,
656 buffer_store,
657 lsp_store,
658 join_project_response_message_id: 0,
659 client_state: ProjectClientState::Local,
660 client_subscriptions: Vec::new(),
661 _subscriptions: vec![cx.on_release(Self::release)],
662 active_entry: None,
663 snippets,
664 languages,
665 client,
666 task_store,
667 user_store,
668 settings_observer,
669 fs,
670 ssh_client: None,
671 buffers_needing_diff: Default::default(),
672 git_diff_debouncer: DebouncedDelay::new(),
673 terminals: Terminals {
674 local_handles: Vec::new(),
675 },
676 node: Some(node),
677 hosted_project_id: None,
678 dev_server_project_id: None,
679 search_history: Self::new_search_history(),
680 environment,
681 remotely_created_models: Default::default(),
682
683 search_included_history: Self::new_search_history(),
684 search_excluded_history: Self::new_search_history(),
685 }
686 })
687 }
688
689 pub fn ssh(
690 ssh: Model<SshRemoteClient>,
691 client: Arc<Client>,
692 node: NodeRuntime,
693 user_store: Model<UserStore>,
694 languages: Arc<LanguageRegistry>,
695 fs: Arc<dyn Fs>,
696 cx: &mut AppContext,
697 ) -> Model<Self> {
698 cx.new_model(|cx: &mut ModelContext<Self>| {
699 let (tx, rx) = mpsc::unbounded();
700 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
701 .detach();
702 let global_snippets_dir = paths::config_dir().join("snippets");
703 let snippets =
704 SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
705
706 let ssh_proto = ssh.read(cx).proto_client();
707 let worktree_store =
708 cx.new_model(|_| WorktreeStore::remote(false, ssh_proto.clone(), 0, None));
709 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
710 .detach();
711
712 let buffer_store = cx.new_model(|cx| {
713 BufferStore::remote(
714 worktree_store.clone(),
715 ssh.read(cx).proto_client(),
716 SSH_PROJECT_ID,
717 cx,
718 )
719 });
720 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
721 .detach();
722
723 let task_store = cx.new_model(|cx| {
724 TaskStore::remote(
725 fs.clone(),
726 buffer_store.downgrade(),
727 worktree_store.clone(),
728 ssh.read(cx).proto_client(),
729 SSH_PROJECT_ID,
730 cx,
731 )
732 });
733
734 let settings_observer = cx.new_model(|cx| {
735 SettingsObserver::new_remote(worktree_store.clone(), task_store.clone(), cx)
736 });
737 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
738 .detach();
739
740 let environment = ProjectEnvironment::new(&worktree_store, None, cx);
741 let lsp_store = cx.new_model(|cx| {
742 LspStore::new_remote(
743 buffer_store.clone(),
744 worktree_store.clone(),
745 languages.clone(),
746 ssh_proto.clone(),
747 SSH_PROJECT_ID,
748 cx,
749 )
750 });
751 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
752
753 cx.subscribe(&ssh, Self::on_ssh_event).detach();
754 cx.observe(&ssh, |_, _, cx| cx.notify()).detach();
755
756 let this = Self {
757 buffer_ordered_messages_tx: tx,
758 collaborators: Default::default(),
759 worktree_store,
760 buffer_store,
761 lsp_store,
762 join_project_response_message_id: 0,
763 client_state: ProjectClientState::Local,
764 client_subscriptions: Vec::new(),
765 _subscriptions: vec![
766 cx.on_release(Self::release),
767 cx.on_app_quit(|this, cx| {
768 let shutdown = this.ssh_client.take().and_then(|client| {
769 client
770 .read(cx)
771 .shutdown_processes(Some(proto::ShutdownRemoteServer {}))
772 });
773
774 cx.background_executor().spawn(async move {
775 if let Some(shutdown) = shutdown {
776 shutdown.await;
777 }
778 })
779 }),
780 ],
781 active_entry: None,
782 snippets,
783 languages,
784 client,
785 task_store,
786 user_store,
787 settings_observer,
788 fs,
789 ssh_client: Some(ssh.clone()),
790 buffers_needing_diff: Default::default(),
791 git_diff_debouncer: DebouncedDelay::new(),
792 terminals: Terminals {
793 local_handles: Vec::new(),
794 },
795 node: Some(node),
796 hosted_project_id: None,
797 dev_server_project_id: None,
798 search_history: Self::new_search_history(),
799 environment,
800 remotely_created_models: Default::default(),
801
802 search_included_history: Self::new_search_history(),
803 search_excluded_history: Self::new_search_history(),
804 };
805
806 let ssh = ssh.read(cx);
807 ssh.subscribe_to_entity(SSH_PROJECT_ID, &cx.handle());
808 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.buffer_store);
809 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.worktree_store);
810 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.lsp_store);
811 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.settings_observer);
812
813 ssh_proto.add_model_message_handler(Self::handle_create_buffer_for_peer);
814 ssh_proto.add_model_message_handler(Self::handle_update_worktree);
815 ssh_proto.add_model_message_handler(Self::handle_update_project);
816 ssh_proto.add_model_message_handler(Self::handle_toast);
817 ssh_proto.add_model_request_handler(Self::handle_language_server_prompt_request);
818 ssh_proto.add_model_message_handler(Self::handle_hide_toast);
819 ssh_proto.add_model_request_handler(BufferStore::handle_update_buffer);
820 BufferStore::init(&ssh_proto);
821 LspStore::init(&ssh_proto);
822 SettingsObserver::init(&ssh_proto);
823 TaskStore::init(Some(&ssh_proto));
824
825 this
826 })
827 }
828
829 pub async fn remote(
830 remote_id: u64,
831 client: Arc<Client>,
832 user_store: Model<UserStore>,
833 languages: Arc<LanguageRegistry>,
834 fs: Arc<dyn Fs>,
835 cx: AsyncAppContext,
836 ) -> Result<Model<Self>> {
837 let project =
838 Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
839 cx.update(|cx| {
840 connection_manager::Manager::global(cx).update(cx, |manager, cx| {
841 manager.maintain_project_connection(&project, cx)
842 })
843 })?;
844 Ok(project)
845 }
846
847 pub async fn in_room(
848 remote_id: u64,
849 client: Arc<Client>,
850 user_store: Model<UserStore>,
851 languages: Arc<LanguageRegistry>,
852 fs: Arc<dyn Fs>,
853 cx: AsyncAppContext,
854 ) -> Result<Model<Self>> {
855 client.authenticate_and_connect(true, &cx).await?;
856
857 let subscriptions = [
858 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
859 EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
860 EntitySubscription::WorktreeStore(
861 client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
862 ),
863 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
864 EntitySubscription::SettingsObserver(
865 client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
866 ),
867 ];
868 let response = client
869 .request_envelope(proto::JoinProject {
870 project_id: remote_id,
871 })
872 .await?;
873 Self::from_join_project_response(
874 response,
875 subscriptions,
876 client,
877 false,
878 user_store,
879 languages,
880 fs,
881 cx,
882 )
883 .await
884 }
885
886 #[allow(clippy::too_many_arguments)]
887 async fn from_join_project_response(
888 response: TypedEnvelope<proto::JoinProjectResponse>,
889 subscriptions: [EntitySubscription; 5],
890 client: Arc<Client>,
891 run_tasks: bool,
892 user_store: Model<UserStore>,
893 languages: Arc<LanguageRegistry>,
894 fs: Arc<dyn Fs>,
895 mut cx: AsyncAppContext,
896 ) -> Result<Model<Self>> {
897 let remote_id = response.payload.project_id;
898 let role = response.payload.role();
899
900 let worktree_store = cx.new_model(|_| {
901 WorktreeStore::remote(
902 true,
903 client.clone().into(),
904 response.payload.project_id,
905 response
906 .payload
907 .dev_server_project_id
908 .map(DevServerProjectId),
909 )
910 })?;
911 let buffer_store = cx.new_model(|cx| {
912 BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
913 })?;
914
915 let lsp_store = cx.new_model(|cx| {
916 let mut lsp_store = LspStore::new_remote(
917 buffer_store.clone(),
918 worktree_store.clone(),
919 languages.clone(),
920 client.clone().into(),
921 remote_id,
922 cx,
923 );
924 lsp_store.set_language_server_statuses_from_proto(response.payload.language_servers);
925 lsp_store
926 })?;
927
928 let task_store = cx.new_model(|cx| {
929 if run_tasks {
930 TaskStore::remote(
931 fs.clone(),
932 buffer_store.downgrade(),
933 worktree_store.clone(),
934 client.clone().into(),
935 remote_id,
936 cx,
937 )
938 } else {
939 TaskStore::Noop
940 }
941 })?;
942
943 let settings_observer = cx.new_model(|cx| {
944 SettingsObserver::new_remote(worktree_store.clone(), task_store.clone(), cx)
945 })?;
946
947 let this = cx.new_model(|cx| {
948 let replica_id = response.payload.replica_id as ReplicaId;
949
950 let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
951
952 let mut worktrees = Vec::new();
953 for worktree in response.payload.worktrees {
954 let worktree =
955 Worktree::remote(remote_id, replica_id, worktree, client.clone().into(), cx);
956 worktrees.push(worktree);
957 }
958
959 let (tx, rx) = mpsc::unbounded();
960 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
961 .detach();
962
963 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
964 .detach();
965
966 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
967 .detach();
968 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
969 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
970 .detach();
971
972 let mut this = Self {
973 buffer_ordered_messages_tx: tx,
974 buffer_store: buffer_store.clone(),
975 worktree_store: worktree_store.clone(),
976 lsp_store: lsp_store.clone(),
977 active_entry: None,
978 collaborators: Default::default(),
979 join_project_response_message_id: response.message_id,
980 languages,
981 user_store: user_store.clone(),
982 task_store,
983 snippets,
984 fs,
985 ssh_client: None,
986 settings_observer: settings_observer.clone(),
987 client_subscriptions: Default::default(),
988 _subscriptions: vec![cx.on_release(Self::release)],
989 client: client.clone(),
990 client_state: ProjectClientState::Remote {
991 sharing_has_stopped: false,
992 capability: Capability::ReadWrite,
993 remote_id,
994 replica_id,
995 in_room: response.payload.dev_server_project_id.is_none(),
996 },
997 buffers_needing_diff: Default::default(),
998 git_diff_debouncer: DebouncedDelay::new(),
999 terminals: Terminals {
1000 local_handles: Vec::new(),
1001 },
1002 node: None,
1003 hosted_project_id: None,
1004 dev_server_project_id: response
1005 .payload
1006 .dev_server_project_id
1007 .map(DevServerProjectId),
1008 search_history: Self::new_search_history(),
1009 search_included_history: Self::new_search_history(),
1010 search_excluded_history: Self::new_search_history(),
1011 environment: ProjectEnvironment::new(&worktree_store, None, cx),
1012 remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1013 };
1014 this.set_role(role, cx);
1015 for worktree in worktrees {
1016 this.add_worktree(&worktree, cx);
1017 }
1018 this
1019 })?;
1020
1021 let subscriptions = subscriptions
1022 .into_iter()
1023 .map(|s| match s {
1024 EntitySubscription::BufferStore(subscription) => {
1025 subscription.set_model(&buffer_store, &mut cx)
1026 }
1027 EntitySubscription::WorktreeStore(subscription) => {
1028 subscription.set_model(&worktree_store, &mut cx)
1029 }
1030 EntitySubscription::SettingsObserver(subscription) => {
1031 subscription.set_model(&settings_observer, &mut cx)
1032 }
1033 EntitySubscription::Project(subscription) => subscription.set_model(&this, &mut cx),
1034 EntitySubscription::LspStore(subscription) => {
1035 subscription.set_model(&lsp_store, &mut cx)
1036 }
1037 })
1038 .collect::<Vec<_>>();
1039
1040 let user_ids = response
1041 .payload
1042 .collaborators
1043 .iter()
1044 .map(|peer| peer.user_id)
1045 .collect();
1046 user_store
1047 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1048 .await?;
1049
1050 this.update(&mut cx, |this, cx| {
1051 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1052 this.client_subscriptions.extend(subscriptions);
1053 anyhow::Ok(())
1054 })??;
1055
1056 Ok(this)
1057 }
1058
1059 pub async fn hosted(
1060 remote_id: ProjectId,
1061 user_store: Model<UserStore>,
1062 client: Arc<Client>,
1063 languages: Arc<LanguageRegistry>,
1064 fs: Arc<dyn Fs>,
1065 cx: AsyncAppContext,
1066 ) -> Result<Model<Self>> {
1067 client.authenticate_and_connect(true, &cx).await?;
1068
1069 let subscriptions = [
1070 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id.0)?),
1071 EntitySubscription::BufferStore(
1072 client.subscribe_to_entity::<BufferStore>(remote_id.0)?,
1073 ),
1074 EntitySubscription::WorktreeStore(
1075 client.subscribe_to_entity::<WorktreeStore>(remote_id.0)?,
1076 ),
1077 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id.0)?),
1078 EntitySubscription::SettingsObserver(
1079 client.subscribe_to_entity::<SettingsObserver>(remote_id.0)?,
1080 ),
1081 ];
1082 let response = client
1083 .request_envelope(proto::JoinHostedProject {
1084 project_id: remote_id.0,
1085 })
1086 .await?;
1087 Self::from_join_project_response(
1088 response,
1089 subscriptions,
1090 client,
1091 true,
1092 user_store,
1093 languages,
1094 fs,
1095 cx,
1096 )
1097 .await
1098 }
1099
1100 fn new_search_history() -> SearchHistory {
1101 SearchHistory::new(
1102 Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1103 search_history::QueryInsertionBehavior::AlwaysInsert,
1104 )
1105 }
1106
1107 fn release(&mut self, cx: &mut AppContext) {
1108 if let Some(client) = self.ssh_client.take() {
1109 let shutdown = client
1110 .read(cx)
1111 .shutdown_processes(Some(proto::ShutdownRemoteServer {}));
1112
1113 cx.background_executor()
1114 .spawn(async move {
1115 if let Some(shutdown) = shutdown {
1116 shutdown.await;
1117 }
1118 })
1119 .detach()
1120 }
1121
1122 match &self.client_state {
1123 ProjectClientState::Local => {}
1124 ProjectClientState::Shared { .. } => {
1125 let _ = self.unshare_internal(cx);
1126 }
1127 ProjectClientState::Remote { remote_id, .. } => {
1128 let _ = self.client.send(proto::LeaveProject {
1129 project_id: *remote_id,
1130 });
1131 self.disconnected_from_host_internal(cx);
1132 }
1133 }
1134 }
1135
1136 #[cfg(any(test, feature = "test-support"))]
1137 pub async fn example(
1138 root_paths: impl IntoIterator<Item = &Path>,
1139 cx: &mut AsyncAppContext,
1140 ) -> Model<Project> {
1141 use clock::FakeSystemClock;
1142
1143 let fs = Arc::new(RealFs::default());
1144 let languages = LanguageRegistry::test(cx.background_executor().clone());
1145 let clock = Arc::new(FakeSystemClock::default());
1146 let http_client = http_client::FakeHttpClient::with_404_response();
1147 let client = cx
1148 .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1149 .unwrap();
1150 let user_store = cx
1151 .new_model(|cx| UserStore::new(client.clone(), cx))
1152 .unwrap();
1153 let project = cx
1154 .update(|cx| {
1155 Project::local(
1156 client,
1157 node_runtime::NodeRuntime::unavailable(),
1158 user_store,
1159 Arc::new(languages),
1160 fs,
1161 None,
1162 cx,
1163 )
1164 })
1165 .unwrap();
1166 for path in root_paths {
1167 let (tree, _) = project
1168 .update(cx, |project, cx| {
1169 project.find_or_create_worktree(path, true, cx)
1170 })
1171 .unwrap()
1172 .await
1173 .unwrap();
1174 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1175 .unwrap()
1176 .await;
1177 }
1178 project
1179 }
1180
1181 #[cfg(any(test, feature = "test-support"))]
1182 pub async fn test(
1183 fs: Arc<dyn Fs>,
1184 root_paths: impl IntoIterator<Item = &Path>,
1185 cx: &mut gpui::TestAppContext,
1186 ) -> Model<Project> {
1187 use clock::FakeSystemClock;
1188 use gpui::Context;
1189
1190 let languages = LanguageRegistry::test(cx.executor());
1191 let clock = Arc::new(FakeSystemClock::default());
1192 let http_client = http_client::FakeHttpClient::with_404_response();
1193 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1194 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
1195 let project = cx.update(|cx| {
1196 Project::local(
1197 client,
1198 node_runtime::NodeRuntime::unavailable(),
1199 user_store,
1200 Arc::new(languages),
1201 fs,
1202 None,
1203 cx,
1204 )
1205 });
1206 for path in root_paths {
1207 let (tree, _) = project
1208 .update(cx, |project, cx| {
1209 project.find_or_create_worktree(path, true, cx)
1210 })
1211 .await
1212 .unwrap();
1213
1214 project.update(cx, |project, cx| {
1215 let tree_id = tree.read(cx).id();
1216 project.environment.update(cx, |environment, _| {
1217 environment.set_cached(&[(tree_id, HashMap::default())])
1218 });
1219 });
1220
1221 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1222 .await;
1223 }
1224 project
1225 }
1226
1227 pub fn lsp_store(&self) -> Model<LspStore> {
1228 self.lsp_store.clone()
1229 }
1230
1231 pub fn worktree_store(&self) -> Model<WorktreeStore> {
1232 self.worktree_store.clone()
1233 }
1234
1235 pub fn buffer_for_id(&self, remote_id: BufferId, cx: &AppContext) -> Option<Model<Buffer>> {
1236 self.buffer_store.read(cx).get(remote_id)
1237 }
1238
1239 pub fn languages(&self) -> &Arc<LanguageRegistry> {
1240 &self.languages
1241 }
1242
1243 pub fn client(&self) -> Arc<Client> {
1244 self.client.clone()
1245 }
1246
1247 pub fn ssh_client(&self) -> Option<Model<SshRemoteClient>> {
1248 self.ssh_client.clone()
1249 }
1250
1251 pub fn user_store(&self) -> Model<UserStore> {
1252 self.user_store.clone()
1253 }
1254
1255 pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1256 self.node.as_ref()
1257 }
1258
1259 pub fn opened_buffers(&self, cx: &AppContext) -> Vec<Model<Buffer>> {
1260 self.buffer_store.read(cx).buffers().collect()
1261 }
1262
1263 pub fn cli_environment(&self, cx: &AppContext) -> Option<HashMap<String, String>> {
1264 self.environment.read(cx).get_cli_environment()
1265 }
1266
1267 pub fn shell_environment_errors<'a>(
1268 &'a self,
1269 cx: &'a AppContext,
1270 ) -> impl Iterator<Item = (&'a WorktreeId, &'a EnvironmentErrorMessage)> {
1271 self.environment.read(cx).environment_errors()
1272 }
1273
1274 pub fn remove_environment_error(
1275 &mut self,
1276 cx: &mut ModelContext<Self>,
1277 worktree_id: WorktreeId,
1278 ) {
1279 self.environment.update(cx, |environment, _| {
1280 environment.remove_environment_error(worktree_id);
1281 });
1282 }
1283
1284 #[cfg(any(test, feature = "test-support"))]
1285 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
1286 self.buffer_store
1287 .read(cx)
1288 .get_by_path(&path.into(), cx)
1289 .is_some()
1290 }
1291
1292 pub fn fs(&self) -> &Arc<dyn Fs> {
1293 &self.fs
1294 }
1295
1296 pub fn remote_id(&self) -> Option<u64> {
1297 match self.client_state {
1298 ProjectClientState::Local => None,
1299 ProjectClientState::Shared { remote_id, .. }
1300 | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1301 }
1302 }
1303
1304 pub fn hosted_project_id(&self) -> Option<ProjectId> {
1305 self.hosted_project_id
1306 }
1307
1308 pub fn dev_server_project_id(&self) -> Option<DevServerProjectId> {
1309 self.dev_server_project_id
1310 }
1311
1312 pub fn supports_terminal(&self, cx: &AppContext) -> bool {
1313 if self.is_local() {
1314 return true;
1315 }
1316 if self.is_via_ssh() {
1317 return true;
1318 }
1319 let Some(id) = self.dev_server_project_id else {
1320 return false;
1321 };
1322 let Some(server) = dev_server_projects::Store::global(cx)
1323 .read(cx)
1324 .dev_server_for_project(id)
1325 else {
1326 return false;
1327 };
1328 server.ssh_connection_string.is_some()
1329 }
1330
1331 pub fn ssh_connection_string(&self, cx: &AppContext) -> Option<SharedString> {
1332 if let Some(ssh_state) = &self.ssh_client {
1333 return Some(ssh_state.read(cx).connection_string().into());
1334 }
1335 let dev_server_id = self.dev_server_project_id()?;
1336 dev_server_projects::Store::global(cx)
1337 .read(cx)
1338 .dev_server_for_project(dev_server_id)?
1339 .ssh_connection_string
1340 .clone()
1341 }
1342
1343 pub fn ssh_connection_state(&self, cx: &AppContext) -> Option<remote::ConnectionState> {
1344 self.ssh_client
1345 .as_ref()
1346 .map(|ssh| ssh.read(cx).connection_state())
1347 }
1348
1349 pub fn ssh_connection_options(&self, cx: &AppContext) -> Option<SshConnectionOptions> {
1350 self.ssh_client
1351 .as_ref()
1352 .map(|ssh| ssh.read(cx).connection_options())
1353 }
1354
1355 pub fn replica_id(&self) -> ReplicaId {
1356 match self.client_state {
1357 ProjectClientState::Remote { replica_id, .. } => replica_id,
1358 _ => {
1359 if self.ssh_client.is_some() {
1360 1
1361 } else {
1362 0
1363 }
1364 }
1365 }
1366 }
1367
1368 pub fn task_store(&self) -> &Model<TaskStore> {
1369 &self.task_store
1370 }
1371
1372 pub fn snippets(&self) -> &Model<SnippetProvider> {
1373 &self.snippets
1374 }
1375
1376 pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1377 match kind {
1378 SearchInputKind::Query => &self.search_history,
1379 SearchInputKind::Include => &self.search_included_history,
1380 SearchInputKind::Exclude => &self.search_excluded_history,
1381 }
1382 }
1383
1384 pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1385 match kind {
1386 SearchInputKind::Query => &mut self.search_history,
1387 SearchInputKind::Include => &mut self.search_included_history,
1388 SearchInputKind::Exclude => &mut self.search_excluded_history,
1389 }
1390 }
1391
1392 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1393 &self.collaborators
1394 }
1395
1396 pub fn host(&self) -> Option<&Collaborator> {
1397 self.collaborators.values().find(|c| c.replica_id == 0)
1398 }
1399
1400 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut AppContext) {
1401 self.worktree_store.update(cx, |store, _| {
1402 store.set_worktrees_reordered(worktrees_reordered);
1403 });
1404 }
1405
1406 /// Collect all worktrees, including ones that don't appear in the project panel
1407 pub fn worktrees<'a>(
1408 &self,
1409 cx: &'a AppContext,
1410 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1411 self.worktree_store.read(cx).worktrees()
1412 }
1413
1414 /// Collect all user-visible worktrees, the ones that appear in the project panel.
1415 pub fn visible_worktrees<'a>(
1416 &'a self,
1417 cx: &'a AppContext,
1418 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1419 self.worktree_store.read(cx).visible_worktrees(cx)
1420 }
1421
1422 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1423 self.visible_worktrees(cx)
1424 .map(|tree| tree.read(cx).root_name())
1425 }
1426
1427 pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
1428 self.worktree_store.read(cx).worktree_for_id(id, cx)
1429 }
1430
1431 pub fn worktree_for_entry(
1432 &self,
1433 entry_id: ProjectEntryId,
1434 cx: &AppContext,
1435 ) -> Option<Model<Worktree>> {
1436 self.worktree_store
1437 .read(cx)
1438 .worktree_for_entry(entry_id, cx)
1439 }
1440
1441 pub fn worktree_id_for_entry(
1442 &self,
1443 entry_id: ProjectEntryId,
1444 cx: &AppContext,
1445 ) -> Option<WorktreeId> {
1446 self.worktree_for_entry(entry_id, cx)
1447 .map(|worktree| worktree.read(cx).id())
1448 }
1449
1450 /// Checks if the entry is the root of a worktree.
1451 pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &AppContext) -> bool {
1452 self.worktree_for_entry(entry_id, cx)
1453 .map(|worktree| {
1454 worktree
1455 .read(cx)
1456 .root_entry()
1457 .is_some_and(|e| e.id == entry_id)
1458 })
1459 .unwrap_or(false)
1460 }
1461
1462 pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &AppContext) -> Option<bool> {
1463 paths
1464 .iter()
1465 .map(|path| self.visibility_for_path(path, cx))
1466 .max()
1467 .flatten()
1468 }
1469
1470 pub fn visibility_for_path(&self, path: &Path, cx: &AppContext) -> Option<bool> {
1471 self.worktrees(cx)
1472 .filter_map(|worktree| {
1473 let worktree = worktree.read(cx);
1474 worktree
1475 .as_local()?
1476 .contains_abs_path(path)
1477 .then(|| worktree.is_visible())
1478 })
1479 .max()
1480 }
1481
1482 pub fn create_entry(
1483 &mut self,
1484 project_path: impl Into<ProjectPath>,
1485 is_directory: bool,
1486 cx: &mut ModelContext<Self>,
1487 ) -> Task<Result<CreatedEntry>> {
1488 let project_path = project_path.into();
1489 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1490 return Task::ready(Err(anyhow!(format!(
1491 "No worktree for path {project_path:?}"
1492 ))));
1493 };
1494 worktree.update(cx, |worktree, cx| {
1495 worktree.create_entry(project_path.path, is_directory, cx)
1496 })
1497 }
1498
1499 pub fn copy_entry(
1500 &mut self,
1501 entry_id: ProjectEntryId,
1502 relative_worktree_source_path: Option<PathBuf>,
1503 new_path: impl Into<Arc<Path>>,
1504 cx: &mut ModelContext<Self>,
1505 ) -> Task<Result<Option<Entry>>> {
1506 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1507 return Task::ready(Ok(None));
1508 };
1509 worktree.update(cx, |worktree, cx| {
1510 worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1511 })
1512 }
1513
1514 pub fn rename_entry(
1515 &mut self,
1516 entry_id: ProjectEntryId,
1517 new_path: impl Into<Arc<Path>>,
1518 cx: &mut ModelContext<Self>,
1519 ) -> Task<Result<CreatedEntry>> {
1520 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1521 return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1522 };
1523 worktree.update(cx, |worktree, cx| {
1524 worktree.rename_entry(entry_id, new_path, cx)
1525 })
1526 }
1527
1528 pub fn delete_entry(
1529 &mut self,
1530 entry_id: ProjectEntryId,
1531 trash: bool,
1532 cx: &mut ModelContext<Self>,
1533 ) -> Option<Task<Result<()>>> {
1534 let worktree = self.worktree_for_entry(entry_id, cx)?;
1535 worktree.update(cx, |worktree, cx| {
1536 worktree.delete_entry(entry_id, trash, cx)
1537 })
1538 }
1539
1540 pub fn expand_entry(
1541 &mut self,
1542 worktree_id: WorktreeId,
1543 entry_id: ProjectEntryId,
1544 cx: &mut ModelContext<Self>,
1545 ) -> Option<Task<Result<()>>> {
1546 let worktree = self.worktree_for_id(worktree_id, cx)?;
1547 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1548 }
1549
1550 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1551 if !matches!(self.client_state, ProjectClientState::Local) {
1552 if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1553 if *in_room || self.dev_server_project_id.is_none() {
1554 return Err(anyhow!("project was already shared"));
1555 } else {
1556 *in_room = true;
1557 return Ok(());
1558 }
1559 } else {
1560 return Err(anyhow!("project was already shared"));
1561 }
1562 }
1563 self.client_subscriptions.extend([
1564 self.client
1565 .subscribe_to_entity(project_id)?
1566 .set_model(&cx.handle(), &mut cx.to_async()),
1567 self.client
1568 .subscribe_to_entity(project_id)?
1569 .set_model(&self.worktree_store, &mut cx.to_async()),
1570 self.client
1571 .subscribe_to_entity(project_id)?
1572 .set_model(&self.buffer_store, &mut cx.to_async()),
1573 self.client
1574 .subscribe_to_entity(project_id)?
1575 .set_model(&self.lsp_store, &mut cx.to_async()),
1576 self.client
1577 .subscribe_to_entity(project_id)?
1578 .set_model(&self.settings_observer, &mut cx.to_async()),
1579 ]);
1580
1581 self.buffer_store.update(cx, |buffer_store, cx| {
1582 buffer_store.shared(project_id, self.client.clone().into(), cx)
1583 });
1584 self.worktree_store.update(cx, |worktree_store, cx| {
1585 worktree_store.shared(project_id, self.client.clone().into(), cx);
1586 });
1587 self.lsp_store.update(cx, |lsp_store, cx| {
1588 lsp_store.shared(project_id, self.client.clone().into(), cx)
1589 });
1590 self.task_store.update(cx, |task_store, cx| {
1591 task_store.shared(project_id, self.client.clone().into(), cx);
1592 });
1593 self.settings_observer.update(cx, |settings_observer, cx| {
1594 settings_observer.shared(project_id, self.client.clone().into(), cx)
1595 });
1596
1597 self.client_state = ProjectClientState::Shared {
1598 remote_id: project_id,
1599 };
1600
1601 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1602 cx.notify();
1603 Ok(())
1604 }
1605
1606 pub fn reshared(
1607 &mut self,
1608 message: proto::ResharedProject,
1609 cx: &mut ModelContext<Self>,
1610 ) -> Result<()> {
1611 self.buffer_store
1612 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
1613 self.set_collaborators_from_proto(message.collaborators, cx)?;
1614
1615 self.worktree_store.update(cx, |worktree_store, cx| {
1616 worktree_store.send_project_updates(cx);
1617 });
1618 cx.notify();
1619 cx.emit(Event::Reshared);
1620 Ok(())
1621 }
1622
1623 pub fn rejoined(
1624 &mut self,
1625 message: proto::RejoinedProject,
1626 message_id: u32,
1627 cx: &mut ModelContext<Self>,
1628 ) -> Result<()> {
1629 cx.update_global::<SettingsStore, _>(|store, cx| {
1630 self.worktree_store.update(cx, |worktree_store, cx| {
1631 for worktree in worktree_store.worktrees() {
1632 store
1633 .clear_local_settings(worktree.read(cx).id(), cx)
1634 .log_err();
1635 }
1636 });
1637 });
1638
1639 self.join_project_response_message_id = message_id;
1640 self.set_worktrees_from_proto(message.worktrees, cx)?;
1641 self.set_collaborators_from_proto(message.collaborators, cx)?;
1642 self.lsp_store.update(cx, |lsp_store, _| {
1643 lsp_store.set_language_server_statuses_from_proto(message.language_servers)
1644 });
1645 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1646 .unwrap();
1647 cx.emit(Event::Rejoined);
1648 cx.notify();
1649 Ok(())
1650 }
1651
1652 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1653 self.unshare_internal(cx)?;
1654 cx.notify();
1655 Ok(())
1656 }
1657
1658 fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1659 if self.is_via_collab() {
1660 if self.dev_server_project_id().is_some() {
1661 if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1662 *in_room = false
1663 }
1664 return Ok(());
1665 } else {
1666 return Err(anyhow!("attempted to unshare a remote project"));
1667 }
1668 }
1669
1670 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1671 self.client_state = ProjectClientState::Local;
1672 self.collaborators.clear();
1673 self.client_subscriptions.clear();
1674 self.worktree_store.update(cx, |store, cx| {
1675 store.unshared(cx);
1676 });
1677 self.buffer_store.update(cx, |buffer_store, cx| {
1678 buffer_store.forget_shared_buffers();
1679 buffer_store.unshared(cx)
1680 });
1681 self.task_store.update(cx, |task_store, cx| {
1682 task_store.unshared(cx);
1683 });
1684 self.settings_observer.update(cx, |settings_observer, cx| {
1685 settings_observer.unshared(cx);
1686 });
1687
1688 self.client
1689 .send(proto::UnshareProject {
1690 project_id: remote_id,
1691 })
1692 .ok();
1693 Ok(())
1694 } else {
1695 Err(anyhow!("attempted to unshare an unshared project"))
1696 }
1697 }
1698
1699 pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1700 if self.is_disconnected(cx) {
1701 return;
1702 }
1703 self.disconnected_from_host_internal(cx);
1704 cx.emit(Event::DisconnectedFromHost);
1705 cx.notify();
1706 }
1707
1708 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
1709 let new_capability =
1710 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1711 Capability::ReadWrite
1712 } else {
1713 Capability::ReadOnly
1714 };
1715 if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1716 if *capability == new_capability {
1717 return;
1718 }
1719
1720 *capability = new_capability;
1721 for buffer in self.opened_buffers(cx) {
1722 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1723 }
1724 }
1725 }
1726
1727 fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1728 if let ProjectClientState::Remote {
1729 sharing_has_stopped,
1730 ..
1731 } = &mut self.client_state
1732 {
1733 *sharing_has_stopped = true;
1734 self.collaborators.clear();
1735 self.worktree_store.update(cx, |store, cx| {
1736 store.disconnected_from_host(cx);
1737 });
1738 self.buffer_store.update(cx, |buffer_store, cx| {
1739 buffer_store.disconnected_from_host(cx)
1740 });
1741 self.lsp_store
1742 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
1743 }
1744 }
1745
1746 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1747 cx.emit(Event::Closed);
1748 }
1749
1750 pub fn is_disconnected(&self, cx: &AppContext) -> bool {
1751 match &self.client_state {
1752 ProjectClientState::Remote {
1753 sharing_has_stopped,
1754 ..
1755 } => *sharing_has_stopped,
1756 ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
1757 _ => false,
1758 }
1759 }
1760
1761 fn ssh_is_disconnected(&self, cx: &AppContext) -> bool {
1762 self.ssh_client
1763 .as_ref()
1764 .map(|ssh| ssh.read(cx).is_disconnected())
1765 .unwrap_or(false)
1766 }
1767
1768 pub fn capability(&self) -> Capability {
1769 match &self.client_state {
1770 ProjectClientState::Remote { capability, .. } => *capability,
1771 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1772 }
1773 }
1774
1775 pub fn is_read_only(&self, cx: &AppContext) -> bool {
1776 self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
1777 }
1778
1779 pub fn is_local(&self) -> bool {
1780 match &self.client_state {
1781 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1782 self.ssh_client.is_none()
1783 }
1784 ProjectClientState::Remote { .. } => false,
1785 }
1786 }
1787
1788 pub fn is_via_ssh(&self) -> bool {
1789 match &self.client_state {
1790 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1791 self.ssh_client.is_some()
1792 }
1793 ProjectClientState::Remote { .. } => false,
1794 }
1795 }
1796
1797 pub fn is_via_collab(&self) -> bool {
1798 match &self.client_state {
1799 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
1800 ProjectClientState::Remote { .. } => true,
1801 }
1802 }
1803
1804 pub fn create_buffer(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Model<Buffer>>> {
1805 self.buffer_store
1806 .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
1807 }
1808
1809 pub fn create_local_buffer(
1810 &mut self,
1811 text: &str,
1812 language: Option<Arc<Language>>,
1813 cx: &mut ModelContext<Self>,
1814 ) -> Model<Buffer> {
1815 if self.is_via_collab() || self.is_via_ssh() {
1816 panic!("called create_local_buffer on a remote project")
1817 }
1818 self.buffer_store.update(cx, |buffer_store, cx| {
1819 buffer_store.create_local_buffer(text, language, cx)
1820 })
1821 }
1822
1823 pub fn open_path(
1824 &mut self,
1825 path: ProjectPath,
1826 cx: &mut ModelContext<Self>,
1827 ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
1828 let task = self.open_buffer(path.clone(), cx);
1829 cx.spawn(move |_, cx| async move {
1830 let buffer = task.await?;
1831 let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1832 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1833 })?;
1834
1835 let buffer: &AnyModel = &buffer;
1836 Ok((project_entry_id, buffer.clone()))
1837 })
1838 }
1839
1840 pub fn open_local_buffer(
1841 &mut self,
1842 abs_path: impl AsRef<Path>,
1843 cx: &mut ModelContext<Self>,
1844 ) -> Task<Result<Model<Buffer>>> {
1845 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1846 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1847 } else {
1848 Task::ready(Err(anyhow!("no such path")))
1849 }
1850 }
1851
1852 pub fn open_buffer(
1853 &mut self,
1854 path: impl Into<ProjectPath>,
1855 cx: &mut ModelContext<Self>,
1856 ) -> Task<Result<Model<Buffer>>> {
1857 if (self.is_via_collab() || self.is_via_ssh()) && self.is_disconnected(cx) {
1858 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1859 }
1860
1861 self.buffer_store.update(cx, |buffer_store, cx| {
1862 buffer_store.open_buffer(path.into(), cx)
1863 })
1864 }
1865
1866 pub fn open_buffer_by_id(
1867 &mut self,
1868 id: BufferId,
1869 cx: &mut ModelContext<Self>,
1870 ) -> Task<Result<Model<Buffer>>> {
1871 if let Some(buffer) = self.buffer_for_id(id, cx) {
1872 Task::ready(Ok(buffer))
1873 } else if self.is_local() || self.is_via_ssh() {
1874 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1875 } else if let Some(project_id) = self.remote_id() {
1876 let request = self.client.request(proto::OpenBufferById {
1877 project_id,
1878 id: id.into(),
1879 });
1880 cx.spawn(move |this, mut cx| async move {
1881 let buffer_id = BufferId::new(request.await?.buffer_id)?;
1882 this.update(&mut cx, |this, cx| {
1883 this.wait_for_remote_buffer(buffer_id, cx)
1884 })?
1885 .await
1886 })
1887 } else {
1888 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1889 }
1890 }
1891
1892 pub fn save_buffers(
1893 &self,
1894 buffers: HashSet<Model<Buffer>>,
1895 cx: &mut ModelContext<Self>,
1896 ) -> Task<Result<()>> {
1897 cx.spawn(move |this, mut cx| async move {
1898 let save_tasks = buffers.into_iter().filter_map(|buffer| {
1899 this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
1900 .ok()
1901 });
1902 try_join_all(save_tasks).await?;
1903 Ok(())
1904 })
1905 }
1906
1907 pub fn save_buffer(
1908 &self,
1909 buffer: Model<Buffer>,
1910 cx: &mut ModelContext<Self>,
1911 ) -> Task<Result<()>> {
1912 self.buffer_store
1913 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
1914 }
1915
1916 pub fn save_buffer_as(
1917 &mut self,
1918 buffer: Model<Buffer>,
1919 path: ProjectPath,
1920 cx: &mut ModelContext<Self>,
1921 ) -> Task<Result<()>> {
1922 self.buffer_store.update(cx, |buffer_store, cx| {
1923 buffer_store.save_buffer_as(buffer.clone(), path, cx)
1924 })
1925 }
1926
1927 pub fn get_open_buffer(
1928 &mut self,
1929 path: &ProjectPath,
1930 cx: &mut ModelContext<Self>,
1931 ) -> Option<Model<Buffer>> {
1932 self.buffer_store.read(cx).get_by_path(path, cx)
1933 }
1934
1935 fn register_buffer(
1936 &mut self,
1937 buffer: &Model<Buffer>,
1938 cx: &mut ModelContext<Self>,
1939 ) -> Result<()> {
1940 {
1941 let mut remotely_created_models = self.remotely_created_models.lock();
1942 if remotely_created_models.retain_count > 0 {
1943 remotely_created_models.buffers.push(buffer.clone())
1944 }
1945 }
1946
1947 self.request_buffer_diff_recalculation(buffer, cx);
1948
1949 cx.subscribe(buffer, |this, buffer, event, cx| {
1950 this.on_buffer_event(buffer, event, cx);
1951 })
1952 .detach();
1953
1954 Ok(())
1955 }
1956
1957 async fn send_buffer_ordered_messages(
1958 this: WeakModel<Self>,
1959 rx: UnboundedReceiver<BufferOrderedMessage>,
1960 mut cx: AsyncAppContext,
1961 ) -> Result<()> {
1962 const MAX_BATCH_SIZE: usize = 128;
1963
1964 let mut operations_by_buffer_id = HashMap::default();
1965 async fn flush_operations(
1966 this: &WeakModel<Project>,
1967 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
1968 needs_resync_with_host: &mut bool,
1969 is_local: bool,
1970 cx: &mut AsyncAppContext,
1971 ) -> Result<()> {
1972 for (buffer_id, operations) in operations_by_buffer_id.drain() {
1973 let request = this.update(cx, |this, _| {
1974 let project_id = this.remote_id()?;
1975 Some(this.client.request(proto::UpdateBuffer {
1976 buffer_id: buffer_id.into(),
1977 project_id,
1978 operations,
1979 }))
1980 })?;
1981 if let Some(request) = request {
1982 if request.await.is_err() && !is_local {
1983 *needs_resync_with_host = true;
1984 break;
1985 }
1986 }
1987 }
1988 Ok(())
1989 }
1990
1991 let mut needs_resync_with_host = false;
1992 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
1993
1994 while let Some(changes) = changes.next().await {
1995 let is_local = this.update(&mut cx, |this, _| this.is_local())?;
1996
1997 for change in changes {
1998 match change {
1999 BufferOrderedMessage::Operation {
2000 buffer_id,
2001 operation,
2002 } => {
2003 if needs_resync_with_host {
2004 continue;
2005 }
2006
2007 operations_by_buffer_id
2008 .entry(buffer_id)
2009 .or_insert(Vec::new())
2010 .push(operation);
2011 }
2012
2013 BufferOrderedMessage::Resync => {
2014 operations_by_buffer_id.clear();
2015 if this
2016 .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2017 .await
2018 .is_ok()
2019 {
2020 needs_resync_with_host = false;
2021 }
2022 }
2023
2024 BufferOrderedMessage::LanguageServerUpdate {
2025 language_server_id,
2026 message,
2027 } => {
2028 flush_operations(
2029 &this,
2030 &mut operations_by_buffer_id,
2031 &mut needs_resync_with_host,
2032 is_local,
2033 &mut cx,
2034 )
2035 .await?;
2036
2037 this.update(&mut cx, |this, _| {
2038 if let Some(project_id) = this.remote_id() {
2039 this.client
2040 .send(proto::UpdateLanguageServer {
2041 project_id,
2042 language_server_id: language_server_id.0 as u64,
2043 variant: Some(message),
2044 })
2045 .log_err();
2046 }
2047 })?;
2048 }
2049 }
2050 }
2051
2052 flush_operations(
2053 &this,
2054 &mut operations_by_buffer_id,
2055 &mut needs_resync_with_host,
2056 is_local,
2057 &mut cx,
2058 )
2059 .await?;
2060 }
2061
2062 Ok(())
2063 }
2064
2065 fn on_buffer_store_event(
2066 &mut self,
2067 _: Model<BufferStore>,
2068 event: &BufferStoreEvent,
2069 cx: &mut ModelContext<Self>,
2070 ) {
2071 match event {
2072 BufferStoreEvent::BufferAdded(buffer) => {
2073 self.register_buffer(buffer, cx).log_err();
2074 }
2075 BufferStoreEvent::BufferChangedFilePath { .. } => {}
2076 BufferStoreEvent::BufferDropped(buffer_id) => {
2077 if let Some(ref ssh_client) = self.ssh_client {
2078 ssh_client
2079 .read(cx)
2080 .proto_client()
2081 .send(proto::CloseBuffer {
2082 project_id: 0,
2083 buffer_id: buffer_id.to_proto(),
2084 })
2085 .log_err();
2086 }
2087 }
2088 }
2089 }
2090
2091 fn on_lsp_store_event(
2092 &mut self,
2093 _: Model<LspStore>,
2094 event: &LspStoreEvent,
2095 cx: &mut ModelContext<Self>,
2096 ) {
2097 match event {
2098 LspStoreEvent::DiagnosticsUpdated {
2099 language_server_id,
2100 path,
2101 } => cx.emit(Event::DiagnosticsUpdated {
2102 path: path.clone(),
2103 language_server_id: *language_server_id,
2104 }),
2105 LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2106 Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2107 ),
2108 LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2109 cx.emit(Event::LanguageServerRemoved(*language_server_id))
2110 }
2111 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2112 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2113 ),
2114 LspStoreEvent::LanguageDetected {
2115 buffer,
2116 new_language,
2117 } => {
2118 let Some(_) = new_language else {
2119 cx.emit(Event::LanguageNotFound(buffer.clone()));
2120 return;
2121 };
2122 }
2123 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2124 LspStoreEvent::LanguageServerPrompt(prompt) => {
2125 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2126 }
2127 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2128 cx.emit(Event::DiskBasedDiagnosticsStarted {
2129 language_server_id: *language_server_id,
2130 });
2131 }
2132 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2133 cx.emit(Event::DiskBasedDiagnosticsFinished {
2134 language_server_id: *language_server_id,
2135 });
2136 }
2137 LspStoreEvent::LanguageServerUpdate {
2138 language_server_id,
2139 message,
2140 } => {
2141 if self.is_local() {
2142 self.enqueue_buffer_ordered_message(
2143 BufferOrderedMessage::LanguageServerUpdate {
2144 language_server_id: *language_server_id,
2145 message: message.clone(),
2146 },
2147 )
2148 .ok();
2149 }
2150 }
2151 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2152 notification_id: "lsp".into(),
2153 message: message.clone(),
2154 }),
2155 LspStoreEvent::SnippetEdit {
2156 buffer_id,
2157 edits,
2158 most_recent_edit,
2159 } => {
2160 if most_recent_edit.replica_id == self.replica_id() {
2161 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2162 }
2163 }
2164 }
2165 }
2166
2167 fn on_ssh_event(
2168 &mut self,
2169 _: Model<SshRemoteClient>,
2170 event: &remote::SshRemoteEvent,
2171 cx: &mut ModelContext<Self>,
2172 ) {
2173 match event {
2174 remote::SshRemoteEvent::Disconnected => {
2175 // if self.is_via_ssh() {
2176 // self.collaborators.clear();
2177 self.worktree_store.update(cx, |store, cx| {
2178 store.disconnected_from_host(cx);
2179 });
2180 self.buffer_store.update(cx, |buffer_store, cx| {
2181 buffer_store.disconnected_from_host(cx)
2182 });
2183 self.lsp_store.update(cx, |lsp_store, _cx| {
2184 lsp_store.disconnected_from_ssh_remote()
2185 });
2186 cx.emit(Event::DisconnectedFromSshRemote);
2187 }
2188 }
2189 }
2190
2191 fn on_settings_observer_event(
2192 &mut self,
2193 _: Model<SettingsObserver>,
2194 event: &SettingsObserverEvent,
2195 cx: &mut ModelContext<Self>,
2196 ) {
2197 match event {
2198 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2199 Err(InvalidSettingsError::LocalSettings { message, path }) => {
2200 let message =
2201 format!("Failed to set local settings in {:?}:\n{}", path, message);
2202 cx.emit(Event::Toast {
2203 notification_id: "local-settings".into(),
2204 message,
2205 });
2206 }
2207 Ok(_) => cx.emit(Event::HideToast {
2208 notification_id: "local-settings".into(),
2209 }),
2210 Err(_) => {}
2211 },
2212 }
2213 }
2214
2215 fn on_worktree_store_event(
2216 &mut self,
2217 _: Model<WorktreeStore>,
2218 event: &WorktreeStoreEvent,
2219 cx: &mut ModelContext<Self>,
2220 ) {
2221 match event {
2222 WorktreeStoreEvent::WorktreeAdded(worktree) => {
2223 self.on_worktree_added(worktree, cx);
2224 cx.emit(Event::WorktreeAdded);
2225 }
2226 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2227 cx.emit(Event::WorktreeRemoved(*id));
2228 }
2229 WorktreeStoreEvent::WorktreeReleased(_, id) => {
2230 self.on_worktree_released(*id, cx);
2231 }
2232 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2233 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2234 }
2235 }
2236
2237 fn on_worktree_added(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
2238 {
2239 let mut remotely_created_models = self.remotely_created_models.lock();
2240 if remotely_created_models.retain_count > 0 {
2241 remotely_created_models.worktrees.push(worktree.clone())
2242 }
2243 }
2244 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2245 cx.subscribe(worktree, |project, worktree, event, cx| match event {
2246 worktree::Event::UpdatedEntries(changes) => {
2247 cx.emit(Event::WorktreeUpdatedEntries(
2248 worktree.read(cx).id(),
2249 changes.clone(),
2250 ));
2251
2252 let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
2253 project
2254 .client()
2255 .telemetry()
2256 .report_discovered_project_events(worktree_id, changes);
2257 }
2258 worktree::Event::UpdatedGitRepositories(_) => {
2259 cx.emit(Event::WorktreeUpdatedGitRepositories);
2260 }
2261 worktree::Event::DeletedEntry(id) => cx.emit(Event::DeletedEntry(*id)),
2262 })
2263 .detach();
2264 cx.notify();
2265 }
2266
2267 fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
2268 if let Some(dev_server_project_id) = self.dev_server_project_id {
2269 let paths: Vec<String> = self
2270 .visible_worktrees(cx)
2271 .filter_map(|worktree| {
2272 if worktree.read(cx).id() == id_to_remove {
2273 None
2274 } else {
2275 Some(worktree.read(cx).abs_path().to_string_lossy().to_string())
2276 }
2277 })
2278 .collect();
2279 if !paths.is_empty() {
2280 let request = self.client.request(proto::UpdateDevServerProject {
2281 dev_server_project_id: dev_server_project_id.0,
2282 paths,
2283 });
2284 cx.background_executor()
2285 .spawn(request)
2286 .detach_and_log_err(cx);
2287 }
2288 return;
2289 }
2290
2291 if let Some(ssh) = &self.ssh_client {
2292 ssh.read(cx)
2293 .proto_client()
2294 .send(proto::RemoveWorktree {
2295 worktree_id: id_to_remove.to_proto(),
2296 })
2297 .log_err();
2298 }
2299
2300 cx.notify();
2301 }
2302
2303 fn on_buffer_event(
2304 &mut self,
2305 buffer: Model<Buffer>,
2306 event: &BufferEvent,
2307 cx: &mut ModelContext<Self>,
2308 ) -> Option<()> {
2309 if matches!(
2310 event,
2311 BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2312 ) {
2313 self.request_buffer_diff_recalculation(&buffer, cx);
2314 }
2315
2316 let buffer_id = buffer.read(cx).remote_id();
2317 match event {
2318 BufferEvent::ReloadNeeded => {
2319 if !self.is_via_collab() {
2320 self.reload_buffers([buffer.clone()].into_iter().collect(), false, cx)
2321 .detach_and_log_err(cx);
2322 }
2323 }
2324 BufferEvent::Operation {
2325 operation,
2326 is_local: true,
2327 } => {
2328 let operation = language::proto::serialize_operation(operation);
2329
2330 if let Some(ssh) = &self.ssh_client {
2331 ssh.read(cx)
2332 .proto_client()
2333 .send(proto::UpdateBuffer {
2334 project_id: 0,
2335 buffer_id: buffer_id.to_proto(),
2336 operations: vec![operation.clone()],
2337 })
2338 .ok();
2339 }
2340
2341 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2342 buffer_id,
2343 operation,
2344 })
2345 .ok();
2346 }
2347
2348 _ => {}
2349 }
2350
2351 None
2352 }
2353
2354 fn request_buffer_diff_recalculation(
2355 &mut self,
2356 buffer: &Model<Buffer>,
2357 cx: &mut ModelContext<Self>,
2358 ) {
2359 self.buffers_needing_diff.insert(buffer.downgrade());
2360 let first_insertion = self.buffers_needing_diff.len() == 1;
2361
2362 let settings = ProjectSettings::get_global(cx);
2363 let delay = if let Some(delay) = settings.git.gutter_debounce {
2364 delay
2365 } else {
2366 if first_insertion {
2367 let this = cx.weak_model();
2368 cx.defer(move |cx| {
2369 if let Some(this) = this.upgrade() {
2370 this.update(cx, |this, cx| {
2371 this.recalculate_buffer_diffs(cx).detach();
2372 });
2373 }
2374 });
2375 }
2376 return;
2377 };
2378
2379 const MIN_DELAY: u64 = 50;
2380 let delay = delay.max(MIN_DELAY);
2381 let duration = Duration::from_millis(delay);
2382
2383 self.git_diff_debouncer
2384 .fire_new(duration, cx, move |this, cx| {
2385 this.recalculate_buffer_diffs(cx)
2386 });
2387 }
2388
2389 fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2390 let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2391 cx.spawn(move |this, mut cx| async move {
2392 let tasks: Vec<_> = buffers
2393 .iter()
2394 .filter_map(|buffer| {
2395 let buffer = buffer.upgrade()?;
2396 buffer
2397 .update(&mut cx, |buffer, cx| buffer.recalculate_diff(cx))
2398 .ok()
2399 .flatten()
2400 })
2401 .collect();
2402
2403 futures::future::join_all(tasks).await;
2404
2405 this.update(&mut cx, |this, cx| {
2406 if this.buffers_needing_diff.is_empty() {
2407 // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2408 for buffer in buffers {
2409 if let Some(buffer) = buffer.upgrade() {
2410 buffer.update(cx, |_, cx| cx.notify());
2411 }
2412 }
2413 } else {
2414 this.recalculate_buffer_diffs(cx).detach();
2415 }
2416 })
2417 .ok();
2418 })
2419 }
2420
2421 pub fn set_language_for_buffer(
2422 &mut self,
2423 buffer: &Model<Buffer>,
2424 new_language: Arc<Language>,
2425 cx: &mut ModelContext<Self>,
2426 ) {
2427 self.lsp_store.update(cx, |lsp_store, cx| {
2428 lsp_store.set_language_for_buffer(buffer, new_language, cx)
2429 })
2430 }
2431
2432 pub fn restart_language_servers_for_buffers(
2433 &mut self,
2434 buffers: impl IntoIterator<Item = Model<Buffer>>,
2435 cx: &mut ModelContext<Self>,
2436 ) {
2437 self.lsp_store.update(cx, |lsp_store, cx| {
2438 lsp_store.restart_language_servers_for_buffers(buffers, cx)
2439 })
2440 }
2441
2442 pub fn cancel_language_server_work_for_buffers(
2443 &mut self,
2444 buffers: impl IntoIterator<Item = Model<Buffer>>,
2445 cx: &mut ModelContext<Self>,
2446 ) {
2447 self.lsp_store.update(cx, |lsp_store, cx| {
2448 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2449 })
2450 }
2451
2452 pub fn cancel_language_server_work(
2453 &mut self,
2454 server_id: LanguageServerId,
2455 token_to_cancel: Option<String>,
2456 cx: &mut ModelContext<Self>,
2457 ) {
2458 self.lsp_store.update(cx, |lsp_store, cx| {
2459 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2460 })
2461 }
2462
2463 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2464 self.buffer_ordered_messages_tx
2465 .unbounded_send(message)
2466 .map_err(|e| anyhow!(e))
2467 }
2468
2469 pub fn language_server_statuses<'a>(
2470 &'a self,
2471 cx: &'a AppContext,
2472 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2473 self.lsp_store.read(cx).language_server_statuses()
2474 }
2475
2476 pub fn last_formatting_failure<'a>(&self, cx: &'a AppContext) -> Option<&'a str> {
2477 self.lsp_store.read(cx).last_formatting_failure()
2478 }
2479
2480 pub fn update_diagnostics(
2481 &mut self,
2482 language_server_id: LanguageServerId,
2483 params: lsp::PublishDiagnosticsParams,
2484 disk_based_sources: &[String],
2485 cx: &mut ModelContext<Self>,
2486 ) -> Result<()> {
2487 self.lsp_store.update(cx, |lsp_store, cx| {
2488 lsp_store.update_diagnostics(language_server_id, params, disk_based_sources, cx)
2489 })
2490 }
2491
2492 pub fn update_diagnostic_entries(
2493 &mut self,
2494 server_id: LanguageServerId,
2495 abs_path: PathBuf,
2496 version: Option<i32>,
2497 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2498 cx: &mut ModelContext<Project>,
2499 ) -> Result<(), anyhow::Error> {
2500 self.lsp_store.update(cx, |lsp_store, cx| {
2501 lsp_store.update_diagnostic_entries(server_id, abs_path, version, diagnostics, cx)
2502 })
2503 }
2504
2505 pub fn reload_buffers(
2506 &self,
2507 buffers: HashSet<Model<Buffer>>,
2508 push_to_history: bool,
2509 cx: &mut ModelContext<Self>,
2510 ) -> Task<Result<ProjectTransaction>> {
2511 self.buffer_store.update(cx, |buffer_store, cx| {
2512 buffer_store.reload_buffers(buffers, push_to_history, cx)
2513 })
2514 }
2515
2516 pub fn format(
2517 &mut self,
2518 buffers: HashSet<Model<Buffer>>,
2519 push_to_history: bool,
2520 trigger: lsp_store::FormatTrigger,
2521 target: lsp_store::FormatTarget,
2522 cx: &mut ModelContext<Project>,
2523 ) -> Task<anyhow::Result<ProjectTransaction>> {
2524 self.lsp_store.update(cx, |lsp_store, cx| {
2525 lsp_store.format(buffers, push_to_history, trigger, target, cx)
2526 })
2527 }
2528
2529 #[inline(never)]
2530 fn definition_impl(
2531 &mut self,
2532 buffer: &Model<Buffer>,
2533 position: PointUtf16,
2534 cx: &mut ModelContext<Self>,
2535 ) -> Task<Result<Vec<LocationLink>>> {
2536 self.request_lsp(
2537 buffer.clone(),
2538 LanguageServerToQuery::Primary,
2539 GetDefinition { position },
2540 cx,
2541 )
2542 }
2543 pub fn definition<T: ToPointUtf16>(
2544 &mut self,
2545 buffer: &Model<Buffer>,
2546 position: T,
2547 cx: &mut ModelContext<Self>,
2548 ) -> Task<Result<Vec<LocationLink>>> {
2549 let position = position.to_point_utf16(buffer.read(cx));
2550 self.definition_impl(buffer, position, cx)
2551 }
2552
2553 fn declaration_impl(
2554 &mut self,
2555 buffer: &Model<Buffer>,
2556 position: PointUtf16,
2557 cx: &mut ModelContext<Self>,
2558 ) -> Task<Result<Vec<LocationLink>>> {
2559 self.request_lsp(
2560 buffer.clone(),
2561 LanguageServerToQuery::Primary,
2562 GetDeclaration { position },
2563 cx,
2564 )
2565 }
2566
2567 pub fn declaration<T: ToPointUtf16>(
2568 &mut self,
2569 buffer: &Model<Buffer>,
2570 position: T,
2571 cx: &mut ModelContext<Self>,
2572 ) -> Task<Result<Vec<LocationLink>>> {
2573 let position = position.to_point_utf16(buffer.read(cx));
2574 self.declaration_impl(buffer, position, cx)
2575 }
2576
2577 fn type_definition_impl(
2578 &mut self,
2579 buffer: &Model<Buffer>,
2580 position: PointUtf16,
2581 cx: &mut ModelContext<Self>,
2582 ) -> Task<Result<Vec<LocationLink>>> {
2583 self.request_lsp(
2584 buffer.clone(),
2585 LanguageServerToQuery::Primary,
2586 GetTypeDefinition { position },
2587 cx,
2588 )
2589 }
2590
2591 pub fn type_definition<T: ToPointUtf16>(
2592 &mut self,
2593 buffer: &Model<Buffer>,
2594 position: T,
2595 cx: &mut ModelContext<Self>,
2596 ) -> Task<Result<Vec<LocationLink>>> {
2597 let position = position.to_point_utf16(buffer.read(cx));
2598 self.type_definition_impl(buffer, position, cx)
2599 }
2600
2601 pub fn implementation<T: ToPointUtf16>(
2602 &mut self,
2603 buffer: &Model<Buffer>,
2604 position: T,
2605 cx: &mut ModelContext<Self>,
2606 ) -> Task<Result<Vec<LocationLink>>> {
2607 let position = position.to_point_utf16(buffer.read(cx));
2608 self.request_lsp(
2609 buffer.clone(),
2610 LanguageServerToQuery::Primary,
2611 GetImplementation { position },
2612 cx,
2613 )
2614 }
2615
2616 pub fn references<T: ToPointUtf16>(
2617 &mut self,
2618 buffer: &Model<Buffer>,
2619 position: T,
2620 cx: &mut ModelContext<Self>,
2621 ) -> Task<Result<Vec<Location>>> {
2622 let position = position.to_point_utf16(buffer.read(cx));
2623 self.request_lsp(
2624 buffer.clone(),
2625 LanguageServerToQuery::Primary,
2626 GetReferences { position },
2627 cx,
2628 )
2629 }
2630
2631 fn document_highlights_impl(
2632 &mut self,
2633 buffer: &Model<Buffer>,
2634 position: PointUtf16,
2635 cx: &mut ModelContext<Self>,
2636 ) -> Task<Result<Vec<DocumentHighlight>>> {
2637 self.request_lsp(
2638 buffer.clone(),
2639 LanguageServerToQuery::Primary,
2640 GetDocumentHighlights { position },
2641 cx,
2642 )
2643 }
2644
2645 pub fn document_highlights<T: ToPointUtf16>(
2646 &mut self,
2647 buffer: &Model<Buffer>,
2648 position: T,
2649 cx: &mut ModelContext<Self>,
2650 ) -> Task<Result<Vec<DocumentHighlight>>> {
2651 let position = position.to_point_utf16(buffer.read(cx));
2652 self.document_highlights_impl(buffer, position, cx)
2653 }
2654
2655 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
2656 self.lsp_store
2657 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
2658 }
2659
2660 pub fn open_buffer_for_symbol(
2661 &mut self,
2662 symbol: &Symbol,
2663 cx: &mut ModelContext<Self>,
2664 ) -> Task<Result<Model<Buffer>>> {
2665 self.lsp_store.update(cx, |lsp_store, cx| {
2666 lsp_store.open_buffer_for_symbol(symbol, cx)
2667 })
2668 }
2669
2670 pub fn open_server_settings(
2671 &mut self,
2672 cx: &mut ModelContext<Self>,
2673 ) -> Task<Result<Model<Buffer>>> {
2674 let guard = self.retain_remotely_created_models(cx);
2675 let Some(ssh_client) = self.ssh_client.as_ref() else {
2676 return Task::ready(Err(anyhow!("not an ssh project")));
2677 };
2678
2679 let proto_client = ssh_client.read(cx).proto_client();
2680
2681 cx.spawn(|this, mut cx| async move {
2682 let buffer = proto_client
2683 .request(proto::OpenServerSettings {
2684 project_id: SSH_PROJECT_ID,
2685 })
2686 .await?;
2687
2688 let buffer = this
2689 .update(&mut cx, |this, cx| {
2690 anyhow::Ok(this.wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx))
2691 })??
2692 .await;
2693
2694 drop(guard);
2695 buffer
2696 })
2697 }
2698
2699 pub fn open_local_buffer_via_lsp(
2700 &mut self,
2701 abs_path: lsp::Url,
2702 language_server_id: LanguageServerId,
2703 language_server_name: LanguageServerName,
2704 cx: &mut ModelContext<Self>,
2705 ) -> Task<Result<Model<Buffer>>> {
2706 self.lsp_store.update(cx, |lsp_store, cx| {
2707 lsp_store.open_local_buffer_via_lsp(
2708 abs_path,
2709 language_server_id,
2710 language_server_name,
2711 cx,
2712 )
2713 })
2714 }
2715
2716 pub fn signature_help<T: ToPointUtf16>(
2717 &self,
2718 buffer: &Model<Buffer>,
2719 position: T,
2720 cx: &mut ModelContext<Self>,
2721 ) -> Task<Vec<SignatureHelp>> {
2722 self.lsp_store.update(cx, |lsp_store, cx| {
2723 lsp_store.signature_help(buffer, position, cx)
2724 })
2725 }
2726
2727 pub fn hover<T: ToPointUtf16>(
2728 &self,
2729 buffer: &Model<Buffer>,
2730 position: T,
2731 cx: &mut ModelContext<Self>,
2732 ) -> Task<Vec<Hover>> {
2733 let position = position.to_point_utf16(buffer.read(cx));
2734 self.lsp_store
2735 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
2736 }
2737
2738 pub fn linked_edit(
2739 &self,
2740 buffer: &Model<Buffer>,
2741 position: Anchor,
2742 cx: &mut ModelContext<Self>,
2743 ) -> Task<Result<Vec<Range<Anchor>>>> {
2744 self.lsp_store.update(cx, |lsp_store, cx| {
2745 lsp_store.linked_edit(buffer, position, cx)
2746 })
2747 }
2748
2749 pub fn completions<T: ToOffset + ToPointUtf16>(
2750 &self,
2751 buffer: &Model<Buffer>,
2752 position: T,
2753 context: CompletionContext,
2754 cx: &mut ModelContext<Self>,
2755 ) -> Task<Result<Vec<Completion>>> {
2756 let position = position.to_point_utf16(buffer.read(cx));
2757 self.lsp_store.update(cx, |lsp_store, cx| {
2758 lsp_store.completions(buffer, position, context, cx)
2759 })
2760 }
2761
2762 pub fn resolve_completions(
2763 &self,
2764 buffer: Model<Buffer>,
2765 completion_indices: Vec<usize>,
2766 completions: Arc<RwLock<Box<[Completion]>>>,
2767 cx: &mut ModelContext<Self>,
2768 ) -> Task<Result<bool>> {
2769 self.lsp_store.update(cx, |lsp_store, cx| {
2770 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
2771 })
2772 }
2773
2774 pub fn apply_additional_edits_for_completion(
2775 &self,
2776 buffer_handle: Model<Buffer>,
2777 completion: Completion,
2778 push_to_history: bool,
2779 cx: &mut ModelContext<Self>,
2780 ) -> Task<Result<Option<Transaction>>> {
2781 self.lsp_store.update(cx, |lsp_store, cx| {
2782 lsp_store.apply_additional_edits_for_completion(
2783 buffer_handle,
2784 completion,
2785 push_to_history,
2786 cx,
2787 )
2788 })
2789 }
2790
2791 pub fn code_actions<T: Clone + ToOffset>(
2792 &mut self,
2793 buffer_handle: &Model<Buffer>,
2794 range: Range<T>,
2795 cx: &mut ModelContext<Self>,
2796 ) -> Task<Result<Vec<CodeAction>>> {
2797 let buffer = buffer_handle.read(cx);
2798 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2799 self.lsp_store.update(cx, |lsp_store, cx| {
2800 lsp_store.code_actions(buffer_handle, range, cx)
2801 })
2802 }
2803
2804 pub fn apply_code_action(
2805 &self,
2806 buffer_handle: Model<Buffer>,
2807 action: CodeAction,
2808 push_to_history: bool,
2809 cx: &mut ModelContext<Self>,
2810 ) -> Task<Result<ProjectTransaction>> {
2811 self.lsp_store.update(cx, |lsp_store, cx| {
2812 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
2813 })
2814 }
2815
2816 fn prepare_rename_impl(
2817 &mut self,
2818 buffer: Model<Buffer>,
2819 position: PointUtf16,
2820 cx: &mut ModelContext<Self>,
2821 ) -> Task<Result<Option<Range<Anchor>>>> {
2822 self.request_lsp(
2823 buffer,
2824 LanguageServerToQuery::Primary,
2825 PrepareRename { position },
2826 cx,
2827 )
2828 }
2829 pub fn prepare_rename<T: ToPointUtf16>(
2830 &mut self,
2831 buffer: Model<Buffer>,
2832 position: T,
2833 cx: &mut ModelContext<Self>,
2834 ) -> Task<Result<Option<Range<Anchor>>>> {
2835 let position = position.to_point_utf16(buffer.read(cx));
2836 self.prepare_rename_impl(buffer, position, cx)
2837 }
2838
2839 fn perform_rename_impl(
2840 &mut self,
2841 buffer: Model<Buffer>,
2842 position: PointUtf16,
2843 new_name: String,
2844 push_to_history: bool,
2845 cx: &mut ModelContext<Self>,
2846 ) -> Task<Result<ProjectTransaction>> {
2847 let position = position.to_point_utf16(buffer.read(cx));
2848 self.request_lsp(
2849 buffer,
2850 LanguageServerToQuery::Primary,
2851 PerformRename {
2852 position,
2853 new_name,
2854 push_to_history,
2855 },
2856 cx,
2857 )
2858 }
2859
2860 pub fn perform_rename<T: ToPointUtf16>(
2861 &mut self,
2862 buffer: Model<Buffer>,
2863 position: T,
2864 new_name: String,
2865 cx: &mut ModelContext<Self>,
2866 ) -> Task<Result<ProjectTransaction>> {
2867 let position = position.to_point_utf16(buffer.read(cx));
2868 self.perform_rename_impl(buffer, position, new_name, true, cx)
2869 }
2870
2871 pub fn on_type_format<T: ToPointUtf16>(
2872 &mut self,
2873 buffer: Model<Buffer>,
2874 position: T,
2875 trigger: String,
2876 push_to_history: bool,
2877 cx: &mut ModelContext<Self>,
2878 ) -> Task<Result<Option<Transaction>>> {
2879 self.lsp_store.update(cx, |lsp_store, cx| {
2880 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
2881 })
2882 }
2883
2884 pub fn inlay_hints<T: ToOffset>(
2885 &mut self,
2886 buffer_handle: Model<Buffer>,
2887 range: Range<T>,
2888 cx: &mut ModelContext<Self>,
2889 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
2890 let buffer = buffer_handle.read(cx);
2891 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2892 self.lsp_store.update(cx, |lsp_store, cx| {
2893 lsp_store.inlay_hints(buffer_handle, range, cx)
2894 })
2895 }
2896
2897 pub fn resolve_inlay_hint(
2898 &self,
2899 hint: InlayHint,
2900 buffer_handle: Model<Buffer>,
2901 server_id: LanguageServerId,
2902 cx: &mut ModelContext<Self>,
2903 ) -> Task<anyhow::Result<InlayHint>> {
2904 self.lsp_store.update(cx, |lsp_store, cx| {
2905 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
2906 })
2907 }
2908
2909 pub fn search(
2910 &mut self,
2911 query: SearchQuery,
2912 cx: &mut ModelContext<Self>,
2913 ) -> Receiver<SearchResult> {
2914 let (result_tx, result_rx) = smol::channel::unbounded();
2915
2916 let matching_buffers_rx = if query.is_opened_only() {
2917 self.sort_search_candidates(&query, cx)
2918 } else {
2919 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
2920 };
2921
2922 cx.spawn(|_, cx| async move {
2923 let mut range_count = 0;
2924 let mut buffer_count = 0;
2925 let mut limit_reached = false;
2926 let query = Arc::new(query);
2927 let mut chunks = matching_buffers_rx.ready_chunks(64);
2928
2929 // Now that we know what paths match the query, we will load at most
2930 // 64 buffers at a time to avoid overwhelming the main thread. For each
2931 // opened buffer, we will spawn a background task that retrieves all the
2932 // ranges in the buffer matched by the query.
2933 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
2934 let mut chunk_results = Vec::new();
2935 for buffer in matching_buffer_chunk {
2936 let buffer = buffer.clone();
2937 let query = query.clone();
2938 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
2939 chunk_results.push(cx.background_executor().spawn(async move {
2940 let ranges = query
2941 .search(&snapshot, None)
2942 .await
2943 .iter()
2944 .map(|range| {
2945 snapshot.anchor_before(range.start)
2946 ..snapshot.anchor_after(range.end)
2947 })
2948 .collect::<Vec<_>>();
2949 anyhow::Ok((buffer, ranges))
2950 }));
2951 }
2952
2953 let chunk_results = futures::future::join_all(chunk_results).await;
2954 for result in chunk_results {
2955 if let Some((buffer, ranges)) = result.log_err() {
2956 range_count += ranges.len();
2957 buffer_count += 1;
2958 result_tx
2959 .send(SearchResult::Buffer { buffer, ranges })
2960 .await?;
2961 if buffer_count > MAX_SEARCH_RESULT_FILES
2962 || range_count > MAX_SEARCH_RESULT_RANGES
2963 {
2964 limit_reached = true;
2965 break 'outer;
2966 }
2967 }
2968 }
2969 }
2970
2971 if limit_reached {
2972 result_tx.send(SearchResult::LimitReached).await?;
2973 }
2974
2975 anyhow::Ok(())
2976 })
2977 .detach();
2978
2979 result_rx
2980 }
2981
2982 fn find_search_candidate_buffers(
2983 &mut self,
2984 query: &SearchQuery,
2985 limit: usize,
2986 cx: &mut ModelContext<Project>,
2987 ) -> Receiver<Model<Buffer>> {
2988 if self.is_local() {
2989 let fs = self.fs.clone();
2990 self.buffer_store.update(cx, |buffer_store, cx| {
2991 buffer_store.find_search_candidates(query, limit, fs, cx)
2992 })
2993 } else {
2994 self.find_search_candidates_remote(query, limit, cx)
2995 }
2996 }
2997
2998 fn sort_search_candidates(
2999 &mut self,
3000 search_query: &SearchQuery,
3001 cx: &mut ModelContext<Project>,
3002 ) -> Receiver<Model<Buffer>> {
3003 let worktree_store = self.worktree_store.read(cx);
3004 let mut buffers = search_query
3005 .buffers()
3006 .into_iter()
3007 .flatten()
3008 .filter(|buffer| {
3009 let b = buffer.read(cx);
3010 if let Some(file) = b.file() {
3011 if !search_query.file_matches(file.path()) {
3012 return false;
3013 }
3014 if let Some(entry) = b
3015 .entry_id(cx)
3016 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3017 {
3018 if entry.is_ignored && !search_query.include_ignored() {
3019 return false;
3020 }
3021 }
3022 }
3023 true
3024 })
3025 .collect::<Vec<_>>();
3026 let (tx, rx) = smol::channel::unbounded();
3027 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3028 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3029 (None, Some(_)) => std::cmp::Ordering::Less,
3030 (Some(_), None) => std::cmp::Ordering::Greater,
3031 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3032 });
3033 for buffer in buffers {
3034 tx.send_blocking(buffer.clone()).unwrap()
3035 }
3036
3037 rx
3038 }
3039
3040 fn find_search_candidates_remote(
3041 &mut self,
3042 query: &SearchQuery,
3043 limit: usize,
3044 cx: &mut ModelContext<Project>,
3045 ) -> Receiver<Model<Buffer>> {
3046 let (tx, rx) = smol::channel::unbounded();
3047
3048 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3049 (ssh_client.read(cx).proto_client(), 0)
3050 } else if let Some(remote_id) = self.remote_id() {
3051 (self.client.clone().into(), remote_id)
3052 } else {
3053 return rx;
3054 };
3055
3056 let request = client.request(proto::FindSearchCandidates {
3057 project_id: remote_id,
3058 query: Some(query.to_proto()),
3059 limit: limit as _,
3060 });
3061 let guard = self.retain_remotely_created_models(cx);
3062
3063 cx.spawn(move |this, mut cx| async move {
3064 let response = request.await?;
3065 for buffer_id in response.buffer_ids {
3066 let buffer_id = BufferId::new(buffer_id)?;
3067 let buffer = this
3068 .update(&mut cx, |this, cx| {
3069 this.wait_for_remote_buffer(buffer_id, cx)
3070 })?
3071 .await?;
3072 let _ = tx.send(buffer).await;
3073 }
3074
3075 drop(guard);
3076 anyhow::Ok(())
3077 })
3078 .detach_and_log_err(cx);
3079 rx
3080 }
3081
3082 pub fn request_lsp<R: LspCommand>(
3083 &mut self,
3084 buffer_handle: Model<Buffer>,
3085 server: LanguageServerToQuery,
3086 request: R,
3087 cx: &mut ModelContext<Self>,
3088 ) -> Task<Result<R::Response>>
3089 where
3090 <R::LspRequest as lsp::request::Request>::Result: Send,
3091 <R::LspRequest as lsp::request::Request>::Params: Send,
3092 {
3093 let guard = self.retain_remotely_created_models(cx);
3094 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3095 lsp_store.request_lsp(buffer_handle, server, request, cx)
3096 });
3097 cx.spawn(|_, _| async move {
3098 let result = task.await;
3099 drop(guard);
3100 result
3101 })
3102 }
3103
3104 /// Move a worktree to a new position in the worktree order.
3105 ///
3106 /// The worktree will moved to the opposite side of the destination worktree.
3107 ///
3108 /// # Example
3109 ///
3110 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3111 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3112 ///
3113 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3114 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3115 ///
3116 /// # Errors
3117 ///
3118 /// An error will be returned if the worktree or destination worktree are not found.
3119 pub fn move_worktree(
3120 &mut self,
3121 source: WorktreeId,
3122 destination: WorktreeId,
3123 cx: &mut ModelContext<'_, Self>,
3124 ) -> Result<()> {
3125 self.worktree_store.update(cx, |worktree_store, cx| {
3126 worktree_store.move_worktree(source, destination, cx)
3127 })
3128 }
3129
3130 pub fn find_or_create_worktree(
3131 &mut self,
3132 abs_path: impl AsRef<Path>,
3133 visible: bool,
3134 cx: &mut ModelContext<Self>,
3135 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
3136 self.worktree_store.update(cx, |worktree_store, cx| {
3137 worktree_store.find_or_create_worktree(abs_path, visible, cx)
3138 })
3139 }
3140
3141 pub fn find_worktree(
3142 &self,
3143 abs_path: &Path,
3144 cx: &AppContext,
3145 ) -> Option<(Model<Worktree>, PathBuf)> {
3146 self.worktree_store.read_with(cx, |worktree_store, cx| {
3147 worktree_store.find_worktree(abs_path, cx)
3148 })
3149 }
3150
3151 pub fn is_shared(&self) -> bool {
3152 match &self.client_state {
3153 ProjectClientState::Shared { .. } => true,
3154 ProjectClientState::Local => false,
3155 ProjectClientState::Remote { in_room, .. } => *in_room,
3156 }
3157 }
3158
3159 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3160 pub fn resolve_existing_file_path(
3161 &self,
3162 path: &str,
3163 buffer: &Model<Buffer>,
3164 cx: &mut ModelContext<Self>,
3165 ) -> Task<Option<ResolvedPath>> {
3166 let path_buf = PathBuf::from(path);
3167 if path_buf.is_absolute() || path.starts_with("~") {
3168 self.resolve_abs_file_path(path, cx)
3169 } else {
3170 self.resolve_path_in_worktrees(path_buf, buffer, cx)
3171 }
3172 }
3173
3174 pub fn abs_file_path_exists(&self, path: &str, cx: &mut ModelContext<Self>) -> Task<bool> {
3175 let resolve_task = self.resolve_abs_file_path(path, cx);
3176 cx.background_executor().spawn(async move {
3177 let resolved_path = resolve_task.await;
3178 resolved_path.is_some()
3179 })
3180 }
3181
3182 fn resolve_abs_file_path(
3183 &self,
3184 path: &str,
3185 cx: &mut ModelContext<Self>,
3186 ) -> Task<Option<ResolvedPath>> {
3187 if self.is_local() {
3188 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3189
3190 let fs = self.fs.clone();
3191 cx.background_executor().spawn(async move {
3192 let path = expanded.as_path();
3193 let exists = fs.is_file(path).await;
3194
3195 exists.then(|| ResolvedPath::AbsPath(expanded))
3196 })
3197 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3198 let request = ssh_client
3199 .read(cx)
3200 .proto_client()
3201 .request(proto::CheckFileExists {
3202 project_id: SSH_PROJECT_ID,
3203 path: path.to_string(),
3204 });
3205 cx.background_executor().spawn(async move {
3206 let response = request.await.log_err()?;
3207 if response.exists {
3208 Some(ResolvedPath::AbsPath(PathBuf::from(response.path)))
3209 } else {
3210 None
3211 }
3212 })
3213 } else {
3214 return Task::ready(None);
3215 }
3216 }
3217
3218 fn resolve_path_in_worktrees(
3219 &self,
3220 path: PathBuf,
3221 buffer: &Model<Buffer>,
3222 cx: &mut ModelContext<Self>,
3223 ) -> Task<Option<ResolvedPath>> {
3224 let mut candidates = vec![path.clone()];
3225
3226 if let Some(file) = buffer.read(cx).file() {
3227 if let Some(dir) = file.path().parent() {
3228 let joined = dir.to_path_buf().join(path);
3229 candidates.push(joined);
3230 }
3231 }
3232
3233 let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3234 cx.spawn(|_, mut cx| async move {
3235 for worktree in worktrees {
3236 for candidate in candidates.iter() {
3237 let path = worktree
3238 .update(&mut cx, |worktree, _| {
3239 let root_entry_path = &worktree.root_entry()?.path;
3240
3241 let resolved = resolve_path(root_entry_path, candidate);
3242
3243 let stripped =
3244 resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3245
3246 worktree.entry_for_path(stripped).map(|entry| {
3247 ResolvedPath::ProjectPath(ProjectPath {
3248 worktree_id: worktree.id(),
3249 path: entry.path.clone(),
3250 })
3251 })
3252 })
3253 .ok()?;
3254
3255 if path.is_some() {
3256 return path;
3257 }
3258 }
3259 }
3260 None
3261 })
3262 }
3263
3264 pub fn list_directory(
3265 &self,
3266 query: String,
3267 cx: &mut ModelContext<Self>,
3268 ) -> Task<Result<Vec<PathBuf>>> {
3269 if self.is_local() {
3270 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3271 } else if let Some(session) = self.ssh_client.as_ref() {
3272 let request = proto::ListRemoteDirectory {
3273 dev_server_id: SSH_PROJECT_ID,
3274 path: query,
3275 };
3276
3277 let response = session.read(cx).proto_client().request(request);
3278 cx.background_executor().spawn(async move {
3279 let response = response.await?;
3280 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3281 })
3282 } else if let Some(dev_server) = self.dev_server_project_id().and_then(|id| {
3283 dev_server_projects::Store::global(cx)
3284 .read(cx)
3285 .dev_server_for_project(id)
3286 }) {
3287 let request = proto::ListRemoteDirectory {
3288 dev_server_id: dev_server.id.0,
3289 path: query,
3290 };
3291 let response = self.client.request(request);
3292 cx.background_executor().spawn(async move {
3293 let response = response.await?;
3294 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3295 })
3296 } else {
3297 Task::ready(Err(anyhow!("cannot list directory in remote project")))
3298 }
3299 }
3300
3301 pub fn create_worktree(
3302 &mut self,
3303 abs_path: impl AsRef<Path>,
3304 visible: bool,
3305 cx: &mut ModelContext<Self>,
3306 ) -> Task<Result<Model<Worktree>>> {
3307 self.worktree_store.update(cx, |worktree_store, cx| {
3308 worktree_store.create_worktree(abs_path, visible, cx)
3309 })
3310 }
3311
3312 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
3313 self.worktree_store.update(cx, |worktree_store, cx| {
3314 worktree_store.remove_worktree(id_to_remove, cx);
3315 });
3316 }
3317
3318 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
3319 self.worktree_store.update(cx, |worktree_store, cx| {
3320 worktree_store.add(worktree, cx);
3321 });
3322 }
3323
3324 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
3325 let new_active_entry = entry.and_then(|project_path| {
3326 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3327 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3328 Some(entry.id)
3329 });
3330 if new_active_entry != self.active_entry {
3331 self.active_entry = new_active_entry;
3332 self.lsp_store.update(cx, |lsp_store, _| {
3333 lsp_store.set_active_entry(new_active_entry);
3334 });
3335 cx.emit(Event::ActiveEntryChanged(new_active_entry));
3336 }
3337 }
3338
3339 pub fn language_servers_running_disk_based_diagnostics<'a>(
3340 &'a self,
3341 cx: &'a AppContext,
3342 ) -> impl Iterator<Item = LanguageServerId> + 'a {
3343 self.lsp_store
3344 .read(cx)
3345 .language_servers_running_disk_based_diagnostics()
3346 }
3347
3348 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
3349 let mut summary = DiagnosticSummary::default();
3350 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
3351 summary.error_count += path_summary.error_count;
3352 summary.warning_count += path_summary.warning_count;
3353 }
3354 summary
3355 }
3356
3357 pub fn diagnostic_summaries<'a>(
3358 &'a self,
3359 include_ignored: bool,
3360 cx: &'a AppContext,
3361 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3362 self.lsp_store
3363 .read(cx)
3364 .diagnostic_summaries(include_ignored, cx)
3365 }
3366
3367 pub fn active_entry(&self) -> Option<ProjectEntryId> {
3368 self.active_entry
3369 }
3370
3371 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
3372 self.worktree_store.read(cx).entry_for_path(path, cx)
3373 }
3374
3375 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
3376 let worktree = self.worktree_for_entry(entry_id, cx)?;
3377 let worktree = worktree.read(cx);
3378 let worktree_id = worktree.id();
3379 let path = worktree.entry_for_id(entry_id)?.path.clone();
3380 Some(ProjectPath { worktree_id, path })
3381 }
3382
3383 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
3384 let workspace_root = self
3385 .worktree_for_id(project_path.worktree_id, cx)?
3386 .read(cx)
3387 .abs_path();
3388 let project_path = project_path.path.as_ref();
3389
3390 Some(if project_path == Path::new("") {
3391 workspace_root.to_path_buf()
3392 } else {
3393 workspace_root.join(project_path)
3394 })
3395 }
3396
3397 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3398 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3399 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3400 /// the first visible worktree that has an entry for that relative path.
3401 ///
3402 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3403 /// root name from paths.
3404 ///
3405 /// # Arguments
3406 ///
3407 /// * `path` - A full path that starts with a worktree root name, or alternatively a
3408 /// relative path within a visible worktree.
3409 /// * `cx` - A reference to the `AppContext`.
3410 ///
3411 /// # Returns
3412 ///
3413 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3414 pub fn find_project_path(&self, path: &Path, cx: &AppContext) -> Option<ProjectPath> {
3415 let worktree_store = self.worktree_store.read(cx);
3416
3417 for worktree in worktree_store.visible_worktrees(cx) {
3418 let worktree_root_name = worktree.read(cx).root_name();
3419 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3420 return Some(ProjectPath {
3421 worktree_id: worktree.read(cx).id(),
3422 path: relative_path.into(),
3423 });
3424 }
3425 }
3426
3427 for worktree in worktree_store.visible_worktrees(cx) {
3428 let worktree = worktree.read(cx);
3429 if let Some(entry) = worktree.entry_for_path(path) {
3430 return Some(ProjectPath {
3431 worktree_id: worktree.id(),
3432 path: entry.path.clone(),
3433 });
3434 }
3435 }
3436
3437 None
3438 }
3439
3440 pub fn get_workspace_root(
3441 &self,
3442 project_path: &ProjectPath,
3443 cx: &AppContext,
3444 ) -> Option<PathBuf> {
3445 Some(
3446 self.worktree_for_id(project_path.worktree_id, cx)?
3447 .read(cx)
3448 .abs_path()
3449 .to_path_buf(),
3450 )
3451 }
3452
3453 pub fn get_repo(
3454 &self,
3455 project_path: &ProjectPath,
3456 cx: &AppContext,
3457 ) -> Option<Arc<dyn GitRepository>> {
3458 self.worktree_for_id(project_path.worktree_id, cx)?
3459 .read(cx)
3460 .as_local()?
3461 .local_git_repo(&project_path.path)
3462 }
3463
3464 pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
3465 let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
3466 let root_entry = worktree.root_git_entry()?;
3467 worktree.get_local_repo(&root_entry)?.repo().clone().into()
3468 }
3469
3470 pub fn blame_buffer(
3471 &self,
3472 buffer: &Model<Buffer>,
3473 version: Option<clock::Global>,
3474 cx: &AppContext,
3475 ) -> Task<Result<Blame>> {
3476 self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
3477 }
3478
3479 pub fn get_permalink_to_line(
3480 &self,
3481 buffer: &Model<Buffer>,
3482 selection: Range<u32>,
3483 cx: &AppContext,
3484 ) -> Task<Result<url::Url>> {
3485 self.buffer_store
3486 .read(cx)
3487 .get_permalink_to_line(buffer, selection, cx)
3488 }
3489
3490 // RPC message handlers
3491
3492 async fn handle_unshare_project(
3493 this: Model<Self>,
3494 _: TypedEnvelope<proto::UnshareProject>,
3495 mut cx: AsyncAppContext,
3496 ) -> Result<()> {
3497 this.update(&mut cx, |this, cx| {
3498 if this.is_local() || this.is_via_ssh() {
3499 this.unshare(cx)?;
3500 } else {
3501 this.disconnected_from_host(cx);
3502 }
3503 Ok(())
3504 })?
3505 }
3506
3507 async fn handle_add_collaborator(
3508 this: Model<Self>,
3509 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3510 mut cx: AsyncAppContext,
3511 ) -> Result<()> {
3512 let collaborator = envelope
3513 .payload
3514 .collaborator
3515 .take()
3516 .ok_or_else(|| anyhow!("empty collaborator"))?;
3517
3518 let collaborator = Collaborator::from_proto(collaborator)?;
3519 this.update(&mut cx, |this, cx| {
3520 this.buffer_store.update(cx, |buffer_store, _| {
3521 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
3522 });
3523 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
3524 this.collaborators
3525 .insert(collaborator.peer_id, collaborator);
3526 cx.notify();
3527 })?;
3528
3529 Ok(())
3530 }
3531
3532 async fn handle_update_project_collaborator(
3533 this: Model<Self>,
3534 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
3535 mut cx: AsyncAppContext,
3536 ) -> Result<()> {
3537 let old_peer_id = envelope
3538 .payload
3539 .old_peer_id
3540 .ok_or_else(|| anyhow!("missing old peer id"))?;
3541 let new_peer_id = envelope
3542 .payload
3543 .new_peer_id
3544 .ok_or_else(|| anyhow!("missing new peer id"))?;
3545 this.update(&mut cx, |this, cx| {
3546 let collaborator = this
3547 .collaborators
3548 .remove(&old_peer_id)
3549 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
3550 let is_host = collaborator.replica_id == 0;
3551 this.collaborators.insert(new_peer_id, collaborator);
3552
3553 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
3554 this.buffer_store.update(cx, |buffer_store, _| {
3555 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
3556 });
3557
3558 if is_host {
3559 this.buffer_store
3560 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
3561 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
3562 .unwrap();
3563 cx.emit(Event::HostReshared);
3564 }
3565
3566 cx.emit(Event::CollaboratorUpdated {
3567 old_peer_id,
3568 new_peer_id,
3569 });
3570 cx.notify();
3571 Ok(())
3572 })?
3573 }
3574
3575 async fn handle_remove_collaborator(
3576 this: Model<Self>,
3577 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3578 mut cx: AsyncAppContext,
3579 ) -> Result<()> {
3580 this.update(&mut cx, |this, cx| {
3581 let peer_id = envelope
3582 .payload
3583 .peer_id
3584 .ok_or_else(|| anyhow!("invalid peer id"))?;
3585 let replica_id = this
3586 .collaborators
3587 .remove(&peer_id)
3588 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3589 .replica_id;
3590 this.buffer_store.update(cx, |buffer_store, cx| {
3591 buffer_store.forget_shared_buffers_for(&peer_id);
3592 for buffer in buffer_store.buffers() {
3593 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3594 }
3595 });
3596
3597 cx.emit(Event::CollaboratorLeft(peer_id));
3598 cx.notify();
3599 Ok(())
3600 })?
3601 }
3602
3603 async fn handle_update_project(
3604 this: Model<Self>,
3605 envelope: TypedEnvelope<proto::UpdateProject>,
3606 mut cx: AsyncAppContext,
3607 ) -> Result<()> {
3608 this.update(&mut cx, |this, cx| {
3609 // Don't handle messages that were sent before the response to us joining the project
3610 if envelope.message_id > this.join_project_response_message_id {
3611 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
3612 }
3613 Ok(())
3614 })?
3615 }
3616
3617 async fn handle_toast(
3618 this: Model<Self>,
3619 envelope: TypedEnvelope<proto::Toast>,
3620 mut cx: AsyncAppContext,
3621 ) -> Result<()> {
3622 this.update(&mut cx, |_, cx| {
3623 cx.emit(Event::Toast {
3624 notification_id: envelope.payload.notification_id.into(),
3625 message: envelope.payload.message,
3626 });
3627 Ok(())
3628 })?
3629 }
3630
3631 async fn handle_language_server_prompt_request(
3632 this: Model<Self>,
3633 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
3634 mut cx: AsyncAppContext,
3635 ) -> Result<proto::LanguageServerPromptResponse> {
3636 let (tx, mut rx) = smol::channel::bounded(1);
3637 let actions: Vec<_> = envelope
3638 .payload
3639 .actions
3640 .into_iter()
3641 .map(|action| MessageActionItem {
3642 title: action,
3643 properties: Default::default(),
3644 })
3645 .collect();
3646 this.update(&mut cx, |_, cx| {
3647 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
3648 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
3649 message: envelope.payload.message,
3650 actions: actions.clone(),
3651 lsp_name: envelope.payload.lsp_name,
3652 response_channel: tx,
3653 }));
3654
3655 anyhow::Ok(())
3656 })??;
3657
3658 let answer = rx.next().await;
3659
3660 Ok(LanguageServerPromptResponse {
3661 action_response: answer.and_then(|answer| {
3662 actions
3663 .iter()
3664 .position(|action| *action == answer)
3665 .map(|index| index as u64)
3666 }),
3667 })
3668 }
3669
3670 async fn handle_hide_toast(
3671 this: Model<Self>,
3672 envelope: TypedEnvelope<proto::HideToast>,
3673 mut cx: AsyncAppContext,
3674 ) -> Result<()> {
3675 this.update(&mut cx, |_, cx| {
3676 cx.emit(Event::HideToast {
3677 notification_id: envelope.payload.notification_id.into(),
3678 });
3679 Ok(())
3680 })?
3681 }
3682
3683 // Collab sends UpdateWorktree protos as messages
3684 async fn handle_update_worktree(
3685 this: Model<Self>,
3686 envelope: TypedEnvelope<proto::UpdateWorktree>,
3687 mut cx: AsyncAppContext,
3688 ) -> Result<()> {
3689 this.update(&mut cx, |this, cx| {
3690 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3691 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3692 worktree.update(cx, |worktree, _| {
3693 let worktree = worktree.as_remote_mut().unwrap();
3694 worktree.update_from_remote(envelope.payload);
3695 });
3696 }
3697 Ok(())
3698 })?
3699 }
3700
3701 async fn handle_update_buffer(
3702 this: Model<Self>,
3703 envelope: TypedEnvelope<proto::UpdateBuffer>,
3704 cx: AsyncAppContext,
3705 ) -> Result<proto::Ack> {
3706 let buffer_store = this.read_with(&cx, |this, cx| {
3707 if let Some(ssh) = &this.ssh_client {
3708 let mut payload = envelope.payload.clone();
3709 payload.project_id = SSH_PROJECT_ID;
3710 cx.background_executor()
3711 .spawn(ssh.read(cx).proto_client().request(payload))
3712 .detach_and_log_err(cx);
3713 }
3714 this.buffer_store.clone()
3715 })?;
3716 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3717 }
3718
3719 fn retain_remotely_created_models(
3720 &mut self,
3721 cx: &mut ModelContext<Self>,
3722 ) -> RemotelyCreatedModelGuard {
3723 {
3724 let mut remotely_create_models = self.remotely_created_models.lock();
3725 if remotely_create_models.retain_count == 0 {
3726 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
3727 remotely_create_models.worktrees =
3728 self.worktree_store.read(cx).worktrees().collect();
3729 }
3730 remotely_create_models.retain_count += 1;
3731 }
3732 RemotelyCreatedModelGuard {
3733 remote_models: Arc::downgrade(&self.remotely_created_models),
3734 }
3735 }
3736
3737 async fn handle_create_buffer_for_peer(
3738 this: Model<Self>,
3739 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
3740 mut cx: AsyncAppContext,
3741 ) -> Result<()> {
3742 this.update(&mut cx, |this, cx| {
3743 this.buffer_store.update(cx, |buffer_store, cx| {
3744 buffer_store.handle_create_buffer_for_peer(
3745 envelope,
3746 this.replica_id(),
3747 this.capability(),
3748 cx,
3749 )
3750 })
3751 })?
3752 }
3753
3754 async fn handle_synchronize_buffers(
3755 this: Model<Self>,
3756 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
3757 mut cx: AsyncAppContext,
3758 ) -> Result<proto::SynchronizeBuffersResponse> {
3759 let response = this.update(&mut cx, |this, cx| {
3760 let client = this.client.clone();
3761 this.buffer_store.update(cx, |this, cx| {
3762 this.handle_synchronize_buffers(envelope, cx, client)
3763 })
3764 })??;
3765
3766 Ok(response)
3767 }
3768
3769 async fn handle_search_candidate_buffers(
3770 this: Model<Self>,
3771 envelope: TypedEnvelope<proto::FindSearchCandidates>,
3772 mut cx: AsyncAppContext,
3773 ) -> Result<proto::FindSearchCandidatesResponse> {
3774 let peer_id = envelope.original_sender_id()?;
3775 let message = envelope.payload;
3776 let query = SearchQuery::from_proto(
3777 message
3778 .query
3779 .ok_or_else(|| anyhow!("missing query field"))?,
3780 )?;
3781 let mut results = this.update(&mut cx, |this, cx| {
3782 this.find_search_candidate_buffers(&query, message.limit as _, cx)
3783 })?;
3784
3785 let mut response = proto::FindSearchCandidatesResponse {
3786 buffer_ids: Vec::new(),
3787 };
3788
3789 while let Some(buffer) = results.next().await {
3790 this.update(&mut cx, |this, cx| {
3791 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
3792 response.buffer_ids.push(buffer_id.to_proto());
3793 })?;
3794 }
3795
3796 Ok(response)
3797 }
3798
3799 async fn handle_open_buffer_by_id(
3800 this: Model<Self>,
3801 envelope: TypedEnvelope<proto::OpenBufferById>,
3802 mut cx: AsyncAppContext,
3803 ) -> Result<proto::OpenBufferResponse> {
3804 let peer_id = envelope.original_sender_id()?;
3805 let buffer_id = BufferId::new(envelope.payload.id)?;
3806 let buffer = this
3807 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
3808 .await?;
3809 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3810 }
3811
3812 async fn handle_open_buffer_by_path(
3813 this: Model<Self>,
3814 envelope: TypedEnvelope<proto::OpenBufferByPath>,
3815 mut cx: AsyncAppContext,
3816 ) -> Result<proto::OpenBufferResponse> {
3817 let peer_id = envelope.original_sender_id()?;
3818 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3819 let open_buffer = this.update(&mut cx, |this, cx| {
3820 this.open_buffer(
3821 ProjectPath {
3822 worktree_id,
3823 path: PathBuf::from(envelope.payload.path).into(),
3824 },
3825 cx,
3826 )
3827 })?;
3828
3829 let buffer = open_buffer.await?;
3830 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3831 }
3832
3833 async fn handle_open_new_buffer(
3834 this: Model<Self>,
3835 envelope: TypedEnvelope<proto::OpenNewBuffer>,
3836 mut cx: AsyncAppContext,
3837 ) -> Result<proto::OpenBufferResponse> {
3838 let buffer = this
3839 .update(&mut cx, |this, cx| this.create_buffer(cx))?
3840 .await?;
3841 let peer_id = envelope.original_sender_id()?;
3842
3843 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3844 }
3845
3846 fn respond_to_open_buffer_request(
3847 this: Model<Self>,
3848 buffer: Model<Buffer>,
3849 peer_id: proto::PeerId,
3850 cx: &mut AsyncAppContext,
3851 ) -> Result<proto::OpenBufferResponse> {
3852 this.update(cx, |this, cx| {
3853 let is_private = buffer
3854 .read(cx)
3855 .file()
3856 .map(|f| f.is_private())
3857 .unwrap_or_default();
3858 if is_private {
3859 Err(anyhow!(ErrorCode::UnsharedItem))
3860 } else {
3861 Ok(proto::OpenBufferResponse {
3862 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
3863 })
3864 }
3865 })?
3866 }
3867
3868 fn create_buffer_for_peer(
3869 &mut self,
3870 buffer: &Model<Buffer>,
3871 peer_id: proto::PeerId,
3872 cx: &mut AppContext,
3873 ) -> BufferId {
3874 self.buffer_store
3875 .update(cx, |buffer_store, cx| {
3876 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
3877 })
3878 .detach_and_log_err(cx);
3879 buffer.read(cx).remote_id()
3880 }
3881
3882 fn wait_for_remote_buffer(
3883 &mut self,
3884 id: BufferId,
3885 cx: &mut ModelContext<Self>,
3886 ) -> Task<Result<Model<Buffer>>> {
3887 self.buffer_store.update(cx, |buffer_store, cx| {
3888 buffer_store.wait_for_remote_buffer(id, cx)
3889 })
3890 }
3891
3892 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
3893 let project_id = match self.client_state {
3894 ProjectClientState::Remote {
3895 sharing_has_stopped,
3896 remote_id,
3897 ..
3898 } => {
3899 if sharing_has_stopped {
3900 return Task::ready(Err(anyhow!(
3901 "can't synchronize remote buffers on a readonly project"
3902 )));
3903 } else {
3904 remote_id
3905 }
3906 }
3907 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
3908 return Task::ready(Err(anyhow!(
3909 "can't synchronize remote buffers on a local project"
3910 )))
3911 }
3912 };
3913
3914 let client = self.client.clone();
3915 cx.spawn(move |this, mut cx| async move {
3916 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
3917 this.buffer_store.read(cx).buffer_version_info(cx)
3918 })?;
3919 let response = client
3920 .request(proto::SynchronizeBuffers {
3921 project_id,
3922 buffers,
3923 })
3924 .await?;
3925
3926 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
3927 response
3928 .buffers
3929 .into_iter()
3930 .map(|buffer| {
3931 let client = client.clone();
3932 let buffer_id = match BufferId::new(buffer.id) {
3933 Ok(id) => id,
3934 Err(e) => {
3935 return Task::ready(Err(e));
3936 }
3937 };
3938 let remote_version = language::proto::deserialize_version(&buffer.version);
3939 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
3940 let operations =
3941 buffer.read(cx).serialize_ops(Some(remote_version), cx);
3942 cx.background_executor().spawn(async move {
3943 let operations = operations.await;
3944 for chunk in split_operations(operations) {
3945 client
3946 .request(proto::UpdateBuffer {
3947 project_id,
3948 buffer_id: buffer_id.into(),
3949 operations: chunk,
3950 })
3951 .await?;
3952 }
3953 anyhow::Ok(())
3954 })
3955 } else {
3956 Task::ready(Ok(()))
3957 }
3958 })
3959 .collect::<Vec<_>>()
3960 })?;
3961
3962 // Any incomplete buffers have open requests waiting. Request that the host sends
3963 // creates these buffers for us again to unblock any waiting futures.
3964 for id in incomplete_buffer_ids {
3965 cx.background_executor()
3966 .spawn(client.request(proto::OpenBufferById {
3967 project_id,
3968 id: id.into(),
3969 }))
3970 .detach();
3971 }
3972
3973 futures::future::join_all(send_updates_for_buffers)
3974 .await
3975 .into_iter()
3976 .collect()
3977 })
3978 }
3979
3980 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
3981 self.worktree_store.read(cx).worktree_metadata_protos(cx)
3982 }
3983
3984 fn set_worktrees_from_proto(
3985 &mut self,
3986 worktrees: Vec<proto::WorktreeMetadata>,
3987 cx: &mut ModelContext<Project>,
3988 ) -> Result<()> {
3989 cx.notify();
3990 self.worktree_store.update(cx, |worktree_store, cx| {
3991 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
3992 })
3993 }
3994
3995 fn set_collaborators_from_proto(
3996 &mut self,
3997 messages: Vec<proto::Collaborator>,
3998 cx: &mut ModelContext<Self>,
3999 ) -> Result<()> {
4000 let mut collaborators = HashMap::default();
4001 for message in messages {
4002 let collaborator = Collaborator::from_proto(message)?;
4003 collaborators.insert(collaborator.peer_id, collaborator);
4004 }
4005 for old_peer_id in self.collaborators.keys() {
4006 if !collaborators.contains_key(old_peer_id) {
4007 cx.emit(Event::CollaboratorLeft(*old_peer_id));
4008 }
4009 }
4010 self.collaborators = collaborators;
4011 Ok(())
4012 }
4013
4014 pub fn language_servers<'a>(
4015 &'a self,
4016 cx: &'a AppContext,
4017 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
4018 self.lsp_store.read(cx).language_servers()
4019 }
4020
4021 pub fn supplementary_language_servers<'a>(
4022 &'a self,
4023 cx: &'a AppContext,
4024 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4025 self.lsp_store.read(cx).supplementary_language_servers()
4026 }
4027
4028 pub fn language_server_for_id(
4029 &self,
4030 id: LanguageServerId,
4031 cx: &AppContext,
4032 ) -> Option<Arc<LanguageServer>> {
4033 self.lsp_store.read(cx).language_server_for_id(id)
4034 }
4035
4036 pub fn language_servers_for_buffer<'a>(
4037 &'a self,
4038 buffer: &'a Buffer,
4039 cx: &'a AppContext,
4040 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4041 self.lsp_store
4042 .read(cx)
4043 .language_servers_for_buffer(buffer, cx)
4044 }
4045}
4046
4047fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
4048 code_actions
4049 .iter()
4050 .flat_map(|(kind, enabled)| {
4051 if *enabled {
4052 Some(kind.clone().into())
4053 } else {
4054 None
4055 }
4056 })
4057 .collect()
4058}
4059
4060pub struct PathMatchCandidateSet {
4061 pub snapshot: Snapshot,
4062 pub include_ignored: bool,
4063 pub include_root_name: bool,
4064 pub candidates: Candidates,
4065}
4066
4067pub enum Candidates {
4068 /// Only consider directories.
4069 Directories,
4070 /// Only consider files.
4071 Files,
4072 /// Consider directories and files.
4073 Entries,
4074}
4075
4076impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4077 type Candidates = PathMatchCandidateSetIter<'a>;
4078
4079 fn id(&self) -> usize {
4080 self.snapshot.id().to_usize()
4081 }
4082
4083 fn len(&self) -> usize {
4084 match self.candidates {
4085 Candidates::Files => {
4086 if self.include_ignored {
4087 self.snapshot.file_count()
4088 } else {
4089 self.snapshot.visible_file_count()
4090 }
4091 }
4092
4093 Candidates::Directories => {
4094 if self.include_ignored {
4095 self.snapshot.dir_count()
4096 } else {
4097 self.snapshot.visible_dir_count()
4098 }
4099 }
4100
4101 Candidates::Entries => {
4102 if self.include_ignored {
4103 self.snapshot.entry_count()
4104 } else {
4105 self.snapshot.visible_entry_count()
4106 }
4107 }
4108 }
4109 }
4110
4111 fn prefix(&self) -> Arc<str> {
4112 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4113 self.snapshot.root_name().into()
4114 } else if self.include_root_name {
4115 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4116 } else {
4117 Arc::default()
4118 }
4119 }
4120
4121 fn candidates(&'a self, start: usize) -> Self::Candidates {
4122 PathMatchCandidateSetIter {
4123 traversal: match self.candidates {
4124 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4125 Candidates::Files => self.snapshot.files(self.include_ignored, start),
4126 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4127 },
4128 }
4129 }
4130}
4131
4132pub struct PathMatchCandidateSetIter<'a> {
4133 traversal: Traversal<'a>,
4134}
4135
4136impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4137 type Item = fuzzy::PathMatchCandidate<'a>;
4138
4139 fn next(&mut self) -> Option<Self::Item> {
4140 self.traversal
4141 .next()
4142 .map(|entry| fuzzy::PathMatchCandidate {
4143 is_dir: entry.kind.is_dir(),
4144 path: &entry.path,
4145 char_bag: entry.char_bag,
4146 })
4147 }
4148}
4149
4150impl EventEmitter<Event> for Project {}
4151
4152impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4153 fn from(val: &'a ProjectPath) -> Self {
4154 SettingsLocation {
4155 worktree_id: val.worktree_id,
4156 path: val.path.as_ref(),
4157 }
4158 }
4159}
4160
4161impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4162 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4163 Self {
4164 worktree_id,
4165 path: path.as_ref().into(),
4166 }
4167 }
4168}
4169
4170pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4171 let mut path_components = path.components();
4172 let mut base_components = base.components();
4173 let mut components: Vec<Component> = Vec::new();
4174 loop {
4175 match (path_components.next(), base_components.next()) {
4176 (None, None) => break,
4177 (Some(a), None) => {
4178 components.push(a);
4179 components.extend(path_components.by_ref());
4180 break;
4181 }
4182 (None, _) => components.push(Component::ParentDir),
4183 (Some(a), Some(b)) if components.is_empty() && a == b => (),
4184 (Some(a), Some(Component::CurDir)) => components.push(a),
4185 (Some(a), Some(_)) => {
4186 components.push(Component::ParentDir);
4187 for _ in base_components {
4188 components.push(Component::ParentDir);
4189 }
4190 components.push(a);
4191 components.extend(path_components.by_ref());
4192 break;
4193 }
4194 }
4195 }
4196 components.iter().map(|c| c.as_os_str()).collect()
4197}
4198
4199fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4200 let mut result = base.to_path_buf();
4201 for component in path.components() {
4202 match component {
4203 Component::ParentDir => {
4204 result.pop();
4205 }
4206 Component::CurDir => (),
4207 _ => result.push(component),
4208 }
4209 }
4210 result
4211}
4212
4213/// ResolvedPath is a path that has been resolved to either a ProjectPath
4214/// or an AbsPath and that *exists*.
4215#[derive(Debug, Clone)]
4216pub enum ResolvedPath {
4217 ProjectPath(ProjectPath),
4218 AbsPath(PathBuf),
4219}
4220
4221impl ResolvedPath {
4222 pub fn abs_path(&self) -> Option<&Path> {
4223 match self {
4224 Self::AbsPath(path) => Some(path.as_path()),
4225 _ => None,
4226 }
4227 }
4228
4229 pub fn project_path(&self) -> Option<&ProjectPath> {
4230 match self {
4231 Self::ProjectPath(path) => Some(&path),
4232 _ => None,
4233 }
4234 }
4235}
4236
4237impl Item for Buffer {
4238 fn try_open(
4239 project: &Model<Project>,
4240 path: &ProjectPath,
4241 cx: &mut AppContext,
4242 ) -> Option<Task<Result<Model<Self>>>> {
4243 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4244 }
4245
4246 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
4247 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4248 }
4249
4250 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
4251 File::from_dyn(self.file()).map(|file| ProjectPath {
4252 worktree_id: file.worktree_id(cx),
4253 path: file.path().clone(),
4254 })
4255 }
4256}
4257
4258impl Completion {
4259 /// A key that can be used to sort completions when displaying
4260 /// them to the user.
4261 pub fn sort_key(&self) -> (usize, &str) {
4262 let kind_key = match self.lsp_completion.kind {
4263 Some(lsp::CompletionItemKind::KEYWORD) => 0,
4264 Some(lsp::CompletionItemKind::VARIABLE) => 1,
4265 _ => 2,
4266 };
4267 (kind_key, &self.label.text[self.label.filter_range.clone()])
4268 }
4269
4270 /// Whether this completion is a snippet.
4271 pub fn is_snippet(&self) -> bool {
4272 self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4273 }
4274
4275 /// Returns the corresponding color for this completion.
4276 ///
4277 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4278 pub fn color(&self) -> Option<Hsla> {
4279 match self.lsp_completion.kind {
4280 Some(CompletionItemKind::COLOR) => color_extractor::extract_color(&self.lsp_completion),
4281 _ => None,
4282 }
4283 }
4284}
4285
4286#[derive(Debug)]
4287pub struct NoRepositoryError {}
4288
4289impl std::fmt::Display for NoRepositoryError {
4290 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4291 write!(f, "no git repository for worktree found")
4292 }
4293}
4294
4295impl std::error::Error for NoRepositoryError {}
4296
4297pub fn sort_worktree_entries(entries: &mut [Entry]) {
4298 entries.sort_by(|entry_a, entry_b| {
4299 compare_paths(
4300 (&entry_a.path, entry_a.is_file()),
4301 (&entry_b.path, entry_b.is_file()),
4302 )
4303 });
4304}
4305
4306fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
4307 match level {
4308 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
4309 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
4310 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
4311 }
4312}