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(&self, path: &ProjectPath, cx: &AppContext) -> Option<Model<Buffer>> {
1928 self.buffer_store.read(cx).get_by_path(path, cx)
1929 }
1930
1931 fn register_buffer(
1932 &mut self,
1933 buffer: &Model<Buffer>,
1934 cx: &mut ModelContext<Self>,
1935 ) -> Result<()> {
1936 {
1937 let mut remotely_created_models = self.remotely_created_models.lock();
1938 if remotely_created_models.retain_count > 0 {
1939 remotely_created_models.buffers.push(buffer.clone())
1940 }
1941 }
1942
1943 self.request_buffer_diff_recalculation(buffer, cx);
1944
1945 cx.subscribe(buffer, |this, buffer, event, cx| {
1946 this.on_buffer_event(buffer, event, cx);
1947 })
1948 .detach();
1949
1950 Ok(())
1951 }
1952
1953 async fn send_buffer_ordered_messages(
1954 this: WeakModel<Self>,
1955 rx: UnboundedReceiver<BufferOrderedMessage>,
1956 mut cx: AsyncAppContext,
1957 ) -> Result<()> {
1958 const MAX_BATCH_SIZE: usize = 128;
1959
1960 let mut operations_by_buffer_id = HashMap::default();
1961 async fn flush_operations(
1962 this: &WeakModel<Project>,
1963 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
1964 needs_resync_with_host: &mut bool,
1965 is_local: bool,
1966 cx: &mut AsyncAppContext,
1967 ) -> Result<()> {
1968 for (buffer_id, operations) in operations_by_buffer_id.drain() {
1969 let request = this.update(cx, |this, _| {
1970 let project_id = this.remote_id()?;
1971 Some(this.client.request(proto::UpdateBuffer {
1972 buffer_id: buffer_id.into(),
1973 project_id,
1974 operations,
1975 }))
1976 })?;
1977 if let Some(request) = request {
1978 if request.await.is_err() && !is_local {
1979 *needs_resync_with_host = true;
1980 break;
1981 }
1982 }
1983 }
1984 Ok(())
1985 }
1986
1987 let mut needs_resync_with_host = false;
1988 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
1989
1990 while let Some(changes) = changes.next().await {
1991 let is_local = this.update(&mut cx, |this, _| this.is_local())?;
1992
1993 for change in changes {
1994 match change {
1995 BufferOrderedMessage::Operation {
1996 buffer_id,
1997 operation,
1998 } => {
1999 if needs_resync_with_host {
2000 continue;
2001 }
2002
2003 operations_by_buffer_id
2004 .entry(buffer_id)
2005 .or_insert(Vec::new())
2006 .push(operation);
2007 }
2008
2009 BufferOrderedMessage::Resync => {
2010 operations_by_buffer_id.clear();
2011 if this
2012 .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2013 .await
2014 .is_ok()
2015 {
2016 needs_resync_with_host = false;
2017 }
2018 }
2019
2020 BufferOrderedMessage::LanguageServerUpdate {
2021 language_server_id,
2022 message,
2023 } => {
2024 flush_operations(
2025 &this,
2026 &mut operations_by_buffer_id,
2027 &mut needs_resync_with_host,
2028 is_local,
2029 &mut cx,
2030 )
2031 .await?;
2032
2033 this.update(&mut cx, |this, _| {
2034 if let Some(project_id) = this.remote_id() {
2035 this.client
2036 .send(proto::UpdateLanguageServer {
2037 project_id,
2038 language_server_id: language_server_id.0 as u64,
2039 variant: Some(message),
2040 })
2041 .log_err();
2042 }
2043 })?;
2044 }
2045 }
2046 }
2047
2048 flush_operations(
2049 &this,
2050 &mut operations_by_buffer_id,
2051 &mut needs_resync_with_host,
2052 is_local,
2053 &mut cx,
2054 )
2055 .await?;
2056 }
2057
2058 Ok(())
2059 }
2060
2061 fn on_buffer_store_event(
2062 &mut self,
2063 _: Model<BufferStore>,
2064 event: &BufferStoreEvent,
2065 cx: &mut ModelContext<Self>,
2066 ) {
2067 match event {
2068 BufferStoreEvent::BufferAdded(buffer) => {
2069 self.register_buffer(buffer, cx).log_err();
2070 }
2071 BufferStoreEvent::BufferChangedFilePath { .. } => {}
2072 BufferStoreEvent::BufferDropped(buffer_id) => {
2073 if let Some(ref ssh_client) = self.ssh_client {
2074 ssh_client
2075 .read(cx)
2076 .proto_client()
2077 .send(proto::CloseBuffer {
2078 project_id: 0,
2079 buffer_id: buffer_id.to_proto(),
2080 })
2081 .log_err();
2082 }
2083 }
2084 }
2085 }
2086
2087 fn on_lsp_store_event(
2088 &mut self,
2089 _: Model<LspStore>,
2090 event: &LspStoreEvent,
2091 cx: &mut ModelContext<Self>,
2092 ) {
2093 match event {
2094 LspStoreEvent::DiagnosticsUpdated {
2095 language_server_id,
2096 path,
2097 } => cx.emit(Event::DiagnosticsUpdated {
2098 path: path.clone(),
2099 language_server_id: *language_server_id,
2100 }),
2101 LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2102 Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2103 ),
2104 LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2105 cx.emit(Event::LanguageServerRemoved(*language_server_id))
2106 }
2107 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2108 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2109 ),
2110 LspStoreEvent::LanguageDetected {
2111 buffer,
2112 new_language,
2113 } => {
2114 let Some(_) = new_language else {
2115 cx.emit(Event::LanguageNotFound(buffer.clone()));
2116 return;
2117 };
2118 }
2119 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2120 LspStoreEvent::LanguageServerPrompt(prompt) => {
2121 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2122 }
2123 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2124 cx.emit(Event::DiskBasedDiagnosticsStarted {
2125 language_server_id: *language_server_id,
2126 });
2127 }
2128 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2129 cx.emit(Event::DiskBasedDiagnosticsFinished {
2130 language_server_id: *language_server_id,
2131 });
2132 }
2133 LspStoreEvent::LanguageServerUpdate {
2134 language_server_id,
2135 message,
2136 } => {
2137 if self.is_local() {
2138 self.enqueue_buffer_ordered_message(
2139 BufferOrderedMessage::LanguageServerUpdate {
2140 language_server_id: *language_server_id,
2141 message: message.clone(),
2142 },
2143 )
2144 .ok();
2145 }
2146 }
2147 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2148 notification_id: "lsp".into(),
2149 message: message.clone(),
2150 }),
2151 LspStoreEvent::SnippetEdit {
2152 buffer_id,
2153 edits,
2154 most_recent_edit,
2155 } => {
2156 if most_recent_edit.replica_id == self.replica_id() {
2157 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2158 }
2159 }
2160 }
2161 }
2162
2163 fn on_ssh_event(
2164 &mut self,
2165 _: Model<SshRemoteClient>,
2166 event: &remote::SshRemoteEvent,
2167 cx: &mut ModelContext<Self>,
2168 ) {
2169 match event {
2170 remote::SshRemoteEvent::Disconnected => {
2171 // if self.is_via_ssh() {
2172 // self.collaborators.clear();
2173 self.worktree_store.update(cx, |store, cx| {
2174 store.disconnected_from_host(cx);
2175 });
2176 self.buffer_store.update(cx, |buffer_store, cx| {
2177 buffer_store.disconnected_from_host(cx)
2178 });
2179 self.lsp_store.update(cx, |lsp_store, _cx| {
2180 lsp_store.disconnected_from_ssh_remote()
2181 });
2182 cx.emit(Event::DisconnectedFromSshRemote);
2183 }
2184 }
2185 }
2186
2187 fn on_settings_observer_event(
2188 &mut self,
2189 _: Model<SettingsObserver>,
2190 event: &SettingsObserverEvent,
2191 cx: &mut ModelContext<Self>,
2192 ) {
2193 match event {
2194 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2195 Err(InvalidSettingsError::LocalSettings { message, path }) => {
2196 let message =
2197 format!("Failed to set local settings in {:?}:\n{}", path, message);
2198 cx.emit(Event::Toast {
2199 notification_id: "local-settings".into(),
2200 message,
2201 });
2202 }
2203 Ok(_) => cx.emit(Event::HideToast {
2204 notification_id: "local-settings".into(),
2205 }),
2206 Err(_) => {}
2207 },
2208 }
2209 }
2210
2211 fn on_worktree_store_event(
2212 &mut self,
2213 _: Model<WorktreeStore>,
2214 event: &WorktreeStoreEvent,
2215 cx: &mut ModelContext<Self>,
2216 ) {
2217 match event {
2218 WorktreeStoreEvent::WorktreeAdded(worktree) => {
2219 self.on_worktree_added(worktree, cx);
2220 cx.emit(Event::WorktreeAdded);
2221 }
2222 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2223 cx.emit(Event::WorktreeRemoved(*id));
2224 }
2225 WorktreeStoreEvent::WorktreeReleased(_, id) => {
2226 self.on_worktree_released(*id, cx);
2227 }
2228 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2229 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2230 }
2231 }
2232
2233 fn on_worktree_added(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
2234 {
2235 let mut remotely_created_models = self.remotely_created_models.lock();
2236 if remotely_created_models.retain_count > 0 {
2237 remotely_created_models.worktrees.push(worktree.clone())
2238 }
2239 }
2240 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2241 cx.subscribe(worktree, |project, worktree, event, cx| match event {
2242 worktree::Event::UpdatedEntries(changes) => {
2243 cx.emit(Event::WorktreeUpdatedEntries(
2244 worktree.read(cx).id(),
2245 changes.clone(),
2246 ));
2247
2248 let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
2249 project
2250 .client()
2251 .telemetry()
2252 .report_discovered_project_events(worktree_id, changes);
2253 }
2254 worktree::Event::UpdatedGitRepositories(_) => {
2255 cx.emit(Event::WorktreeUpdatedGitRepositories);
2256 }
2257 worktree::Event::DeletedEntry(id) => cx.emit(Event::DeletedEntry(*id)),
2258 })
2259 .detach();
2260 cx.notify();
2261 }
2262
2263 fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
2264 if let Some(dev_server_project_id) = self.dev_server_project_id {
2265 let paths: Vec<String> = self
2266 .visible_worktrees(cx)
2267 .filter_map(|worktree| {
2268 if worktree.read(cx).id() == id_to_remove {
2269 None
2270 } else {
2271 Some(worktree.read(cx).abs_path().to_string_lossy().to_string())
2272 }
2273 })
2274 .collect();
2275 if !paths.is_empty() {
2276 let request = self.client.request(proto::UpdateDevServerProject {
2277 dev_server_project_id: dev_server_project_id.0,
2278 paths,
2279 });
2280 cx.background_executor()
2281 .spawn(request)
2282 .detach_and_log_err(cx);
2283 }
2284 return;
2285 }
2286
2287 if let Some(ssh) = &self.ssh_client {
2288 ssh.read(cx)
2289 .proto_client()
2290 .send(proto::RemoveWorktree {
2291 worktree_id: id_to_remove.to_proto(),
2292 })
2293 .log_err();
2294 }
2295
2296 cx.notify();
2297 }
2298
2299 fn on_buffer_event(
2300 &mut self,
2301 buffer: Model<Buffer>,
2302 event: &BufferEvent,
2303 cx: &mut ModelContext<Self>,
2304 ) -> Option<()> {
2305 if matches!(
2306 event,
2307 BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2308 ) {
2309 self.request_buffer_diff_recalculation(&buffer, cx);
2310 }
2311
2312 let buffer_id = buffer.read(cx).remote_id();
2313 match event {
2314 BufferEvent::ReloadNeeded => {
2315 if !self.is_via_collab() {
2316 self.reload_buffers([buffer.clone()].into_iter().collect(), false, cx)
2317 .detach_and_log_err(cx);
2318 }
2319 }
2320 BufferEvent::Operation {
2321 operation,
2322 is_local: true,
2323 } => {
2324 let operation = language::proto::serialize_operation(operation);
2325
2326 if let Some(ssh) = &self.ssh_client {
2327 ssh.read(cx)
2328 .proto_client()
2329 .send(proto::UpdateBuffer {
2330 project_id: 0,
2331 buffer_id: buffer_id.to_proto(),
2332 operations: vec![operation.clone()],
2333 })
2334 .ok();
2335 }
2336
2337 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2338 buffer_id,
2339 operation,
2340 })
2341 .ok();
2342 }
2343
2344 _ => {}
2345 }
2346
2347 None
2348 }
2349
2350 fn request_buffer_diff_recalculation(
2351 &mut self,
2352 buffer: &Model<Buffer>,
2353 cx: &mut ModelContext<Self>,
2354 ) {
2355 self.buffers_needing_diff.insert(buffer.downgrade());
2356 let first_insertion = self.buffers_needing_diff.len() == 1;
2357
2358 let settings = ProjectSettings::get_global(cx);
2359 let delay = if let Some(delay) = settings.git.gutter_debounce {
2360 delay
2361 } else {
2362 if first_insertion {
2363 let this = cx.weak_model();
2364 cx.defer(move |cx| {
2365 if let Some(this) = this.upgrade() {
2366 this.update(cx, |this, cx| {
2367 this.recalculate_buffer_diffs(cx).detach();
2368 });
2369 }
2370 });
2371 }
2372 return;
2373 };
2374
2375 const MIN_DELAY: u64 = 50;
2376 let delay = delay.max(MIN_DELAY);
2377 let duration = Duration::from_millis(delay);
2378
2379 self.git_diff_debouncer
2380 .fire_new(duration, cx, move |this, cx| {
2381 this.recalculate_buffer_diffs(cx)
2382 });
2383 }
2384
2385 fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2386 let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2387 cx.spawn(move |this, mut cx| async move {
2388 let tasks: Vec<_> = buffers
2389 .iter()
2390 .filter_map(|buffer| {
2391 let buffer = buffer.upgrade()?;
2392 buffer
2393 .update(&mut cx, |buffer, cx| buffer.recalculate_diff(cx))
2394 .ok()
2395 .flatten()
2396 })
2397 .collect();
2398
2399 futures::future::join_all(tasks).await;
2400
2401 this.update(&mut cx, |this, cx| {
2402 if this.buffers_needing_diff.is_empty() {
2403 // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2404 for buffer in buffers {
2405 if let Some(buffer) = buffer.upgrade() {
2406 buffer.update(cx, |_, cx| cx.notify());
2407 }
2408 }
2409 } else {
2410 this.recalculate_buffer_diffs(cx).detach();
2411 }
2412 })
2413 .ok();
2414 })
2415 }
2416
2417 pub fn set_language_for_buffer(
2418 &mut self,
2419 buffer: &Model<Buffer>,
2420 new_language: Arc<Language>,
2421 cx: &mut ModelContext<Self>,
2422 ) {
2423 self.lsp_store.update(cx, |lsp_store, cx| {
2424 lsp_store.set_language_for_buffer(buffer, new_language, cx)
2425 })
2426 }
2427
2428 pub fn restart_language_servers_for_buffers(
2429 &mut self,
2430 buffers: impl IntoIterator<Item = Model<Buffer>>,
2431 cx: &mut ModelContext<Self>,
2432 ) {
2433 self.lsp_store.update(cx, |lsp_store, cx| {
2434 lsp_store.restart_language_servers_for_buffers(buffers, cx)
2435 })
2436 }
2437
2438 pub fn cancel_language_server_work_for_buffers(
2439 &mut self,
2440 buffers: impl IntoIterator<Item = Model<Buffer>>,
2441 cx: &mut ModelContext<Self>,
2442 ) {
2443 self.lsp_store.update(cx, |lsp_store, cx| {
2444 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2445 })
2446 }
2447
2448 pub fn cancel_language_server_work(
2449 &mut self,
2450 server_id: LanguageServerId,
2451 token_to_cancel: Option<String>,
2452 cx: &mut ModelContext<Self>,
2453 ) {
2454 self.lsp_store.update(cx, |lsp_store, cx| {
2455 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2456 })
2457 }
2458
2459 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2460 self.buffer_ordered_messages_tx
2461 .unbounded_send(message)
2462 .map_err(|e| anyhow!(e))
2463 }
2464
2465 pub fn language_server_statuses<'a>(
2466 &'a self,
2467 cx: &'a AppContext,
2468 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2469 self.lsp_store.read(cx).language_server_statuses()
2470 }
2471
2472 pub fn last_formatting_failure<'a>(&self, cx: &'a AppContext) -> Option<&'a str> {
2473 self.lsp_store.read(cx).last_formatting_failure()
2474 }
2475
2476 pub fn update_diagnostics(
2477 &mut self,
2478 language_server_id: LanguageServerId,
2479 params: lsp::PublishDiagnosticsParams,
2480 disk_based_sources: &[String],
2481 cx: &mut ModelContext<Self>,
2482 ) -> Result<()> {
2483 self.lsp_store.update(cx, |lsp_store, cx| {
2484 lsp_store.update_diagnostics(language_server_id, params, disk_based_sources, cx)
2485 })
2486 }
2487
2488 pub fn update_diagnostic_entries(
2489 &mut self,
2490 server_id: LanguageServerId,
2491 abs_path: PathBuf,
2492 version: Option<i32>,
2493 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2494 cx: &mut ModelContext<Project>,
2495 ) -> Result<(), anyhow::Error> {
2496 self.lsp_store.update(cx, |lsp_store, cx| {
2497 lsp_store.update_diagnostic_entries(server_id, abs_path, version, diagnostics, cx)
2498 })
2499 }
2500
2501 pub fn reload_buffers(
2502 &self,
2503 buffers: HashSet<Model<Buffer>>,
2504 push_to_history: bool,
2505 cx: &mut ModelContext<Self>,
2506 ) -> Task<Result<ProjectTransaction>> {
2507 self.buffer_store.update(cx, |buffer_store, cx| {
2508 buffer_store.reload_buffers(buffers, push_to_history, cx)
2509 })
2510 }
2511
2512 pub fn format(
2513 &mut self,
2514 buffers: HashSet<Model<Buffer>>,
2515 push_to_history: bool,
2516 trigger: lsp_store::FormatTrigger,
2517 target: lsp_store::FormatTarget,
2518 cx: &mut ModelContext<Project>,
2519 ) -> Task<anyhow::Result<ProjectTransaction>> {
2520 self.lsp_store.update(cx, |lsp_store, cx| {
2521 lsp_store.format(buffers, push_to_history, trigger, target, cx)
2522 })
2523 }
2524
2525 #[inline(never)]
2526 fn definition_impl(
2527 &mut self,
2528 buffer: &Model<Buffer>,
2529 position: PointUtf16,
2530 cx: &mut ModelContext<Self>,
2531 ) -> Task<Result<Vec<LocationLink>>> {
2532 self.request_lsp(
2533 buffer.clone(),
2534 LanguageServerToQuery::Primary,
2535 GetDefinition { position },
2536 cx,
2537 )
2538 }
2539 pub fn definition<T: ToPointUtf16>(
2540 &mut self,
2541 buffer: &Model<Buffer>,
2542 position: T,
2543 cx: &mut ModelContext<Self>,
2544 ) -> Task<Result<Vec<LocationLink>>> {
2545 let position = position.to_point_utf16(buffer.read(cx));
2546 self.definition_impl(buffer, position, cx)
2547 }
2548
2549 fn declaration_impl(
2550 &mut self,
2551 buffer: &Model<Buffer>,
2552 position: PointUtf16,
2553 cx: &mut ModelContext<Self>,
2554 ) -> Task<Result<Vec<LocationLink>>> {
2555 self.request_lsp(
2556 buffer.clone(),
2557 LanguageServerToQuery::Primary,
2558 GetDeclaration { position },
2559 cx,
2560 )
2561 }
2562
2563 pub fn declaration<T: ToPointUtf16>(
2564 &mut self,
2565 buffer: &Model<Buffer>,
2566 position: T,
2567 cx: &mut ModelContext<Self>,
2568 ) -> Task<Result<Vec<LocationLink>>> {
2569 let position = position.to_point_utf16(buffer.read(cx));
2570 self.declaration_impl(buffer, position, cx)
2571 }
2572
2573 fn type_definition_impl(
2574 &mut self,
2575 buffer: &Model<Buffer>,
2576 position: PointUtf16,
2577 cx: &mut ModelContext<Self>,
2578 ) -> Task<Result<Vec<LocationLink>>> {
2579 self.request_lsp(
2580 buffer.clone(),
2581 LanguageServerToQuery::Primary,
2582 GetTypeDefinition { position },
2583 cx,
2584 )
2585 }
2586
2587 pub fn type_definition<T: ToPointUtf16>(
2588 &mut self,
2589 buffer: &Model<Buffer>,
2590 position: T,
2591 cx: &mut ModelContext<Self>,
2592 ) -> Task<Result<Vec<LocationLink>>> {
2593 let position = position.to_point_utf16(buffer.read(cx));
2594 self.type_definition_impl(buffer, position, cx)
2595 }
2596
2597 pub fn implementation<T: ToPointUtf16>(
2598 &mut self,
2599 buffer: &Model<Buffer>,
2600 position: T,
2601 cx: &mut ModelContext<Self>,
2602 ) -> Task<Result<Vec<LocationLink>>> {
2603 let position = position.to_point_utf16(buffer.read(cx));
2604 self.request_lsp(
2605 buffer.clone(),
2606 LanguageServerToQuery::Primary,
2607 GetImplementation { position },
2608 cx,
2609 )
2610 }
2611
2612 pub fn references<T: ToPointUtf16>(
2613 &mut self,
2614 buffer: &Model<Buffer>,
2615 position: T,
2616 cx: &mut ModelContext<Self>,
2617 ) -> Task<Result<Vec<Location>>> {
2618 let position = position.to_point_utf16(buffer.read(cx));
2619 self.request_lsp(
2620 buffer.clone(),
2621 LanguageServerToQuery::Primary,
2622 GetReferences { position },
2623 cx,
2624 )
2625 }
2626
2627 fn document_highlights_impl(
2628 &mut self,
2629 buffer: &Model<Buffer>,
2630 position: PointUtf16,
2631 cx: &mut ModelContext<Self>,
2632 ) -> Task<Result<Vec<DocumentHighlight>>> {
2633 self.request_lsp(
2634 buffer.clone(),
2635 LanguageServerToQuery::Primary,
2636 GetDocumentHighlights { position },
2637 cx,
2638 )
2639 }
2640
2641 pub fn document_highlights<T: ToPointUtf16>(
2642 &mut self,
2643 buffer: &Model<Buffer>,
2644 position: T,
2645 cx: &mut ModelContext<Self>,
2646 ) -> Task<Result<Vec<DocumentHighlight>>> {
2647 let position = position.to_point_utf16(buffer.read(cx));
2648 self.document_highlights_impl(buffer, position, cx)
2649 }
2650
2651 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
2652 self.lsp_store
2653 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
2654 }
2655
2656 pub fn open_buffer_for_symbol(
2657 &mut self,
2658 symbol: &Symbol,
2659 cx: &mut ModelContext<Self>,
2660 ) -> Task<Result<Model<Buffer>>> {
2661 self.lsp_store.update(cx, |lsp_store, cx| {
2662 lsp_store.open_buffer_for_symbol(symbol, cx)
2663 })
2664 }
2665
2666 pub fn open_server_settings(
2667 &mut self,
2668 cx: &mut ModelContext<Self>,
2669 ) -> Task<Result<Model<Buffer>>> {
2670 let guard = self.retain_remotely_created_models(cx);
2671 let Some(ssh_client) = self.ssh_client.as_ref() else {
2672 return Task::ready(Err(anyhow!("not an ssh project")));
2673 };
2674
2675 let proto_client = ssh_client.read(cx).proto_client();
2676
2677 cx.spawn(|this, mut cx| async move {
2678 let buffer = proto_client
2679 .request(proto::OpenServerSettings {
2680 project_id: SSH_PROJECT_ID,
2681 })
2682 .await?;
2683
2684 let buffer = this
2685 .update(&mut cx, |this, cx| {
2686 anyhow::Ok(this.wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx))
2687 })??
2688 .await;
2689
2690 drop(guard);
2691 buffer
2692 })
2693 }
2694
2695 pub fn open_local_buffer_via_lsp(
2696 &mut self,
2697 abs_path: lsp::Url,
2698 language_server_id: LanguageServerId,
2699 language_server_name: LanguageServerName,
2700 cx: &mut ModelContext<Self>,
2701 ) -> Task<Result<Model<Buffer>>> {
2702 self.lsp_store.update(cx, |lsp_store, cx| {
2703 lsp_store.open_local_buffer_via_lsp(
2704 abs_path,
2705 language_server_id,
2706 language_server_name,
2707 cx,
2708 )
2709 })
2710 }
2711
2712 pub fn signature_help<T: ToPointUtf16>(
2713 &self,
2714 buffer: &Model<Buffer>,
2715 position: T,
2716 cx: &mut ModelContext<Self>,
2717 ) -> Task<Vec<SignatureHelp>> {
2718 self.lsp_store.update(cx, |lsp_store, cx| {
2719 lsp_store.signature_help(buffer, position, cx)
2720 })
2721 }
2722
2723 pub fn hover<T: ToPointUtf16>(
2724 &self,
2725 buffer: &Model<Buffer>,
2726 position: T,
2727 cx: &mut ModelContext<Self>,
2728 ) -> Task<Vec<Hover>> {
2729 let position = position.to_point_utf16(buffer.read(cx));
2730 self.lsp_store
2731 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
2732 }
2733
2734 pub fn linked_edit(
2735 &self,
2736 buffer: &Model<Buffer>,
2737 position: Anchor,
2738 cx: &mut ModelContext<Self>,
2739 ) -> Task<Result<Vec<Range<Anchor>>>> {
2740 self.lsp_store.update(cx, |lsp_store, cx| {
2741 lsp_store.linked_edit(buffer, position, cx)
2742 })
2743 }
2744
2745 pub fn completions<T: ToOffset + ToPointUtf16>(
2746 &self,
2747 buffer: &Model<Buffer>,
2748 position: T,
2749 context: CompletionContext,
2750 cx: &mut ModelContext<Self>,
2751 ) -> Task<Result<Vec<Completion>>> {
2752 let position = position.to_point_utf16(buffer.read(cx));
2753 self.lsp_store.update(cx, |lsp_store, cx| {
2754 lsp_store.completions(buffer, position, context, cx)
2755 })
2756 }
2757
2758 pub fn resolve_completions(
2759 &self,
2760 buffer: Model<Buffer>,
2761 completion_indices: Vec<usize>,
2762 completions: Arc<RwLock<Box<[Completion]>>>,
2763 cx: &mut ModelContext<Self>,
2764 ) -> Task<Result<bool>> {
2765 self.lsp_store.update(cx, |lsp_store, cx| {
2766 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
2767 })
2768 }
2769
2770 pub fn apply_additional_edits_for_completion(
2771 &self,
2772 buffer_handle: Model<Buffer>,
2773 completion: Completion,
2774 push_to_history: bool,
2775 cx: &mut ModelContext<Self>,
2776 ) -> Task<Result<Option<Transaction>>> {
2777 self.lsp_store.update(cx, |lsp_store, cx| {
2778 lsp_store.apply_additional_edits_for_completion(
2779 buffer_handle,
2780 completion,
2781 push_to_history,
2782 cx,
2783 )
2784 })
2785 }
2786
2787 pub fn code_actions<T: Clone + ToOffset>(
2788 &mut self,
2789 buffer_handle: &Model<Buffer>,
2790 range: Range<T>,
2791 cx: &mut ModelContext<Self>,
2792 ) -> Task<Result<Vec<CodeAction>>> {
2793 let buffer = buffer_handle.read(cx);
2794 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2795 self.lsp_store.update(cx, |lsp_store, cx| {
2796 lsp_store.code_actions(buffer_handle, range, cx)
2797 })
2798 }
2799
2800 pub fn apply_code_action(
2801 &self,
2802 buffer_handle: Model<Buffer>,
2803 action: CodeAction,
2804 push_to_history: bool,
2805 cx: &mut ModelContext<Self>,
2806 ) -> Task<Result<ProjectTransaction>> {
2807 self.lsp_store.update(cx, |lsp_store, cx| {
2808 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
2809 })
2810 }
2811
2812 fn prepare_rename_impl(
2813 &mut self,
2814 buffer: Model<Buffer>,
2815 position: PointUtf16,
2816 cx: &mut ModelContext<Self>,
2817 ) -> Task<Result<Option<Range<Anchor>>>> {
2818 self.request_lsp(
2819 buffer,
2820 LanguageServerToQuery::Primary,
2821 PrepareRename { position },
2822 cx,
2823 )
2824 }
2825 pub fn prepare_rename<T: ToPointUtf16>(
2826 &mut self,
2827 buffer: Model<Buffer>,
2828 position: T,
2829 cx: &mut ModelContext<Self>,
2830 ) -> Task<Result<Option<Range<Anchor>>>> {
2831 let position = position.to_point_utf16(buffer.read(cx));
2832 self.prepare_rename_impl(buffer, position, cx)
2833 }
2834
2835 fn perform_rename_impl(
2836 &mut self,
2837 buffer: Model<Buffer>,
2838 position: PointUtf16,
2839 new_name: String,
2840 push_to_history: bool,
2841 cx: &mut ModelContext<Self>,
2842 ) -> Task<Result<ProjectTransaction>> {
2843 let position = position.to_point_utf16(buffer.read(cx));
2844 self.request_lsp(
2845 buffer,
2846 LanguageServerToQuery::Primary,
2847 PerformRename {
2848 position,
2849 new_name,
2850 push_to_history,
2851 },
2852 cx,
2853 )
2854 }
2855
2856 pub fn perform_rename<T: ToPointUtf16>(
2857 &mut self,
2858 buffer: Model<Buffer>,
2859 position: T,
2860 new_name: String,
2861 cx: &mut ModelContext<Self>,
2862 ) -> Task<Result<ProjectTransaction>> {
2863 let position = position.to_point_utf16(buffer.read(cx));
2864 self.perform_rename_impl(buffer, position, new_name, true, cx)
2865 }
2866
2867 pub fn on_type_format<T: ToPointUtf16>(
2868 &mut self,
2869 buffer: Model<Buffer>,
2870 position: T,
2871 trigger: String,
2872 push_to_history: bool,
2873 cx: &mut ModelContext<Self>,
2874 ) -> Task<Result<Option<Transaction>>> {
2875 self.lsp_store.update(cx, |lsp_store, cx| {
2876 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
2877 })
2878 }
2879
2880 pub fn inlay_hints<T: ToOffset>(
2881 &mut self,
2882 buffer_handle: Model<Buffer>,
2883 range: Range<T>,
2884 cx: &mut ModelContext<Self>,
2885 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
2886 let buffer = buffer_handle.read(cx);
2887 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2888 self.lsp_store.update(cx, |lsp_store, cx| {
2889 lsp_store.inlay_hints(buffer_handle, range, cx)
2890 })
2891 }
2892
2893 pub fn resolve_inlay_hint(
2894 &self,
2895 hint: InlayHint,
2896 buffer_handle: Model<Buffer>,
2897 server_id: LanguageServerId,
2898 cx: &mut ModelContext<Self>,
2899 ) -> Task<anyhow::Result<InlayHint>> {
2900 self.lsp_store.update(cx, |lsp_store, cx| {
2901 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
2902 })
2903 }
2904
2905 pub fn search(
2906 &mut self,
2907 query: SearchQuery,
2908 cx: &mut ModelContext<Self>,
2909 ) -> Receiver<SearchResult> {
2910 let (result_tx, result_rx) = smol::channel::unbounded();
2911
2912 let matching_buffers_rx = if query.is_opened_only() {
2913 self.sort_search_candidates(&query, cx)
2914 } else {
2915 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
2916 };
2917
2918 cx.spawn(|_, cx| async move {
2919 let mut range_count = 0;
2920 let mut buffer_count = 0;
2921 let mut limit_reached = false;
2922 let query = Arc::new(query);
2923 let mut chunks = matching_buffers_rx.ready_chunks(64);
2924
2925 // Now that we know what paths match the query, we will load at most
2926 // 64 buffers at a time to avoid overwhelming the main thread. For each
2927 // opened buffer, we will spawn a background task that retrieves all the
2928 // ranges in the buffer matched by the query.
2929 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
2930 let mut chunk_results = Vec::new();
2931 for buffer in matching_buffer_chunk {
2932 let buffer = buffer.clone();
2933 let query = query.clone();
2934 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
2935 chunk_results.push(cx.background_executor().spawn(async move {
2936 let ranges = query
2937 .search(&snapshot, None)
2938 .await
2939 .iter()
2940 .map(|range| {
2941 snapshot.anchor_before(range.start)
2942 ..snapshot.anchor_after(range.end)
2943 })
2944 .collect::<Vec<_>>();
2945 anyhow::Ok((buffer, ranges))
2946 }));
2947 }
2948
2949 let chunk_results = futures::future::join_all(chunk_results).await;
2950 for result in chunk_results {
2951 if let Some((buffer, ranges)) = result.log_err() {
2952 range_count += ranges.len();
2953 buffer_count += 1;
2954 result_tx
2955 .send(SearchResult::Buffer { buffer, ranges })
2956 .await?;
2957 if buffer_count > MAX_SEARCH_RESULT_FILES
2958 || range_count > MAX_SEARCH_RESULT_RANGES
2959 {
2960 limit_reached = true;
2961 break 'outer;
2962 }
2963 }
2964 }
2965 }
2966
2967 if limit_reached {
2968 result_tx.send(SearchResult::LimitReached).await?;
2969 }
2970
2971 anyhow::Ok(())
2972 })
2973 .detach();
2974
2975 result_rx
2976 }
2977
2978 fn find_search_candidate_buffers(
2979 &mut self,
2980 query: &SearchQuery,
2981 limit: usize,
2982 cx: &mut ModelContext<Project>,
2983 ) -> Receiver<Model<Buffer>> {
2984 if self.is_local() {
2985 let fs = self.fs.clone();
2986 self.buffer_store.update(cx, |buffer_store, cx| {
2987 buffer_store.find_search_candidates(query, limit, fs, cx)
2988 })
2989 } else {
2990 self.find_search_candidates_remote(query, limit, cx)
2991 }
2992 }
2993
2994 fn sort_search_candidates(
2995 &mut self,
2996 search_query: &SearchQuery,
2997 cx: &mut ModelContext<Project>,
2998 ) -> Receiver<Model<Buffer>> {
2999 let worktree_store = self.worktree_store.read(cx);
3000 let mut buffers = search_query
3001 .buffers()
3002 .into_iter()
3003 .flatten()
3004 .filter(|buffer| {
3005 let b = buffer.read(cx);
3006 if let Some(file) = b.file() {
3007 if !search_query.file_matches(file.path()) {
3008 return false;
3009 }
3010 if let Some(entry) = b
3011 .entry_id(cx)
3012 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3013 {
3014 if entry.is_ignored && !search_query.include_ignored() {
3015 return false;
3016 }
3017 }
3018 }
3019 true
3020 })
3021 .collect::<Vec<_>>();
3022 let (tx, rx) = smol::channel::unbounded();
3023 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3024 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3025 (None, Some(_)) => std::cmp::Ordering::Less,
3026 (Some(_), None) => std::cmp::Ordering::Greater,
3027 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3028 });
3029 for buffer in buffers {
3030 tx.send_blocking(buffer.clone()).unwrap()
3031 }
3032
3033 rx
3034 }
3035
3036 fn find_search_candidates_remote(
3037 &mut self,
3038 query: &SearchQuery,
3039 limit: usize,
3040 cx: &mut ModelContext<Project>,
3041 ) -> Receiver<Model<Buffer>> {
3042 let (tx, rx) = smol::channel::unbounded();
3043
3044 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3045 (ssh_client.read(cx).proto_client(), 0)
3046 } else if let Some(remote_id) = self.remote_id() {
3047 (self.client.clone().into(), remote_id)
3048 } else {
3049 return rx;
3050 };
3051
3052 let request = client.request(proto::FindSearchCandidates {
3053 project_id: remote_id,
3054 query: Some(query.to_proto()),
3055 limit: limit as _,
3056 });
3057 let guard = self.retain_remotely_created_models(cx);
3058
3059 cx.spawn(move |this, mut cx| async move {
3060 let response = request.await?;
3061 for buffer_id in response.buffer_ids {
3062 let buffer_id = BufferId::new(buffer_id)?;
3063 let buffer = this
3064 .update(&mut cx, |this, cx| {
3065 this.wait_for_remote_buffer(buffer_id, cx)
3066 })?
3067 .await?;
3068 let _ = tx.send(buffer).await;
3069 }
3070
3071 drop(guard);
3072 anyhow::Ok(())
3073 })
3074 .detach_and_log_err(cx);
3075 rx
3076 }
3077
3078 pub fn request_lsp<R: LspCommand>(
3079 &mut self,
3080 buffer_handle: Model<Buffer>,
3081 server: LanguageServerToQuery,
3082 request: R,
3083 cx: &mut ModelContext<Self>,
3084 ) -> Task<Result<R::Response>>
3085 where
3086 <R::LspRequest as lsp::request::Request>::Result: Send,
3087 <R::LspRequest as lsp::request::Request>::Params: Send,
3088 {
3089 let guard = self.retain_remotely_created_models(cx);
3090 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3091 lsp_store.request_lsp(buffer_handle, server, request, cx)
3092 });
3093 cx.spawn(|_, _| async move {
3094 let result = task.await;
3095 drop(guard);
3096 result
3097 })
3098 }
3099
3100 /// Move a worktree to a new position in the worktree order.
3101 ///
3102 /// The worktree will moved to the opposite side of the destination worktree.
3103 ///
3104 /// # Example
3105 ///
3106 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3107 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3108 ///
3109 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3110 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3111 ///
3112 /// # Errors
3113 ///
3114 /// An error will be returned if the worktree or destination worktree are not found.
3115 pub fn move_worktree(
3116 &mut self,
3117 source: WorktreeId,
3118 destination: WorktreeId,
3119 cx: &mut ModelContext<'_, Self>,
3120 ) -> Result<()> {
3121 self.worktree_store.update(cx, |worktree_store, cx| {
3122 worktree_store.move_worktree(source, destination, cx)
3123 })
3124 }
3125
3126 pub fn find_or_create_worktree(
3127 &mut self,
3128 abs_path: impl AsRef<Path>,
3129 visible: bool,
3130 cx: &mut ModelContext<Self>,
3131 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
3132 self.worktree_store.update(cx, |worktree_store, cx| {
3133 worktree_store.find_or_create_worktree(abs_path, visible, cx)
3134 })
3135 }
3136
3137 pub fn find_worktree(
3138 &self,
3139 abs_path: &Path,
3140 cx: &AppContext,
3141 ) -> Option<(Model<Worktree>, PathBuf)> {
3142 self.worktree_store.read_with(cx, |worktree_store, cx| {
3143 worktree_store.find_worktree(abs_path, cx)
3144 })
3145 }
3146
3147 pub fn is_shared(&self) -> bool {
3148 match &self.client_state {
3149 ProjectClientState::Shared { .. } => true,
3150 ProjectClientState::Local => false,
3151 ProjectClientState::Remote { in_room, .. } => *in_room,
3152 }
3153 }
3154
3155 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3156 pub fn resolve_existing_file_path(
3157 &self,
3158 path: &str,
3159 buffer: &Model<Buffer>,
3160 cx: &mut ModelContext<Self>,
3161 ) -> Task<Option<ResolvedPath>> {
3162 let path_buf = PathBuf::from(path);
3163 if path_buf.is_absolute() || path.starts_with("~") {
3164 self.resolve_abs_file_path(path, cx)
3165 } else {
3166 self.resolve_path_in_worktrees(path_buf, buffer, cx)
3167 }
3168 }
3169
3170 pub fn abs_file_path_exists(&self, path: &str, cx: &mut ModelContext<Self>) -> Task<bool> {
3171 let resolve_task = self.resolve_abs_file_path(path, cx);
3172 cx.background_executor().spawn(async move {
3173 let resolved_path = resolve_task.await;
3174 resolved_path.is_some()
3175 })
3176 }
3177
3178 fn resolve_abs_file_path(
3179 &self,
3180 path: &str,
3181 cx: &mut ModelContext<Self>,
3182 ) -> Task<Option<ResolvedPath>> {
3183 if self.is_local() {
3184 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3185
3186 let fs = self.fs.clone();
3187 cx.background_executor().spawn(async move {
3188 let path = expanded.as_path();
3189 let exists = fs.is_file(path).await;
3190
3191 exists.then(|| ResolvedPath::AbsPath(expanded))
3192 })
3193 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3194 let request = ssh_client
3195 .read(cx)
3196 .proto_client()
3197 .request(proto::CheckFileExists {
3198 project_id: SSH_PROJECT_ID,
3199 path: path.to_string(),
3200 });
3201 cx.background_executor().spawn(async move {
3202 let response = request.await.log_err()?;
3203 if response.exists {
3204 Some(ResolvedPath::AbsPath(PathBuf::from(response.path)))
3205 } else {
3206 None
3207 }
3208 })
3209 } else {
3210 return Task::ready(None);
3211 }
3212 }
3213
3214 fn resolve_path_in_worktrees(
3215 &self,
3216 path: PathBuf,
3217 buffer: &Model<Buffer>,
3218 cx: &mut ModelContext<Self>,
3219 ) -> Task<Option<ResolvedPath>> {
3220 let mut candidates = vec![path.clone()];
3221
3222 if let Some(file) = buffer.read(cx).file() {
3223 if let Some(dir) = file.path().parent() {
3224 let joined = dir.to_path_buf().join(path);
3225 candidates.push(joined);
3226 }
3227 }
3228
3229 let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3230 cx.spawn(|_, mut cx| async move {
3231 for worktree in worktrees {
3232 for candidate in candidates.iter() {
3233 let path = worktree
3234 .update(&mut cx, |worktree, _| {
3235 let root_entry_path = &worktree.root_entry()?.path;
3236
3237 let resolved = resolve_path(root_entry_path, candidate);
3238
3239 let stripped =
3240 resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3241
3242 worktree.entry_for_path(stripped).map(|entry| {
3243 ResolvedPath::ProjectPath(ProjectPath {
3244 worktree_id: worktree.id(),
3245 path: entry.path.clone(),
3246 })
3247 })
3248 })
3249 .ok()?;
3250
3251 if path.is_some() {
3252 return path;
3253 }
3254 }
3255 }
3256 None
3257 })
3258 }
3259
3260 pub fn list_directory(
3261 &self,
3262 query: String,
3263 cx: &mut ModelContext<Self>,
3264 ) -> Task<Result<Vec<PathBuf>>> {
3265 if self.is_local() {
3266 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3267 } else if let Some(session) = self.ssh_client.as_ref() {
3268 let request = proto::ListRemoteDirectory {
3269 dev_server_id: SSH_PROJECT_ID,
3270 path: query,
3271 };
3272
3273 let response = session.read(cx).proto_client().request(request);
3274 cx.background_executor().spawn(async move {
3275 let response = response.await?;
3276 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3277 })
3278 } else if let Some(dev_server) = self.dev_server_project_id().and_then(|id| {
3279 dev_server_projects::Store::global(cx)
3280 .read(cx)
3281 .dev_server_for_project(id)
3282 }) {
3283 let request = proto::ListRemoteDirectory {
3284 dev_server_id: dev_server.id.0,
3285 path: query,
3286 };
3287 let response = self.client.request(request);
3288 cx.background_executor().spawn(async move {
3289 let response = response.await?;
3290 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3291 })
3292 } else {
3293 Task::ready(Err(anyhow!("cannot list directory in remote project")))
3294 }
3295 }
3296
3297 pub fn create_worktree(
3298 &mut self,
3299 abs_path: impl AsRef<Path>,
3300 visible: bool,
3301 cx: &mut ModelContext<Self>,
3302 ) -> Task<Result<Model<Worktree>>> {
3303 self.worktree_store.update(cx, |worktree_store, cx| {
3304 worktree_store.create_worktree(abs_path, visible, cx)
3305 })
3306 }
3307
3308 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
3309 self.worktree_store.update(cx, |worktree_store, cx| {
3310 worktree_store.remove_worktree(id_to_remove, cx);
3311 });
3312 }
3313
3314 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
3315 self.worktree_store.update(cx, |worktree_store, cx| {
3316 worktree_store.add(worktree, cx);
3317 });
3318 }
3319
3320 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
3321 let new_active_entry = entry.and_then(|project_path| {
3322 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3323 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3324 Some(entry.id)
3325 });
3326 if new_active_entry != self.active_entry {
3327 self.active_entry = new_active_entry;
3328 self.lsp_store.update(cx, |lsp_store, _| {
3329 lsp_store.set_active_entry(new_active_entry);
3330 });
3331 cx.emit(Event::ActiveEntryChanged(new_active_entry));
3332 }
3333 }
3334
3335 pub fn language_servers_running_disk_based_diagnostics<'a>(
3336 &'a self,
3337 cx: &'a AppContext,
3338 ) -> impl Iterator<Item = LanguageServerId> + 'a {
3339 self.lsp_store
3340 .read(cx)
3341 .language_servers_running_disk_based_diagnostics()
3342 }
3343
3344 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
3345 let mut summary = DiagnosticSummary::default();
3346 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
3347 summary.error_count += path_summary.error_count;
3348 summary.warning_count += path_summary.warning_count;
3349 }
3350 summary
3351 }
3352
3353 pub fn diagnostic_summaries<'a>(
3354 &'a self,
3355 include_ignored: bool,
3356 cx: &'a AppContext,
3357 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3358 self.lsp_store
3359 .read(cx)
3360 .diagnostic_summaries(include_ignored, cx)
3361 }
3362
3363 pub fn active_entry(&self) -> Option<ProjectEntryId> {
3364 self.active_entry
3365 }
3366
3367 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
3368 self.worktree_store.read(cx).entry_for_path(path, cx)
3369 }
3370
3371 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
3372 let worktree = self.worktree_for_entry(entry_id, cx)?;
3373 let worktree = worktree.read(cx);
3374 let worktree_id = worktree.id();
3375 let path = worktree.entry_for_id(entry_id)?.path.clone();
3376 Some(ProjectPath { worktree_id, path })
3377 }
3378
3379 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
3380 self.worktree_for_id(project_path.worktree_id, cx)?
3381 .read(cx)
3382 .absolutize(&project_path.path)
3383 .ok()
3384 }
3385
3386 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3387 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3388 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3389 /// the first visible worktree that has an entry for that relative path.
3390 ///
3391 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3392 /// root name from paths.
3393 ///
3394 /// # Arguments
3395 ///
3396 /// * `path` - A full path that starts with a worktree root name, or alternatively a
3397 /// relative path within a visible worktree.
3398 /// * `cx` - A reference to the `AppContext`.
3399 ///
3400 /// # Returns
3401 ///
3402 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3403 pub fn find_project_path(&self, path: &Path, cx: &AppContext) -> Option<ProjectPath> {
3404 let worktree_store = self.worktree_store.read(cx);
3405
3406 for worktree in worktree_store.visible_worktrees(cx) {
3407 let worktree_root_name = worktree.read(cx).root_name();
3408 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3409 return Some(ProjectPath {
3410 worktree_id: worktree.read(cx).id(),
3411 path: relative_path.into(),
3412 });
3413 }
3414 }
3415
3416 for worktree in worktree_store.visible_worktrees(cx) {
3417 let worktree = worktree.read(cx);
3418 if let Some(entry) = worktree.entry_for_path(path) {
3419 return Some(ProjectPath {
3420 worktree_id: worktree.id(),
3421 path: entry.path.clone(),
3422 });
3423 }
3424 }
3425
3426 None
3427 }
3428
3429 pub fn get_workspace_root(
3430 &self,
3431 project_path: &ProjectPath,
3432 cx: &AppContext,
3433 ) -> Option<PathBuf> {
3434 Some(
3435 self.worktree_for_id(project_path.worktree_id, cx)?
3436 .read(cx)
3437 .abs_path()
3438 .to_path_buf(),
3439 )
3440 }
3441
3442 pub fn get_repo(
3443 &self,
3444 project_path: &ProjectPath,
3445 cx: &AppContext,
3446 ) -> Option<Arc<dyn GitRepository>> {
3447 self.worktree_for_id(project_path.worktree_id, cx)?
3448 .read(cx)
3449 .as_local()?
3450 .local_git_repo(&project_path.path)
3451 }
3452
3453 pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
3454 let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
3455 let root_entry = worktree.root_git_entry()?;
3456 worktree.get_local_repo(&root_entry)?.repo().clone().into()
3457 }
3458
3459 pub fn blame_buffer(
3460 &self,
3461 buffer: &Model<Buffer>,
3462 version: Option<clock::Global>,
3463 cx: &AppContext,
3464 ) -> Task<Result<Blame>> {
3465 self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
3466 }
3467
3468 pub fn get_permalink_to_line(
3469 &self,
3470 buffer: &Model<Buffer>,
3471 selection: Range<u32>,
3472 cx: &AppContext,
3473 ) -> Task<Result<url::Url>> {
3474 self.buffer_store
3475 .read(cx)
3476 .get_permalink_to_line(buffer, selection, cx)
3477 }
3478
3479 // RPC message handlers
3480
3481 async fn handle_unshare_project(
3482 this: Model<Self>,
3483 _: TypedEnvelope<proto::UnshareProject>,
3484 mut cx: AsyncAppContext,
3485 ) -> Result<()> {
3486 this.update(&mut cx, |this, cx| {
3487 if this.is_local() || this.is_via_ssh() {
3488 this.unshare(cx)?;
3489 } else {
3490 this.disconnected_from_host(cx);
3491 }
3492 Ok(())
3493 })?
3494 }
3495
3496 async fn handle_add_collaborator(
3497 this: Model<Self>,
3498 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3499 mut cx: AsyncAppContext,
3500 ) -> Result<()> {
3501 let collaborator = envelope
3502 .payload
3503 .collaborator
3504 .take()
3505 .ok_or_else(|| anyhow!("empty collaborator"))?;
3506
3507 let collaborator = Collaborator::from_proto(collaborator)?;
3508 this.update(&mut cx, |this, cx| {
3509 this.buffer_store.update(cx, |buffer_store, _| {
3510 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
3511 });
3512 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
3513 this.collaborators
3514 .insert(collaborator.peer_id, collaborator);
3515 cx.notify();
3516 })?;
3517
3518 Ok(())
3519 }
3520
3521 async fn handle_update_project_collaborator(
3522 this: Model<Self>,
3523 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
3524 mut cx: AsyncAppContext,
3525 ) -> Result<()> {
3526 let old_peer_id = envelope
3527 .payload
3528 .old_peer_id
3529 .ok_or_else(|| anyhow!("missing old peer id"))?;
3530 let new_peer_id = envelope
3531 .payload
3532 .new_peer_id
3533 .ok_or_else(|| anyhow!("missing new peer id"))?;
3534 this.update(&mut cx, |this, cx| {
3535 let collaborator = this
3536 .collaborators
3537 .remove(&old_peer_id)
3538 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
3539 let is_host = collaborator.replica_id == 0;
3540 this.collaborators.insert(new_peer_id, collaborator);
3541
3542 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
3543 this.buffer_store.update(cx, |buffer_store, _| {
3544 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
3545 });
3546
3547 if is_host {
3548 this.buffer_store
3549 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
3550 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
3551 .unwrap();
3552 cx.emit(Event::HostReshared);
3553 }
3554
3555 cx.emit(Event::CollaboratorUpdated {
3556 old_peer_id,
3557 new_peer_id,
3558 });
3559 cx.notify();
3560 Ok(())
3561 })?
3562 }
3563
3564 async fn handle_remove_collaborator(
3565 this: Model<Self>,
3566 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3567 mut cx: AsyncAppContext,
3568 ) -> Result<()> {
3569 this.update(&mut cx, |this, cx| {
3570 let peer_id = envelope
3571 .payload
3572 .peer_id
3573 .ok_or_else(|| anyhow!("invalid peer id"))?;
3574 let replica_id = this
3575 .collaborators
3576 .remove(&peer_id)
3577 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3578 .replica_id;
3579 this.buffer_store.update(cx, |buffer_store, cx| {
3580 buffer_store.forget_shared_buffers_for(&peer_id);
3581 for buffer in buffer_store.buffers() {
3582 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3583 }
3584 });
3585
3586 cx.emit(Event::CollaboratorLeft(peer_id));
3587 cx.notify();
3588 Ok(())
3589 })?
3590 }
3591
3592 async fn handle_update_project(
3593 this: Model<Self>,
3594 envelope: TypedEnvelope<proto::UpdateProject>,
3595 mut cx: AsyncAppContext,
3596 ) -> Result<()> {
3597 this.update(&mut cx, |this, cx| {
3598 // Don't handle messages that were sent before the response to us joining the project
3599 if envelope.message_id > this.join_project_response_message_id {
3600 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
3601 }
3602 Ok(())
3603 })?
3604 }
3605
3606 async fn handle_toast(
3607 this: Model<Self>,
3608 envelope: TypedEnvelope<proto::Toast>,
3609 mut cx: AsyncAppContext,
3610 ) -> Result<()> {
3611 this.update(&mut cx, |_, cx| {
3612 cx.emit(Event::Toast {
3613 notification_id: envelope.payload.notification_id.into(),
3614 message: envelope.payload.message,
3615 });
3616 Ok(())
3617 })?
3618 }
3619
3620 async fn handle_language_server_prompt_request(
3621 this: Model<Self>,
3622 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
3623 mut cx: AsyncAppContext,
3624 ) -> Result<proto::LanguageServerPromptResponse> {
3625 let (tx, mut rx) = smol::channel::bounded(1);
3626 let actions: Vec<_> = envelope
3627 .payload
3628 .actions
3629 .into_iter()
3630 .map(|action| MessageActionItem {
3631 title: action,
3632 properties: Default::default(),
3633 })
3634 .collect();
3635 this.update(&mut cx, |_, cx| {
3636 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
3637 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
3638 message: envelope.payload.message,
3639 actions: actions.clone(),
3640 lsp_name: envelope.payload.lsp_name,
3641 response_channel: tx,
3642 }));
3643
3644 anyhow::Ok(())
3645 })??;
3646
3647 let answer = rx.next().await;
3648
3649 Ok(LanguageServerPromptResponse {
3650 action_response: answer.and_then(|answer| {
3651 actions
3652 .iter()
3653 .position(|action| *action == answer)
3654 .map(|index| index as u64)
3655 }),
3656 })
3657 }
3658
3659 async fn handle_hide_toast(
3660 this: Model<Self>,
3661 envelope: TypedEnvelope<proto::HideToast>,
3662 mut cx: AsyncAppContext,
3663 ) -> Result<()> {
3664 this.update(&mut cx, |_, cx| {
3665 cx.emit(Event::HideToast {
3666 notification_id: envelope.payload.notification_id.into(),
3667 });
3668 Ok(())
3669 })?
3670 }
3671
3672 // Collab sends UpdateWorktree protos as messages
3673 async fn handle_update_worktree(
3674 this: Model<Self>,
3675 envelope: TypedEnvelope<proto::UpdateWorktree>,
3676 mut cx: AsyncAppContext,
3677 ) -> Result<()> {
3678 this.update(&mut cx, |this, cx| {
3679 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3680 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3681 worktree.update(cx, |worktree, _| {
3682 let worktree = worktree.as_remote_mut().unwrap();
3683 worktree.update_from_remote(envelope.payload);
3684 });
3685 }
3686 Ok(())
3687 })?
3688 }
3689
3690 async fn handle_update_buffer(
3691 this: Model<Self>,
3692 envelope: TypedEnvelope<proto::UpdateBuffer>,
3693 cx: AsyncAppContext,
3694 ) -> Result<proto::Ack> {
3695 let buffer_store = this.read_with(&cx, |this, cx| {
3696 if let Some(ssh) = &this.ssh_client {
3697 let mut payload = envelope.payload.clone();
3698 payload.project_id = SSH_PROJECT_ID;
3699 cx.background_executor()
3700 .spawn(ssh.read(cx).proto_client().request(payload))
3701 .detach_and_log_err(cx);
3702 }
3703 this.buffer_store.clone()
3704 })?;
3705 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3706 }
3707
3708 fn retain_remotely_created_models(
3709 &mut self,
3710 cx: &mut ModelContext<Self>,
3711 ) -> RemotelyCreatedModelGuard {
3712 {
3713 let mut remotely_create_models = self.remotely_created_models.lock();
3714 if remotely_create_models.retain_count == 0 {
3715 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
3716 remotely_create_models.worktrees =
3717 self.worktree_store.read(cx).worktrees().collect();
3718 }
3719 remotely_create_models.retain_count += 1;
3720 }
3721 RemotelyCreatedModelGuard {
3722 remote_models: Arc::downgrade(&self.remotely_created_models),
3723 }
3724 }
3725
3726 async fn handle_create_buffer_for_peer(
3727 this: Model<Self>,
3728 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
3729 mut cx: AsyncAppContext,
3730 ) -> Result<()> {
3731 this.update(&mut cx, |this, cx| {
3732 this.buffer_store.update(cx, |buffer_store, cx| {
3733 buffer_store.handle_create_buffer_for_peer(
3734 envelope,
3735 this.replica_id(),
3736 this.capability(),
3737 cx,
3738 )
3739 })
3740 })?
3741 }
3742
3743 async fn handle_synchronize_buffers(
3744 this: Model<Self>,
3745 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
3746 mut cx: AsyncAppContext,
3747 ) -> Result<proto::SynchronizeBuffersResponse> {
3748 let response = this.update(&mut cx, |this, cx| {
3749 let client = this.client.clone();
3750 this.buffer_store.update(cx, |this, cx| {
3751 this.handle_synchronize_buffers(envelope, cx, client)
3752 })
3753 })??;
3754
3755 Ok(response)
3756 }
3757
3758 async fn handle_search_candidate_buffers(
3759 this: Model<Self>,
3760 envelope: TypedEnvelope<proto::FindSearchCandidates>,
3761 mut cx: AsyncAppContext,
3762 ) -> Result<proto::FindSearchCandidatesResponse> {
3763 let peer_id = envelope.original_sender_id()?;
3764 let message = envelope.payload;
3765 let query = SearchQuery::from_proto(
3766 message
3767 .query
3768 .ok_or_else(|| anyhow!("missing query field"))?,
3769 )?;
3770 let mut results = this.update(&mut cx, |this, cx| {
3771 this.find_search_candidate_buffers(&query, message.limit as _, cx)
3772 })?;
3773
3774 let mut response = proto::FindSearchCandidatesResponse {
3775 buffer_ids: Vec::new(),
3776 };
3777
3778 while let Some(buffer) = results.next().await {
3779 this.update(&mut cx, |this, cx| {
3780 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
3781 response.buffer_ids.push(buffer_id.to_proto());
3782 })?;
3783 }
3784
3785 Ok(response)
3786 }
3787
3788 async fn handle_open_buffer_by_id(
3789 this: Model<Self>,
3790 envelope: TypedEnvelope<proto::OpenBufferById>,
3791 mut cx: AsyncAppContext,
3792 ) -> Result<proto::OpenBufferResponse> {
3793 let peer_id = envelope.original_sender_id()?;
3794 let buffer_id = BufferId::new(envelope.payload.id)?;
3795 let buffer = this
3796 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
3797 .await?;
3798 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3799 }
3800
3801 async fn handle_open_buffer_by_path(
3802 this: Model<Self>,
3803 envelope: TypedEnvelope<proto::OpenBufferByPath>,
3804 mut cx: AsyncAppContext,
3805 ) -> Result<proto::OpenBufferResponse> {
3806 let peer_id = envelope.original_sender_id()?;
3807 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3808 let open_buffer = this.update(&mut cx, |this, cx| {
3809 this.open_buffer(
3810 ProjectPath {
3811 worktree_id,
3812 path: PathBuf::from(envelope.payload.path).into(),
3813 },
3814 cx,
3815 )
3816 })?;
3817
3818 let buffer = open_buffer.await?;
3819 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3820 }
3821
3822 async fn handle_open_new_buffer(
3823 this: Model<Self>,
3824 envelope: TypedEnvelope<proto::OpenNewBuffer>,
3825 mut cx: AsyncAppContext,
3826 ) -> Result<proto::OpenBufferResponse> {
3827 let buffer = this
3828 .update(&mut cx, |this, cx| this.create_buffer(cx))?
3829 .await?;
3830 let peer_id = envelope.original_sender_id()?;
3831
3832 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3833 }
3834
3835 fn respond_to_open_buffer_request(
3836 this: Model<Self>,
3837 buffer: Model<Buffer>,
3838 peer_id: proto::PeerId,
3839 cx: &mut AsyncAppContext,
3840 ) -> Result<proto::OpenBufferResponse> {
3841 this.update(cx, |this, cx| {
3842 let is_private = buffer
3843 .read(cx)
3844 .file()
3845 .map(|f| f.is_private())
3846 .unwrap_or_default();
3847 if is_private {
3848 Err(anyhow!(ErrorCode::UnsharedItem))
3849 } else {
3850 Ok(proto::OpenBufferResponse {
3851 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
3852 })
3853 }
3854 })?
3855 }
3856
3857 fn create_buffer_for_peer(
3858 &mut self,
3859 buffer: &Model<Buffer>,
3860 peer_id: proto::PeerId,
3861 cx: &mut AppContext,
3862 ) -> BufferId {
3863 self.buffer_store
3864 .update(cx, |buffer_store, cx| {
3865 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
3866 })
3867 .detach_and_log_err(cx);
3868 buffer.read(cx).remote_id()
3869 }
3870
3871 fn wait_for_remote_buffer(
3872 &mut self,
3873 id: BufferId,
3874 cx: &mut ModelContext<Self>,
3875 ) -> Task<Result<Model<Buffer>>> {
3876 self.buffer_store.update(cx, |buffer_store, cx| {
3877 buffer_store.wait_for_remote_buffer(id, cx)
3878 })
3879 }
3880
3881 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
3882 let project_id = match self.client_state {
3883 ProjectClientState::Remote {
3884 sharing_has_stopped,
3885 remote_id,
3886 ..
3887 } => {
3888 if sharing_has_stopped {
3889 return Task::ready(Err(anyhow!(
3890 "can't synchronize remote buffers on a readonly project"
3891 )));
3892 } else {
3893 remote_id
3894 }
3895 }
3896 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
3897 return Task::ready(Err(anyhow!(
3898 "can't synchronize remote buffers on a local project"
3899 )))
3900 }
3901 };
3902
3903 let client = self.client.clone();
3904 cx.spawn(move |this, mut cx| async move {
3905 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
3906 this.buffer_store.read(cx).buffer_version_info(cx)
3907 })?;
3908 let response = client
3909 .request(proto::SynchronizeBuffers {
3910 project_id,
3911 buffers,
3912 })
3913 .await?;
3914
3915 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
3916 response
3917 .buffers
3918 .into_iter()
3919 .map(|buffer| {
3920 let client = client.clone();
3921 let buffer_id = match BufferId::new(buffer.id) {
3922 Ok(id) => id,
3923 Err(e) => {
3924 return Task::ready(Err(e));
3925 }
3926 };
3927 let remote_version = language::proto::deserialize_version(&buffer.version);
3928 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
3929 let operations =
3930 buffer.read(cx).serialize_ops(Some(remote_version), cx);
3931 cx.background_executor().spawn(async move {
3932 let operations = operations.await;
3933 for chunk in split_operations(operations) {
3934 client
3935 .request(proto::UpdateBuffer {
3936 project_id,
3937 buffer_id: buffer_id.into(),
3938 operations: chunk,
3939 })
3940 .await?;
3941 }
3942 anyhow::Ok(())
3943 })
3944 } else {
3945 Task::ready(Ok(()))
3946 }
3947 })
3948 .collect::<Vec<_>>()
3949 })?;
3950
3951 // Any incomplete buffers have open requests waiting. Request that the host sends
3952 // creates these buffers for us again to unblock any waiting futures.
3953 for id in incomplete_buffer_ids {
3954 cx.background_executor()
3955 .spawn(client.request(proto::OpenBufferById {
3956 project_id,
3957 id: id.into(),
3958 }))
3959 .detach();
3960 }
3961
3962 futures::future::join_all(send_updates_for_buffers)
3963 .await
3964 .into_iter()
3965 .collect()
3966 })
3967 }
3968
3969 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
3970 self.worktree_store.read(cx).worktree_metadata_protos(cx)
3971 }
3972
3973 fn set_worktrees_from_proto(
3974 &mut self,
3975 worktrees: Vec<proto::WorktreeMetadata>,
3976 cx: &mut ModelContext<Project>,
3977 ) -> Result<()> {
3978 cx.notify();
3979 self.worktree_store.update(cx, |worktree_store, cx| {
3980 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
3981 })
3982 }
3983
3984 fn set_collaborators_from_proto(
3985 &mut self,
3986 messages: Vec<proto::Collaborator>,
3987 cx: &mut ModelContext<Self>,
3988 ) -> Result<()> {
3989 let mut collaborators = HashMap::default();
3990 for message in messages {
3991 let collaborator = Collaborator::from_proto(message)?;
3992 collaborators.insert(collaborator.peer_id, collaborator);
3993 }
3994 for old_peer_id in self.collaborators.keys() {
3995 if !collaborators.contains_key(old_peer_id) {
3996 cx.emit(Event::CollaboratorLeft(*old_peer_id));
3997 }
3998 }
3999 self.collaborators = collaborators;
4000 Ok(())
4001 }
4002
4003 pub fn language_servers<'a>(
4004 &'a self,
4005 cx: &'a AppContext,
4006 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
4007 self.lsp_store.read(cx).language_servers()
4008 }
4009
4010 pub fn supplementary_language_servers<'a>(
4011 &'a self,
4012 cx: &'a AppContext,
4013 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4014 self.lsp_store.read(cx).supplementary_language_servers()
4015 }
4016
4017 pub fn language_server_for_id(
4018 &self,
4019 id: LanguageServerId,
4020 cx: &AppContext,
4021 ) -> Option<Arc<LanguageServer>> {
4022 self.lsp_store.read(cx).language_server_for_id(id)
4023 }
4024
4025 pub fn language_servers_for_buffer<'a>(
4026 &'a self,
4027 buffer: &'a Buffer,
4028 cx: &'a AppContext,
4029 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4030 self.lsp_store
4031 .read(cx)
4032 .language_servers_for_buffer(buffer, cx)
4033 }
4034}
4035
4036fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
4037 code_actions
4038 .iter()
4039 .flat_map(|(kind, enabled)| {
4040 if *enabled {
4041 Some(kind.clone().into())
4042 } else {
4043 None
4044 }
4045 })
4046 .collect()
4047}
4048
4049pub struct PathMatchCandidateSet {
4050 pub snapshot: Snapshot,
4051 pub include_ignored: bool,
4052 pub include_root_name: bool,
4053 pub candidates: Candidates,
4054}
4055
4056pub enum Candidates {
4057 /// Only consider directories.
4058 Directories,
4059 /// Only consider files.
4060 Files,
4061 /// Consider directories and files.
4062 Entries,
4063}
4064
4065impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4066 type Candidates = PathMatchCandidateSetIter<'a>;
4067
4068 fn id(&self) -> usize {
4069 self.snapshot.id().to_usize()
4070 }
4071
4072 fn len(&self) -> usize {
4073 match self.candidates {
4074 Candidates::Files => {
4075 if self.include_ignored {
4076 self.snapshot.file_count()
4077 } else {
4078 self.snapshot.visible_file_count()
4079 }
4080 }
4081
4082 Candidates::Directories => {
4083 if self.include_ignored {
4084 self.snapshot.dir_count()
4085 } else {
4086 self.snapshot.visible_dir_count()
4087 }
4088 }
4089
4090 Candidates::Entries => {
4091 if self.include_ignored {
4092 self.snapshot.entry_count()
4093 } else {
4094 self.snapshot.visible_entry_count()
4095 }
4096 }
4097 }
4098 }
4099
4100 fn prefix(&self) -> Arc<str> {
4101 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4102 self.snapshot.root_name().into()
4103 } else if self.include_root_name {
4104 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4105 } else {
4106 Arc::default()
4107 }
4108 }
4109
4110 fn candidates(&'a self, start: usize) -> Self::Candidates {
4111 PathMatchCandidateSetIter {
4112 traversal: match self.candidates {
4113 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4114 Candidates::Files => self.snapshot.files(self.include_ignored, start),
4115 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4116 },
4117 }
4118 }
4119}
4120
4121pub struct PathMatchCandidateSetIter<'a> {
4122 traversal: Traversal<'a>,
4123}
4124
4125impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4126 type Item = fuzzy::PathMatchCandidate<'a>;
4127
4128 fn next(&mut self) -> Option<Self::Item> {
4129 self.traversal
4130 .next()
4131 .map(|entry| fuzzy::PathMatchCandidate {
4132 is_dir: entry.kind.is_dir(),
4133 path: &entry.path,
4134 char_bag: entry.char_bag,
4135 })
4136 }
4137}
4138
4139impl EventEmitter<Event> for Project {}
4140
4141impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4142 fn from(val: &'a ProjectPath) -> Self {
4143 SettingsLocation {
4144 worktree_id: val.worktree_id,
4145 path: val.path.as_ref(),
4146 }
4147 }
4148}
4149
4150impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4151 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4152 Self {
4153 worktree_id,
4154 path: path.as_ref().into(),
4155 }
4156 }
4157}
4158
4159pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4160 let mut path_components = path.components();
4161 let mut base_components = base.components();
4162 let mut components: Vec<Component> = Vec::new();
4163 loop {
4164 match (path_components.next(), base_components.next()) {
4165 (None, None) => break,
4166 (Some(a), None) => {
4167 components.push(a);
4168 components.extend(path_components.by_ref());
4169 break;
4170 }
4171 (None, _) => components.push(Component::ParentDir),
4172 (Some(a), Some(b)) if components.is_empty() && a == b => (),
4173 (Some(a), Some(Component::CurDir)) => components.push(a),
4174 (Some(a), Some(_)) => {
4175 components.push(Component::ParentDir);
4176 for _ in base_components {
4177 components.push(Component::ParentDir);
4178 }
4179 components.push(a);
4180 components.extend(path_components.by_ref());
4181 break;
4182 }
4183 }
4184 }
4185 components.iter().map(|c| c.as_os_str()).collect()
4186}
4187
4188fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4189 let mut result = base.to_path_buf();
4190 for component in path.components() {
4191 match component {
4192 Component::ParentDir => {
4193 result.pop();
4194 }
4195 Component::CurDir => (),
4196 _ => result.push(component),
4197 }
4198 }
4199 result
4200}
4201
4202/// ResolvedPath is a path that has been resolved to either a ProjectPath
4203/// or an AbsPath and that *exists*.
4204#[derive(Debug, Clone)]
4205pub enum ResolvedPath {
4206 ProjectPath(ProjectPath),
4207 AbsPath(PathBuf),
4208}
4209
4210impl ResolvedPath {
4211 pub fn abs_path(&self) -> Option<&Path> {
4212 match self {
4213 Self::AbsPath(path) => Some(path.as_path()),
4214 _ => None,
4215 }
4216 }
4217
4218 pub fn project_path(&self) -> Option<&ProjectPath> {
4219 match self {
4220 Self::ProjectPath(path) => Some(&path),
4221 _ => None,
4222 }
4223 }
4224}
4225
4226impl Item for Buffer {
4227 fn try_open(
4228 project: &Model<Project>,
4229 path: &ProjectPath,
4230 cx: &mut AppContext,
4231 ) -> Option<Task<Result<Model<Self>>>> {
4232 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4233 }
4234
4235 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
4236 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4237 }
4238
4239 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
4240 File::from_dyn(self.file()).map(|file| ProjectPath {
4241 worktree_id: file.worktree_id(cx),
4242 path: file.path().clone(),
4243 })
4244 }
4245}
4246
4247impl Completion {
4248 /// A key that can be used to sort completions when displaying
4249 /// them to the user.
4250 pub fn sort_key(&self) -> (usize, &str) {
4251 let kind_key = match self.lsp_completion.kind {
4252 Some(lsp::CompletionItemKind::KEYWORD) => 0,
4253 Some(lsp::CompletionItemKind::VARIABLE) => 1,
4254 _ => 2,
4255 };
4256 (kind_key, &self.label.text[self.label.filter_range.clone()])
4257 }
4258
4259 /// Whether this completion is a snippet.
4260 pub fn is_snippet(&self) -> bool {
4261 self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4262 }
4263
4264 /// Returns the corresponding color for this completion.
4265 ///
4266 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4267 pub fn color(&self) -> Option<Hsla> {
4268 match self.lsp_completion.kind {
4269 Some(CompletionItemKind::COLOR) => color_extractor::extract_color(&self.lsp_completion),
4270 _ => None,
4271 }
4272 }
4273}
4274
4275#[derive(Debug)]
4276pub struct NoRepositoryError {}
4277
4278impl std::fmt::Display for NoRepositoryError {
4279 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4280 write!(f, "no git repository for worktree found")
4281 }
4282}
4283
4284impl std::error::Error for NoRepositoryError {}
4285
4286pub fn sort_worktree_entries(entries: &mut [Entry]) {
4287 entries.sort_by(|entry_a, entry_b| {
4288 compare_paths(
4289 (&entry_a.path, entry_a.is_file()),
4290 (&entry_b.path, entry_b.is_file()),
4291 )
4292 });
4293}
4294
4295fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
4296 match level {
4297 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
4298 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
4299 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
4300 }
4301}