1mod db;
2pub mod fs;
3mod ignore;
4mod lsp_command;
5pub mod search;
6pub mod worktree;
7
8#[cfg(test)]
9mod project_tests;
10
11use anyhow::{anyhow, Context, Result};
12use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
13use clock::ReplicaId;
14use collections::{hash_map, BTreeMap, HashMap, HashSet};
15use futures::{future::Shared, AsyncWriteExt, Future, FutureExt, SinkExt, StreamExt, TryFutureExt};
16use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
17use gpui::{
18 AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
19 MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
20};
21use language::{
22 point_to_lsp,
23 proto::{
24 deserialize_anchor, deserialize_line_ending, deserialize_version, serialize_anchor,
25 serialize_version,
26 },
27 range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CharKind, CodeAction, CodeLabel,
28 Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Event as BufferEvent, File as _,
29 Language, LanguageRegistry, LanguageServerName, LineEnding, LocalFile, LspAdapter,
30 OffsetRangeExt, Operation, Patch, PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16,
31 Transaction,
32};
33use lsp::{
34 DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer, LanguageString,
35 MarkedString,
36};
37use lsp_command::*;
38use parking_lot::Mutex;
39use postage::stream::Stream;
40use postage::watch;
41use rand::prelude::*;
42use search::SearchQuery;
43use serde::Serialize;
44use settings::Settings;
45use sha2::{Digest, Sha256};
46use similar::{ChangeTag, TextDiff};
47use std::{
48 cell::RefCell,
49 cmp::{self, Ordering},
50 convert::TryInto,
51 ffi::OsString,
52 hash::Hash,
53 mem,
54 num::NonZeroU32,
55 ops::Range,
56 os::unix::{ffi::OsStrExt, prelude::OsStringExt},
57 path::{Component, Path, PathBuf},
58 rc::Rc,
59 str,
60 sync::{
61 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
62 Arc,
63 },
64 time::Instant,
65};
66use thiserror::Error;
67use util::{post_inc, ResultExt, TryFutureExt as _};
68
69pub use db::Db;
70pub use fs::*;
71pub use worktree::*;
72
73pub trait Item: Entity {
74 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
75}
76
77pub struct ProjectStore {
78 db: Arc<Db>,
79 projects: Vec<WeakModelHandle<Project>>,
80}
81
82// Language server state is stored across 3 collections:
83// language_servers =>
84// a mapping from unique server id to LanguageServerState which can either be a task for a
85// server in the process of starting, or a running server with adapter and language server arcs
86// language_server_ids => a mapping from worktreeId and server name to the unique server id
87// language_server_statuses => a mapping from unique server id to the current server status
88//
89// Multiple worktrees can map to the same language server for example when you jump to the definition
90// of a file in the standard library. So language_server_ids is used to look up which server is active
91// for a given worktree and language server name
92//
93// When starting a language server, first the id map is checked to make sure a server isn't already available
94// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
95// the Starting variant of LanguageServerState is stored in the language_servers map.
96pub struct Project {
97 worktrees: Vec<WorktreeHandle>,
98 active_entry: Option<ProjectEntryId>,
99 languages: Arc<LanguageRegistry>,
100 language_servers: HashMap<usize, LanguageServerState>,
101 language_server_ids: HashMap<(WorktreeId, LanguageServerName), usize>,
102 language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
103 language_server_settings: Arc<Mutex<serde_json::Value>>,
104 last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
105 next_language_server_id: usize,
106 client: Arc<client::Client>,
107 next_entry_id: Arc<AtomicUsize>,
108 next_diagnostic_group_id: usize,
109 user_store: ModelHandle<UserStore>,
110 project_store: ModelHandle<ProjectStore>,
111 fs: Arc<dyn Fs>,
112 client_state: ProjectClientState,
113 collaborators: HashMap<PeerId, Collaborator>,
114 client_subscriptions: Vec<client::Subscription>,
115 _subscriptions: Vec<gpui::Subscription>,
116 lsp_settings_changed: Option<Task<()>>,
117 opened_buffer: (Rc<RefCell<watch::Sender<()>>>, watch::Receiver<()>),
118 shared_buffers: HashMap<PeerId, HashSet<u64>>,
119 loading_buffers: HashMap<
120 ProjectPath,
121 postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
122 >,
123 loading_local_worktrees:
124 HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
125 opened_buffers: HashMap<u64, OpenBuffer>,
126 buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
127 nonce: u128,
128 initialized_persistent_state: bool,
129}
130
131#[derive(Error, Debug)]
132pub enum JoinProjectError {
133 #[error("host declined join request")]
134 HostDeclined,
135 #[error("host closed the project")]
136 HostClosedProject,
137 #[error("host went offline")]
138 HostWentOffline,
139 #[error("{0}")]
140 Other(#[from] anyhow::Error),
141}
142
143enum OpenBuffer {
144 Strong(ModelHandle<Buffer>),
145 Weak(WeakModelHandle<Buffer>),
146 Loading(Vec<Operation>),
147}
148
149enum WorktreeHandle {
150 Strong(ModelHandle<Worktree>),
151 Weak(WeakModelHandle<Worktree>),
152}
153
154enum ProjectClientState {
155 Local {
156 is_shared: bool,
157 remote_id_tx: watch::Sender<Option<u64>>,
158 remote_id_rx: watch::Receiver<Option<u64>>,
159 online_tx: watch::Sender<bool>,
160 online_rx: watch::Receiver<bool>,
161 _maintain_remote_id: Task<Option<()>>,
162 _maintain_online_status: Task<Option<()>>,
163 },
164 Remote {
165 sharing_has_stopped: bool,
166 remote_id: u64,
167 replica_id: ReplicaId,
168 _detect_unshare: Task<Option<()>>,
169 },
170}
171
172#[derive(Clone, Debug)]
173pub struct Collaborator {
174 pub user: Arc<User>,
175 pub peer_id: PeerId,
176 pub replica_id: ReplicaId,
177}
178
179#[derive(Clone, Debug, PartialEq, Eq)]
180pub enum Event {
181 ActiveEntryChanged(Option<ProjectEntryId>),
182 WorktreeAdded,
183 WorktreeRemoved(WorktreeId),
184 DiskBasedDiagnosticsStarted {
185 language_server_id: usize,
186 },
187 DiskBasedDiagnosticsFinished {
188 language_server_id: usize,
189 },
190 DiagnosticsUpdated {
191 path: ProjectPath,
192 language_server_id: usize,
193 },
194 RemoteIdChanged(Option<u64>),
195 CollaboratorLeft(PeerId),
196 ContactRequestedJoin(Arc<User>),
197 ContactCancelledJoinRequest(Arc<User>),
198}
199
200pub enum LanguageServerState {
201 Starting(Task<Option<Arc<LanguageServer>>>),
202 Running {
203 adapter: Arc<dyn LspAdapter>,
204 server: Arc<LanguageServer>,
205 },
206}
207
208#[derive(Serialize)]
209pub struct LanguageServerStatus {
210 pub name: String,
211 pub pending_work: BTreeMap<String, LanguageServerProgress>,
212 pub has_pending_diagnostic_updates: bool,
213 progress_tokens: HashSet<String>,
214}
215
216#[derive(Clone, Debug, Serialize)]
217pub struct LanguageServerProgress {
218 pub message: Option<String>,
219 pub percentage: Option<usize>,
220 #[serde(skip_serializing)]
221 pub last_update_at: Instant,
222}
223
224#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
225pub struct ProjectPath {
226 pub worktree_id: WorktreeId,
227 pub path: Arc<Path>,
228}
229
230#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
231pub struct DiagnosticSummary {
232 pub language_server_id: usize,
233 pub error_count: usize,
234 pub warning_count: usize,
235}
236
237#[derive(Debug, Clone)]
238pub struct Location {
239 pub buffer: ModelHandle<Buffer>,
240 pub range: Range<language::Anchor>,
241}
242
243#[derive(Debug, Clone)]
244pub struct LocationLink {
245 pub origin: Option<Location>,
246 pub target: Location,
247}
248
249#[derive(Debug)]
250pub struct DocumentHighlight {
251 pub range: Range<language::Anchor>,
252 pub kind: DocumentHighlightKind,
253}
254
255#[derive(Clone, Debug)]
256pub struct Symbol {
257 pub source_worktree_id: WorktreeId,
258 pub worktree_id: WorktreeId,
259 pub language_server_name: LanguageServerName,
260 pub path: PathBuf,
261 pub label: CodeLabel,
262 pub name: String,
263 pub kind: lsp::SymbolKind,
264 pub range: Range<PointUtf16>,
265 pub signature: [u8; 32],
266}
267
268#[derive(Clone, Debug, PartialEq)]
269pub struct HoverBlock {
270 pub text: String,
271 pub language: Option<String>,
272}
273
274impl HoverBlock {
275 fn try_new(marked_string: MarkedString) -> Option<Self> {
276 let result = match marked_string {
277 MarkedString::LanguageString(LanguageString { language, value }) => HoverBlock {
278 text: value,
279 language: Some(language),
280 },
281 MarkedString::String(text) => HoverBlock {
282 text,
283 language: None,
284 },
285 };
286 if result.text.is_empty() {
287 None
288 } else {
289 Some(result)
290 }
291 }
292}
293
294#[derive(Debug)]
295pub struct Hover {
296 pub contents: Vec<HoverBlock>,
297 pub range: Option<Range<language::Anchor>>,
298}
299
300#[derive(Default)]
301pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
302
303impl DiagnosticSummary {
304 fn new<'a, T: 'a>(
305 language_server_id: usize,
306 diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>,
307 ) -> Self {
308 let mut this = Self {
309 language_server_id,
310 error_count: 0,
311 warning_count: 0,
312 };
313
314 for entry in diagnostics {
315 if entry.diagnostic.is_primary {
316 match entry.diagnostic.severity {
317 DiagnosticSeverity::ERROR => this.error_count += 1,
318 DiagnosticSeverity::WARNING => this.warning_count += 1,
319 _ => {}
320 }
321 }
322 }
323
324 this
325 }
326
327 pub fn is_empty(&self) -> bool {
328 self.error_count == 0 && self.warning_count == 0
329 }
330
331 pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
332 proto::DiagnosticSummary {
333 path: path.to_string_lossy().to_string(),
334 language_server_id: self.language_server_id as u64,
335 error_count: self.error_count as u32,
336 warning_count: self.warning_count as u32,
337 }
338 }
339}
340
341#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
342pub struct ProjectEntryId(usize);
343
344impl ProjectEntryId {
345 pub const MAX: Self = Self(usize::MAX);
346
347 pub fn new(counter: &AtomicUsize) -> Self {
348 Self(counter.fetch_add(1, SeqCst))
349 }
350
351 pub fn from_proto(id: u64) -> Self {
352 Self(id as usize)
353 }
354
355 pub fn to_proto(&self) -> u64 {
356 self.0 as u64
357 }
358
359 pub fn to_usize(&self) -> usize {
360 self.0
361 }
362}
363
364impl Project {
365 pub fn init(client: &Arc<Client>) {
366 client.add_model_message_handler(Self::handle_request_join_project);
367 client.add_model_message_handler(Self::handle_add_collaborator);
368 client.add_model_message_handler(Self::handle_buffer_reloaded);
369 client.add_model_message_handler(Self::handle_buffer_saved);
370 client.add_model_message_handler(Self::handle_start_language_server);
371 client.add_model_message_handler(Self::handle_update_language_server);
372 client.add_model_message_handler(Self::handle_remove_collaborator);
373 client.add_model_message_handler(Self::handle_join_project_request_cancelled);
374 client.add_model_message_handler(Self::handle_update_project);
375 client.add_model_message_handler(Self::handle_unregister_project);
376 client.add_model_message_handler(Self::handle_project_unshared);
377 client.add_model_message_handler(Self::handle_update_buffer_file);
378 client.add_model_message_handler(Self::handle_update_buffer);
379 client.add_model_message_handler(Self::handle_update_diagnostic_summary);
380 client.add_model_message_handler(Self::handle_update_worktree);
381 client.add_model_request_handler(Self::handle_create_project_entry);
382 client.add_model_request_handler(Self::handle_rename_project_entry);
383 client.add_model_request_handler(Self::handle_copy_project_entry);
384 client.add_model_request_handler(Self::handle_delete_project_entry);
385 client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
386 client.add_model_request_handler(Self::handle_apply_code_action);
387 client.add_model_request_handler(Self::handle_reload_buffers);
388 client.add_model_request_handler(Self::handle_format_buffers);
389 client.add_model_request_handler(Self::handle_get_code_actions);
390 client.add_model_request_handler(Self::handle_get_completions);
391 client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
392 client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
393 client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
394 client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
395 client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
396 client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
397 client.add_model_request_handler(Self::handle_search_project);
398 client.add_model_request_handler(Self::handle_get_project_symbols);
399 client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
400 client.add_model_request_handler(Self::handle_open_buffer_by_id);
401 client.add_model_request_handler(Self::handle_open_buffer_by_path);
402 client.add_model_request_handler(Self::handle_save_buffer);
403 }
404
405 pub fn local(
406 online: bool,
407 client: Arc<Client>,
408 user_store: ModelHandle<UserStore>,
409 project_store: ModelHandle<ProjectStore>,
410 languages: Arc<LanguageRegistry>,
411 fs: Arc<dyn Fs>,
412 cx: &mut MutableAppContext,
413 ) -> ModelHandle<Self> {
414 cx.add_model(|cx: &mut ModelContext<Self>| {
415 let (remote_id_tx, remote_id_rx) = watch::channel();
416 let _maintain_remote_id = cx.spawn_weak({
417 let mut status_rx = client.clone().status();
418 move |this, mut cx| async move {
419 while let Some(status) = status_rx.recv().await {
420 let this = this.upgrade(&cx)?;
421 if status.is_connected() {
422 this.update(&mut cx, |this, cx| this.register(cx))
423 .await
424 .log_err()?;
425 } else {
426 this.update(&mut cx, |this, cx| this.unregister(cx))
427 .await
428 .log_err();
429 }
430 }
431 None
432 }
433 });
434
435 let (online_tx, online_rx) = watch::channel_with(online);
436 let _maintain_online_status = cx.spawn_weak({
437 let mut online_rx = online_rx.clone();
438 move |this, mut cx| async move {
439 while let Some(online) = online_rx.recv().await {
440 let this = this.upgrade(&cx)?;
441 this.update(&mut cx, |this, cx| {
442 if !online {
443 this.unshared(cx);
444 }
445 this.metadata_changed(false, cx)
446 });
447 }
448 None
449 }
450 });
451
452 let handle = cx.weak_handle();
453 project_store.update(cx, |store, cx| store.add_project(handle, cx));
454
455 let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
456 Self {
457 worktrees: Default::default(),
458 collaborators: Default::default(),
459 opened_buffers: Default::default(),
460 shared_buffers: Default::default(),
461 loading_buffers: Default::default(),
462 loading_local_worktrees: Default::default(),
463 buffer_snapshots: Default::default(),
464 client_state: ProjectClientState::Local {
465 is_shared: false,
466 remote_id_tx,
467 remote_id_rx,
468 online_tx,
469 online_rx,
470 _maintain_remote_id,
471 _maintain_online_status,
472 },
473 opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
474 client_subscriptions: Vec::new(),
475 _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
476 active_entry: None,
477 languages,
478 client,
479 user_store,
480 project_store,
481 fs,
482 next_entry_id: Default::default(),
483 next_diagnostic_group_id: Default::default(),
484 language_servers: Default::default(),
485 language_server_ids: Default::default(),
486 language_server_statuses: Default::default(),
487 last_workspace_edits_by_language_server: Default::default(),
488 language_server_settings: Default::default(),
489 next_language_server_id: 0,
490 nonce: StdRng::from_entropy().gen(),
491 initialized_persistent_state: false,
492 lsp_settings_changed: None,
493 }
494 })
495 }
496
497 pub async fn remote(
498 remote_id: u64,
499 client: Arc<Client>,
500 user_store: ModelHandle<UserStore>,
501 project_store: ModelHandle<ProjectStore>,
502 languages: Arc<LanguageRegistry>,
503 fs: Arc<dyn Fs>,
504 mut cx: AsyncAppContext,
505 ) -> Result<ModelHandle<Self>, JoinProjectError> {
506 client.authenticate_and_connect(true, &cx).await?;
507
508 let response = client
509 .request(proto::JoinProject {
510 project_id: remote_id,
511 })
512 .await?;
513
514 let response = match response.variant.ok_or_else(|| anyhow!("missing variant"))? {
515 proto::join_project_response::Variant::Accept(response) => response,
516 proto::join_project_response::Variant::Decline(decline) => {
517 match proto::join_project_response::decline::Reason::from_i32(decline.reason) {
518 Some(proto::join_project_response::decline::Reason::Declined) => {
519 Err(JoinProjectError::HostDeclined)?
520 }
521 Some(proto::join_project_response::decline::Reason::Closed) => {
522 Err(JoinProjectError::HostClosedProject)?
523 }
524 Some(proto::join_project_response::decline::Reason::WentOffline) => {
525 Err(JoinProjectError::HostWentOffline)?
526 }
527 None => Err(anyhow!("missing decline reason"))?,
528 }
529 }
530 };
531
532 let replica_id = response.replica_id as ReplicaId;
533
534 let mut worktrees = Vec::new();
535 for worktree in response.worktrees {
536 let worktree = cx
537 .update(|cx| Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx));
538 worktrees.push(worktree);
539 }
540
541 let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
542 let this = cx.add_model(|cx: &mut ModelContext<Self>| {
543 let handle = cx.weak_handle();
544 project_store.update(cx, |store, cx| store.add_project(handle, cx));
545
546 let mut this = Self {
547 worktrees: Vec::new(),
548 loading_buffers: Default::default(),
549 opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
550 shared_buffers: Default::default(),
551 loading_local_worktrees: Default::default(),
552 active_entry: None,
553 collaborators: Default::default(),
554 languages,
555 user_store: user_store.clone(),
556 project_store,
557 fs,
558 next_entry_id: Default::default(),
559 next_diagnostic_group_id: Default::default(),
560 client_subscriptions: vec![client.add_model_for_remote_entity(remote_id, cx)],
561 _subscriptions: Default::default(),
562 client: client.clone(),
563 client_state: ProjectClientState::Remote {
564 sharing_has_stopped: false,
565 remote_id,
566 replica_id,
567 _detect_unshare: cx.spawn_weak(move |this, mut cx| {
568 async move {
569 let mut status = client.status();
570 let is_connected =
571 status.next().await.map_or(false, |s| s.is_connected());
572 // Even if we're initially connected, any future change of the status means we momentarily disconnected.
573 if !is_connected || status.next().await.is_some() {
574 if let Some(this) = this.upgrade(&cx) {
575 this.update(&mut cx, |this, cx| this.removed_from_project(cx))
576 }
577 }
578 Ok(())
579 }
580 .log_err()
581 }),
582 },
583 language_servers: Default::default(),
584 language_server_ids: Default::default(),
585 language_server_settings: Default::default(),
586 language_server_statuses: response
587 .language_servers
588 .into_iter()
589 .map(|server| {
590 (
591 server.id as usize,
592 LanguageServerStatus {
593 name: server.name,
594 pending_work: Default::default(),
595 has_pending_diagnostic_updates: false,
596 progress_tokens: Default::default(),
597 },
598 )
599 })
600 .collect(),
601 last_workspace_edits_by_language_server: Default::default(),
602 next_language_server_id: 0,
603 opened_buffers: Default::default(),
604 buffer_snapshots: Default::default(),
605 nonce: StdRng::from_entropy().gen(),
606 initialized_persistent_state: false,
607 lsp_settings_changed: None,
608 };
609 for worktree in worktrees {
610 this.add_worktree(&worktree, cx);
611 }
612 this
613 });
614
615 let user_ids = response
616 .collaborators
617 .iter()
618 .map(|peer| peer.user_id)
619 .collect();
620 user_store
621 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
622 .await?;
623 let mut collaborators = HashMap::default();
624 for message in response.collaborators {
625 let collaborator = Collaborator::from_proto(message, &user_store, &mut cx).await?;
626 collaborators.insert(collaborator.peer_id, collaborator);
627 }
628
629 this.update(&mut cx, |this, _| {
630 this.collaborators = collaborators;
631 });
632
633 Ok(this)
634 }
635
636 #[cfg(any(test, feature = "test-support"))]
637 pub async fn test(
638 fs: Arc<dyn Fs>,
639 root_paths: impl IntoIterator<Item = &Path>,
640 cx: &mut gpui::TestAppContext,
641 ) -> ModelHandle<Project> {
642 if !cx.read(|cx| cx.has_global::<Settings>()) {
643 cx.update(|cx| cx.set_global(Settings::test(cx)));
644 }
645
646 let languages = Arc::new(LanguageRegistry::test());
647 let http_client = client::test::FakeHttpClient::with_404_response();
648 let client = client::Client::new(http_client.clone());
649 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
650 let project_store = cx.add_model(|_| ProjectStore::new(Db::open_fake()));
651 let project = cx.update(|cx| {
652 Project::local(true, client, user_store, project_store, languages, fs, cx)
653 });
654 for path in root_paths {
655 let (tree, _) = project
656 .update(cx, |project, cx| {
657 project.find_or_create_local_worktree(path, true, cx)
658 })
659 .await
660 .unwrap();
661 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
662 .await;
663 }
664 project
665 }
666
667 pub fn restore_state(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
668 if self.is_remote() {
669 return Task::ready(Ok(()));
670 }
671
672 let db = self.project_store.read(cx).db.clone();
673 let keys = self.db_keys_for_online_state(cx);
674 let online_by_default = cx.global::<Settings>().projects_online_by_default;
675 let read_online = cx.background().spawn(async move {
676 let values = db.read(keys)?;
677 anyhow::Ok(
678 values
679 .into_iter()
680 .all(|e| e.map_or(online_by_default, |e| e == [true as u8])),
681 )
682 });
683 cx.spawn(|this, mut cx| async move {
684 let online = read_online.await.log_err().unwrap_or(false);
685 this.update(&mut cx, |this, cx| {
686 this.initialized_persistent_state = true;
687 if let ProjectClientState::Local { online_tx, .. } = &mut this.client_state {
688 let mut online_tx = online_tx.borrow_mut();
689 if *online_tx != online {
690 *online_tx = online;
691 drop(online_tx);
692 this.metadata_changed(false, cx);
693 }
694 }
695 });
696 Ok(())
697 })
698 }
699
700 fn persist_state(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
701 if self.is_remote() || !self.initialized_persistent_state {
702 return Task::ready(Ok(()));
703 }
704
705 let db = self.project_store.read(cx).db.clone();
706 let keys = self.db_keys_for_online_state(cx);
707 let is_online = self.is_online();
708 cx.background().spawn(async move {
709 let value = &[is_online as u8];
710 db.write(keys.into_iter().map(|key| (key, value)))
711 })
712 }
713
714 fn on_settings_changed(&mut self, cx: &mut ModelContext<'_, Self>) {
715 let settings = cx.global::<Settings>();
716 self.lsp_settings_changed = Some(cx.spawn(|project, cx| async {
717 let language_servers_to_start = project.update(&mut cx, |project, cx| {
718 let mut language_servers_to_start = Vec::new();
719 for buffer in self.opened_buffers.values() {
720 if let Some(buffer) = buffer.upgrade(cx) {
721 let buffer = buffer.read(cx);
722 if let Some((file, language)) =
723 File::from_dyn(buffer.file()).zip(buffer.language())
724 {
725 if settings.enable_language_server(Some(&language.name())) {
726 let worktree = file.worktree.read(cx);
727 language_servers_to_start.push((
728 worktree.id(),
729 worktree.as_local().unwrap().abs_path().clone(),
730 language.clone(),
731 ));
732 }
733 }
734 }
735 }
736 language_servers_to_start
737 });
738
739 let mut language_servers_to_stop = Vec::new();
740 for language in self.languages.to_vec() {
741 if let Some(lsp_adapter) = language.lsp_adapter() {
742 if !settings.enable_language_server(Some(&language.name())) {
743 let lsp_name = lsp_adapter.name().await;
744 for (worktree_id, started_lsp_name) in self.started_language_servers.keys()
745 {
746 if lsp_name == *started_lsp_name {
747 language_servers_to_stop
748 .push((*worktree_id, started_lsp_name.clone()));
749 }
750 }
751 }
752 }
753 }
754
755 project.update(&mut cx, |project, cx| {
756 // Stop all newly-disabled language servers.
757 for (worktree_id, adapter_name) in language_servers_to_stop {
758 self.stop_language_server(worktree_id, adapter_name, cx)
759 .detach();
760 }
761
762 // Start all the newly-enabled language servers.
763 for (worktree_id, worktree_path, language) in language_servers_to_start {
764 self.start_language_server(worktree_id, worktree_path, language, cx);
765 }
766
767 cx.notify();
768 });
769 }))
770
771 // // TODO(isaac): uncomment the above
772 // todo!()
773 }
774
775 pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
776 self.opened_buffers
777 .get(&remote_id)
778 .and_then(|buffer| buffer.upgrade(cx))
779 }
780
781 pub fn languages(&self) -> &Arc<LanguageRegistry> {
782 &self.languages
783 }
784
785 pub fn client(&self) -> Arc<Client> {
786 self.client.clone()
787 }
788
789 pub fn user_store(&self) -> ModelHandle<UserStore> {
790 self.user_store.clone()
791 }
792
793 pub fn project_store(&self) -> ModelHandle<ProjectStore> {
794 self.project_store.clone()
795 }
796
797 #[cfg(any(test, feature = "test-support"))]
798 pub fn check_invariants(&self, cx: &AppContext) {
799 if self.is_local() {
800 let mut worktree_root_paths = HashMap::default();
801 for worktree in self.worktrees(cx) {
802 let worktree = worktree.read(cx);
803 let abs_path = worktree.as_local().unwrap().abs_path().clone();
804 let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
805 assert_eq!(
806 prev_worktree_id,
807 None,
808 "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
809 abs_path,
810 worktree.id(),
811 prev_worktree_id
812 )
813 }
814 } else {
815 let replica_id = self.replica_id();
816 for buffer in self.opened_buffers.values() {
817 if let Some(buffer) = buffer.upgrade(cx) {
818 let buffer = buffer.read(cx);
819 assert_eq!(
820 buffer.deferred_ops_len(),
821 0,
822 "replica {}, buffer {} has deferred operations",
823 replica_id,
824 buffer.remote_id()
825 );
826 }
827 }
828 }
829 }
830
831 #[cfg(any(test, feature = "test-support"))]
832 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
833 let path = path.into();
834 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
835 self.opened_buffers.iter().any(|(_, buffer)| {
836 if let Some(buffer) = buffer.upgrade(cx) {
837 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
838 if file.worktree == worktree && file.path() == &path.path {
839 return true;
840 }
841 }
842 }
843 false
844 })
845 } else {
846 false
847 }
848 }
849
850 pub fn fs(&self) -> &Arc<dyn Fs> {
851 &self.fs
852 }
853
854 pub fn set_online(&mut self, online: bool, _: &mut ModelContext<Self>) {
855 if let ProjectClientState::Local { online_tx, .. } = &mut self.client_state {
856 let mut online_tx = online_tx.borrow_mut();
857 if *online_tx != online {
858 *online_tx = online;
859 }
860 }
861 }
862
863 pub fn is_online(&self) -> bool {
864 match &self.client_state {
865 ProjectClientState::Local { online_rx, .. } => *online_rx.borrow(),
866 ProjectClientState::Remote { .. } => true,
867 }
868 }
869
870 fn unregister(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
871 self.unshared(cx);
872 if let ProjectClientState::Local { remote_id_rx, .. } = &mut self.client_state {
873 if let Some(remote_id) = *remote_id_rx.borrow() {
874 let request = self.client.request(proto::UnregisterProject {
875 project_id: remote_id,
876 });
877 return cx.spawn(|this, mut cx| async move {
878 let response = request.await;
879
880 // Unregistering the project causes the server to send out a
881 // contact update removing this project from the host's list
882 // of online projects. Wait until this contact update has been
883 // processed before clearing out this project's remote id, so
884 // that there is no moment where this project appears in the
885 // contact metadata and *also* has no remote id.
886 this.update(&mut cx, |this, cx| {
887 this.user_store()
888 .update(cx, |store, _| store.contact_updates_done())
889 })
890 .await;
891
892 this.update(&mut cx, |this, cx| {
893 if let ProjectClientState::Local { remote_id_tx, .. } =
894 &mut this.client_state
895 {
896 *remote_id_tx.borrow_mut() = None;
897 }
898 this.client_subscriptions.clear();
899 this.metadata_changed(false, cx);
900 });
901 response.map(drop)
902 });
903 }
904 }
905 Task::ready(Ok(()))
906 }
907
908 fn register(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
909 if let ProjectClientState::Local {
910 remote_id_rx,
911 online_rx,
912 ..
913 } = &self.client_state
914 {
915 if remote_id_rx.borrow().is_some() {
916 return Task::ready(Ok(()));
917 }
918
919 let response = self.client.request(proto::RegisterProject {
920 online: *online_rx.borrow(),
921 });
922 cx.spawn(|this, mut cx| async move {
923 let remote_id = response.await?.project_id;
924 this.update(&mut cx, |this, cx| {
925 if let ProjectClientState::Local { remote_id_tx, .. } = &mut this.client_state {
926 *remote_id_tx.borrow_mut() = Some(remote_id);
927 }
928
929 this.metadata_changed(false, cx);
930 cx.emit(Event::RemoteIdChanged(Some(remote_id)));
931 this.client_subscriptions
932 .push(this.client.add_model_for_remote_entity(remote_id, cx));
933 Ok(())
934 })
935 })
936 } else {
937 Task::ready(Err(anyhow!("can't register a remote project")))
938 }
939 }
940
941 pub fn remote_id(&self) -> Option<u64> {
942 match &self.client_state {
943 ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
944 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
945 }
946 }
947
948 pub fn next_remote_id(&self) -> impl Future<Output = u64> {
949 let mut id = None;
950 let mut watch = None;
951 match &self.client_state {
952 ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
953 ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
954 }
955
956 async move {
957 if let Some(id) = id {
958 return id;
959 }
960 let mut watch = watch.unwrap();
961 loop {
962 let id = *watch.borrow();
963 if let Some(id) = id {
964 return id;
965 }
966 watch.next().await;
967 }
968 }
969 }
970
971 pub fn shared_remote_id(&self) -> Option<u64> {
972 match &self.client_state {
973 ProjectClientState::Local {
974 remote_id_rx,
975 is_shared,
976 ..
977 } => {
978 if *is_shared {
979 *remote_id_rx.borrow()
980 } else {
981 None
982 }
983 }
984 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
985 }
986 }
987
988 pub fn replica_id(&self) -> ReplicaId {
989 match &self.client_state {
990 ProjectClientState::Local { .. } => 0,
991 ProjectClientState::Remote { replica_id, .. } => *replica_id,
992 }
993 }
994
995 fn metadata_changed(&mut self, persist: bool, cx: &mut ModelContext<Self>) {
996 if let ProjectClientState::Local {
997 remote_id_rx,
998 online_rx,
999 ..
1000 } = &self.client_state
1001 {
1002 // Broadcast worktrees only if the project is online.
1003 let worktrees = if *online_rx.borrow() {
1004 self.worktrees
1005 .iter()
1006 .filter_map(|worktree| {
1007 worktree
1008 .upgrade(&cx)
1009 .map(|worktree| worktree.read(cx).as_local().unwrap().metadata_proto())
1010 })
1011 .collect()
1012 } else {
1013 Default::default()
1014 };
1015 if let Some(project_id) = *remote_id_rx.borrow() {
1016 let online = *online_rx.borrow();
1017 self.client
1018 .send(proto::UpdateProject {
1019 project_id,
1020 worktrees,
1021 online,
1022 })
1023 .log_err();
1024
1025 if online {
1026 let worktrees = self.visible_worktrees(cx).collect::<Vec<_>>();
1027 let scans_complete =
1028 futures::future::join_all(worktrees.iter().filter_map(|worktree| {
1029 Some(worktree.read(cx).as_local()?.scan_complete())
1030 }));
1031
1032 let worktrees = worktrees.into_iter().map(|handle| handle.downgrade());
1033 cx.spawn_weak(move |_, cx| async move {
1034 scans_complete.await;
1035 cx.read(|cx| {
1036 for worktree in worktrees {
1037 if let Some(worktree) = worktree
1038 .upgrade(cx)
1039 .and_then(|worktree| worktree.read(cx).as_local())
1040 {
1041 worktree.send_extension_counts(project_id);
1042 }
1043 }
1044 })
1045 })
1046 .detach();
1047 }
1048 }
1049
1050 self.project_store.update(cx, |_, cx| cx.notify());
1051 if persist {
1052 self.persist_state(cx).detach_and_log_err(cx);
1053 }
1054 cx.notify();
1055 }
1056 }
1057
1058 pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
1059 &self.collaborators
1060 }
1061
1062 pub fn worktrees<'a>(
1063 &'a self,
1064 cx: &'a AppContext,
1065 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1066 self.worktrees
1067 .iter()
1068 .filter_map(move |worktree| worktree.upgrade(cx))
1069 }
1070
1071 pub fn visible_worktrees<'a>(
1072 &'a self,
1073 cx: &'a AppContext,
1074 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1075 self.worktrees.iter().filter_map(|worktree| {
1076 worktree.upgrade(cx).and_then(|worktree| {
1077 if worktree.read(cx).is_visible() {
1078 Some(worktree)
1079 } else {
1080 None
1081 }
1082 })
1083 })
1084 }
1085
1086 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1087 self.visible_worktrees(cx)
1088 .map(|tree| tree.read(cx).root_name())
1089 }
1090
1091 fn db_keys_for_online_state(&self, cx: &AppContext) -> Vec<String> {
1092 self.worktrees
1093 .iter()
1094 .filter_map(|worktree| {
1095 let worktree = worktree.upgrade(&cx)?.read(cx);
1096 if worktree.is_visible() {
1097 Some(format!(
1098 "project-path-online:{}",
1099 worktree.as_local().unwrap().abs_path().to_string_lossy()
1100 ))
1101 } else {
1102 None
1103 }
1104 })
1105 .collect::<Vec<_>>()
1106 }
1107
1108 pub fn worktree_for_id(
1109 &self,
1110 id: WorktreeId,
1111 cx: &AppContext,
1112 ) -> Option<ModelHandle<Worktree>> {
1113 self.worktrees(cx)
1114 .find(|worktree| worktree.read(cx).id() == id)
1115 }
1116
1117 pub fn worktree_for_entry(
1118 &self,
1119 entry_id: ProjectEntryId,
1120 cx: &AppContext,
1121 ) -> Option<ModelHandle<Worktree>> {
1122 self.worktrees(cx)
1123 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
1124 }
1125
1126 pub fn worktree_id_for_entry(
1127 &self,
1128 entry_id: ProjectEntryId,
1129 cx: &AppContext,
1130 ) -> Option<WorktreeId> {
1131 self.worktree_for_entry(entry_id, cx)
1132 .map(|worktree| worktree.read(cx).id())
1133 }
1134
1135 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
1136 paths.iter().all(|path| self.contains_path(&path, cx))
1137 }
1138
1139 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
1140 for worktree in self.worktrees(cx) {
1141 let worktree = worktree.read(cx).as_local();
1142 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
1143 return true;
1144 }
1145 }
1146 false
1147 }
1148
1149 pub fn create_entry(
1150 &mut self,
1151 project_path: impl Into<ProjectPath>,
1152 is_directory: bool,
1153 cx: &mut ModelContext<Self>,
1154 ) -> Option<Task<Result<Entry>>> {
1155 let project_path = project_path.into();
1156 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1157 if self.is_local() {
1158 Some(worktree.update(cx, |worktree, cx| {
1159 worktree
1160 .as_local_mut()
1161 .unwrap()
1162 .create_entry(project_path.path, is_directory, cx)
1163 }))
1164 } else {
1165 let client = self.client.clone();
1166 let project_id = self.remote_id().unwrap();
1167 Some(cx.spawn_weak(|_, mut cx| async move {
1168 let response = client
1169 .request(proto::CreateProjectEntry {
1170 worktree_id: project_path.worktree_id.to_proto(),
1171 project_id,
1172 path: project_path.path.as_os_str().as_bytes().to_vec(),
1173 is_directory,
1174 })
1175 .await?;
1176 let entry = response
1177 .entry
1178 .ok_or_else(|| anyhow!("missing entry in response"))?;
1179 worktree
1180 .update(&mut cx, |worktree, cx| {
1181 worktree.as_remote_mut().unwrap().insert_entry(
1182 entry,
1183 response.worktree_scan_id as usize,
1184 cx,
1185 )
1186 })
1187 .await
1188 }))
1189 }
1190 }
1191
1192 pub fn copy_entry(
1193 &mut self,
1194 entry_id: ProjectEntryId,
1195 new_path: impl Into<Arc<Path>>,
1196 cx: &mut ModelContext<Self>,
1197 ) -> Option<Task<Result<Entry>>> {
1198 let worktree = self.worktree_for_entry(entry_id, cx)?;
1199 let new_path = new_path.into();
1200 if self.is_local() {
1201 worktree.update(cx, |worktree, cx| {
1202 worktree
1203 .as_local_mut()
1204 .unwrap()
1205 .copy_entry(entry_id, new_path, cx)
1206 })
1207 } else {
1208 let client = self.client.clone();
1209 let project_id = self.remote_id().unwrap();
1210
1211 Some(cx.spawn_weak(|_, mut cx| async move {
1212 let response = client
1213 .request(proto::CopyProjectEntry {
1214 project_id,
1215 entry_id: entry_id.to_proto(),
1216 new_path: new_path.as_os_str().as_bytes().to_vec(),
1217 })
1218 .await?;
1219 let entry = response
1220 .entry
1221 .ok_or_else(|| anyhow!("missing entry in response"))?;
1222 worktree
1223 .update(&mut cx, |worktree, cx| {
1224 worktree.as_remote_mut().unwrap().insert_entry(
1225 entry,
1226 response.worktree_scan_id as usize,
1227 cx,
1228 )
1229 })
1230 .await
1231 }))
1232 }
1233 }
1234
1235 pub fn rename_entry(
1236 &mut self,
1237 entry_id: ProjectEntryId,
1238 new_path: impl Into<Arc<Path>>,
1239 cx: &mut ModelContext<Self>,
1240 ) -> Option<Task<Result<Entry>>> {
1241 let worktree = self.worktree_for_entry(entry_id, cx)?;
1242 let new_path = new_path.into();
1243 if self.is_local() {
1244 worktree.update(cx, |worktree, cx| {
1245 worktree
1246 .as_local_mut()
1247 .unwrap()
1248 .rename_entry(entry_id, new_path, cx)
1249 })
1250 } else {
1251 let client = self.client.clone();
1252 let project_id = self.remote_id().unwrap();
1253
1254 Some(cx.spawn_weak(|_, mut cx| async move {
1255 let response = client
1256 .request(proto::RenameProjectEntry {
1257 project_id,
1258 entry_id: entry_id.to_proto(),
1259 new_path: new_path.as_os_str().as_bytes().to_vec(),
1260 })
1261 .await?;
1262 let entry = response
1263 .entry
1264 .ok_or_else(|| anyhow!("missing entry in response"))?;
1265 worktree
1266 .update(&mut cx, |worktree, cx| {
1267 worktree.as_remote_mut().unwrap().insert_entry(
1268 entry,
1269 response.worktree_scan_id as usize,
1270 cx,
1271 )
1272 })
1273 .await
1274 }))
1275 }
1276 }
1277
1278 pub fn delete_entry(
1279 &mut self,
1280 entry_id: ProjectEntryId,
1281 cx: &mut ModelContext<Self>,
1282 ) -> Option<Task<Result<()>>> {
1283 let worktree = self.worktree_for_entry(entry_id, cx)?;
1284 if self.is_local() {
1285 worktree.update(cx, |worktree, cx| {
1286 worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1287 })
1288 } else {
1289 let client = self.client.clone();
1290 let project_id = self.remote_id().unwrap();
1291 Some(cx.spawn_weak(|_, mut cx| async move {
1292 let response = client
1293 .request(proto::DeleteProjectEntry {
1294 project_id,
1295 entry_id: entry_id.to_proto(),
1296 })
1297 .await?;
1298 worktree
1299 .update(&mut cx, move |worktree, cx| {
1300 worktree.as_remote_mut().unwrap().delete_entry(
1301 entry_id,
1302 response.worktree_scan_id as usize,
1303 cx,
1304 )
1305 })
1306 .await
1307 }))
1308 }
1309 }
1310
1311 fn share(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
1312 if !self.is_online() {
1313 return Task::ready(Err(anyhow!("can't share an offline project")));
1314 }
1315
1316 let project_id;
1317 if let ProjectClientState::Local {
1318 remote_id_rx,
1319 is_shared,
1320 ..
1321 } = &mut self.client_state
1322 {
1323 if *is_shared {
1324 return Task::ready(Ok(()));
1325 }
1326 *is_shared = true;
1327 if let Some(id) = *remote_id_rx.borrow() {
1328 project_id = id;
1329 } else {
1330 return Task::ready(Err(anyhow!("project hasn't been registered")));
1331 }
1332 } else {
1333 return Task::ready(Err(anyhow!("can't share a remote project")));
1334 };
1335
1336 for open_buffer in self.opened_buffers.values_mut() {
1337 match open_buffer {
1338 OpenBuffer::Strong(_) => {}
1339 OpenBuffer::Weak(buffer) => {
1340 if let Some(buffer) = buffer.upgrade(cx) {
1341 *open_buffer = OpenBuffer::Strong(buffer);
1342 }
1343 }
1344 OpenBuffer::Loading(_) => unreachable!(),
1345 }
1346 }
1347
1348 for worktree_handle in self.worktrees.iter_mut() {
1349 match worktree_handle {
1350 WorktreeHandle::Strong(_) => {}
1351 WorktreeHandle::Weak(worktree) => {
1352 if let Some(worktree) = worktree.upgrade(cx) {
1353 *worktree_handle = WorktreeHandle::Strong(worktree);
1354 }
1355 }
1356 }
1357 }
1358
1359 let mut tasks = Vec::new();
1360 for worktree in self.worktrees(cx).collect::<Vec<_>>() {
1361 worktree.update(cx, |worktree, cx| {
1362 let worktree = worktree.as_local_mut().unwrap();
1363 tasks.push(worktree.share(project_id, cx));
1364 });
1365 }
1366
1367 for (server_id, status) in &self.language_server_statuses {
1368 self.client
1369 .send(proto::StartLanguageServer {
1370 project_id,
1371 server: Some(proto::LanguageServer {
1372 id: *server_id as u64,
1373 name: status.name.clone(),
1374 }),
1375 })
1376 .log_err();
1377 }
1378
1379 cx.spawn(|this, mut cx| async move {
1380 for task in tasks {
1381 task.await?;
1382 }
1383 this.update(&mut cx, |_, cx| cx.notify());
1384 Ok(())
1385 })
1386 }
1387
1388 fn unshared(&mut self, cx: &mut ModelContext<Self>) {
1389 if let ProjectClientState::Local { is_shared, .. } = &mut self.client_state {
1390 if !*is_shared {
1391 return;
1392 }
1393
1394 *is_shared = false;
1395 self.collaborators.clear();
1396 self.shared_buffers.clear();
1397 for worktree_handle in self.worktrees.iter_mut() {
1398 if let WorktreeHandle::Strong(worktree) = worktree_handle {
1399 let is_visible = worktree.update(cx, |worktree, _| {
1400 worktree.as_local_mut().unwrap().unshare();
1401 worktree.is_visible()
1402 });
1403 if !is_visible {
1404 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1405 }
1406 }
1407 }
1408
1409 for open_buffer in self.opened_buffers.values_mut() {
1410 match open_buffer {
1411 OpenBuffer::Strong(buffer) => {
1412 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1413 }
1414 _ => {}
1415 }
1416 }
1417
1418 cx.notify();
1419 } else {
1420 log::error!("attempted to unshare a remote project");
1421 }
1422 }
1423
1424 pub fn respond_to_join_request(
1425 &mut self,
1426 requester_id: u64,
1427 allow: bool,
1428 cx: &mut ModelContext<Self>,
1429 ) {
1430 if let Some(project_id) = self.remote_id() {
1431 let share = if self.is_online() && allow {
1432 Some(self.share(cx))
1433 } else {
1434 None
1435 };
1436 let client = self.client.clone();
1437 cx.foreground()
1438 .spawn(async move {
1439 client.send(proto::RespondToJoinProjectRequest {
1440 requester_id,
1441 project_id,
1442 allow,
1443 })?;
1444 if let Some(share) = share {
1445 share.await?;
1446 }
1447 anyhow::Ok(())
1448 })
1449 .detach_and_log_err(cx);
1450 }
1451 }
1452
1453 fn removed_from_project(&mut self, cx: &mut ModelContext<Self>) {
1454 if let ProjectClientState::Remote {
1455 sharing_has_stopped,
1456 ..
1457 } = &mut self.client_state
1458 {
1459 *sharing_has_stopped = true;
1460 self.collaborators.clear();
1461 for worktree in &self.worktrees {
1462 if let Some(worktree) = worktree.upgrade(cx) {
1463 worktree.update(cx, |worktree, _| {
1464 if let Some(worktree) = worktree.as_remote_mut() {
1465 worktree.disconnected_from_host();
1466 }
1467 });
1468 }
1469 }
1470 cx.notify();
1471 }
1472 }
1473
1474 pub fn is_read_only(&self) -> bool {
1475 match &self.client_state {
1476 ProjectClientState::Local { .. } => false,
1477 ProjectClientState::Remote {
1478 sharing_has_stopped,
1479 ..
1480 } => *sharing_has_stopped,
1481 }
1482 }
1483
1484 pub fn is_local(&self) -> bool {
1485 match &self.client_state {
1486 ProjectClientState::Local { .. } => true,
1487 ProjectClientState::Remote { .. } => false,
1488 }
1489 }
1490
1491 pub fn is_remote(&self) -> bool {
1492 !self.is_local()
1493 }
1494
1495 pub fn create_buffer(
1496 &mut self,
1497 text: &str,
1498 language: Option<Arc<Language>>,
1499 cx: &mut ModelContext<Self>,
1500 ) -> Result<ModelHandle<Buffer>> {
1501 if self.is_remote() {
1502 return Err(anyhow!("creating buffers as a guest is not supported yet"));
1503 }
1504
1505 let buffer = cx.add_model(|cx| {
1506 Buffer::new(self.replica_id(), text, cx)
1507 .with_language(language.unwrap_or(language::PLAIN_TEXT.clone()), cx)
1508 });
1509 self.register_buffer(&buffer, cx)?;
1510 Ok(buffer)
1511 }
1512
1513 pub fn open_path(
1514 &mut self,
1515 path: impl Into<ProjectPath>,
1516 cx: &mut ModelContext<Self>,
1517 ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1518 let task = self.open_buffer(path, cx);
1519 cx.spawn_weak(|_, cx| async move {
1520 let buffer = task.await?;
1521 let project_entry_id = buffer
1522 .read_with(&cx, |buffer, cx| {
1523 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1524 })
1525 .ok_or_else(|| anyhow!("no project entry"))?;
1526 Ok((project_entry_id, buffer.into()))
1527 })
1528 }
1529
1530 pub fn open_local_buffer(
1531 &mut self,
1532 abs_path: impl AsRef<Path>,
1533 cx: &mut ModelContext<Self>,
1534 ) -> Task<Result<ModelHandle<Buffer>>> {
1535 if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1536 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1537 } else {
1538 Task::ready(Err(anyhow!("no such path")))
1539 }
1540 }
1541
1542 pub fn open_buffer(
1543 &mut self,
1544 path: impl Into<ProjectPath>,
1545 cx: &mut ModelContext<Self>,
1546 ) -> Task<Result<ModelHandle<Buffer>>> {
1547 let project_path = path.into();
1548 let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1549 worktree
1550 } else {
1551 return Task::ready(Err(anyhow!("no such worktree")));
1552 };
1553
1554 // If there is already a buffer for the given path, then return it.
1555 let existing_buffer = self.get_open_buffer(&project_path, cx);
1556 if let Some(existing_buffer) = existing_buffer {
1557 return Task::ready(Ok(existing_buffer));
1558 }
1559
1560 let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
1561 // If the given path is already being loaded, then wait for that existing
1562 // task to complete and return the same buffer.
1563 hash_map::Entry::Occupied(e) => e.get().clone(),
1564
1565 // Otherwise, record the fact that this path is now being loaded.
1566 hash_map::Entry::Vacant(entry) => {
1567 let (mut tx, rx) = postage::watch::channel();
1568 entry.insert(rx.clone());
1569
1570 let load_buffer = if worktree.read(cx).is_local() {
1571 self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1572 } else {
1573 self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1574 };
1575
1576 cx.spawn(move |this, mut cx| async move {
1577 let load_result = load_buffer.await;
1578 *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1579 // Record the fact that the buffer is no longer loading.
1580 this.loading_buffers.remove(&project_path);
1581 let buffer = load_result.map_err(Arc::new)?;
1582 Ok(buffer)
1583 }));
1584 })
1585 .detach();
1586 rx
1587 }
1588 };
1589
1590 cx.foreground().spawn(async move {
1591 loop {
1592 if let Some(result) = loading_watch.borrow().as_ref() {
1593 match result {
1594 Ok(buffer) => return Ok(buffer.clone()),
1595 Err(error) => return Err(anyhow!("{}", error)),
1596 }
1597 }
1598 loading_watch.next().await;
1599 }
1600 })
1601 }
1602
1603 fn open_local_buffer_internal(
1604 &mut self,
1605 path: &Arc<Path>,
1606 worktree: &ModelHandle<Worktree>,
1607 cx: &mut ModelContext<Self>,
1608 ) -> Task<Result<ModelHandle<Buffer>>> {
1609 let load_buffer = worktree.update(cx, |worktree, cx| {
1610 let worktree = worktree.as_local_mut().unwrap();
1611 worktree.load_buffer(path, cx)
1612 });
1613 cx.spawn(|this, mut cx| async move {
1614 let buffer = load_buffer.await?;
1615 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1616 Ok(buffer)
1617 })
1618 }
1619
1620 fn open_remote_buffer_internal(
1621 &mut self,
1622 path: &Arc<Path>,
1623 worktree: &ModelHandle<Worktree>,
1624 cx: &mut ModelContext<Self>,
1625 ) -> Task<Result<ModelHandle<Buffer>>> {
1626 let rpc = self.client.clone();
1627 let project_id = self.remote_id().unwrap();
1628 let remote_worktree_id = worktree.read(cx).id();
1629 let path = path.clone();
1630 let path_string = path.to_string_lossy().to_string();
1631 cx.spawn(|this, mut cx| async move {
1632 let response = rpc
1633 .request(proto::OpenBufferByPath {
1634 project_id,
1635 worktree_id: remote_worktree_id.to_proto(),
1636 path: path_string,
1637 })
1638 .await?;
1639 let buffer = response.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
1640 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1641 .await
1642 })
1643 }
1644
1645 fn open_local_buffer_via_lsp(
1646 &mut self,
1647 abs_path: lsp::Url,
1648 language_server_id: usize,
1649 language_server_name: LanguageServerName,
1650 cx: &mut ModelContext<Self>,
1651 ) -> Task<Result<ModelHandle<Buffer>>> {
1652 cx.spawn(|this, mut cx| async move {
1653 let abs_path = abs_path
1654 .to_file_path()
1655 .map_err(|_| anyhow!("can't convert URI to path"))?;
1656 let (worktree, relative_path) = if let Some(result) =
1657 this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1658 {
1659 result
1660 } else {
1661 let worktree = this
1662 .update(&mut cx, |this, cx| {
1663 this.create_local_worktree(&abs_path, false, cx)
1664 })
1665 .await?;
1666 let name = lsp_adapter.name().await;
1667 this.update(&mut cx, |this, cx| {
1668 this.language_servers
1669 .insert((worktree.read(cx).id(), name), (lsp_adapter, lsp_server));
1670 });
1671 (worktree, PathBuf::new())
1672 };
1673
1674 let project_path = ProjectPath {
1675 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1676 path: relative_path.into(),
1677 };
1678 this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1679 .await
1680 })
1681 }
1682
1683 pub fn open_buffer_by_id(
1684 &mut self,
1685 id: u64,
1686 cx: &mut ModelContext<Self>,
1687 ) -> Task<Result<ModelHandle<Buffer>>> {
1688 if let Some(buffer) = self.buffer_for_id(id, cx) {
1689 Task::ready(Ok(buffer))
1690 } else if self.is_local() {
1691 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1692 } else if let Some(project_id) = self.remote_id() {
1693 let request = self
1694 .client
1695 .request(proto::OpenBufferById { project_id, id });
1696 cx.spawn(|this, mut cx| async move {
1697 let buffer = request
1698 .await?
1699 .buffer
1700 .ok_or_else(|| anyhow!("invalid buffer"))?;
1701 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1702 .await
1703 })
1704 } else {
1705 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1706 }
1707 }
1708
1709 pub fn save_buffer_as(
1710 &mut self,
1711 buffer: ModelHandle<Buffer>,
1712 abs_path: PathBuf,
1713 cx: &mut ModelContext<Project>,
1714 ) -> Task<Result<()>> {
1715 let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1716 let old_path =
1717 File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1718 cx.spawn(|this, mut cx| async move {
1719 if let Some(old_path) = old_path {
1720 this.update(&mut cx, |this, cx| {
1721 this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1722 });
1723 }
1724 let (worktree, path) = worktree_task.await?;
1725 worktree
1726 .update(&mut cx, |worktree, cx| {
1727 worktree
1728 .as_local_mut()
1729 .unwrap()
1730 .save_buffer_as(buffer.clone(), path, cx)
1731 })
1732 .await?;
1733 this.update(&mut cx, |this, cx| {
1734 this.assign_language_to_buffer(&buffer, cx);
1735 this.register_buffer_with_language_server(&buffer, cx)
1736 })
1737 .await;
1738 Ok(())
1739 })
1740 }
1741
1742 pub fn get_open_buffer(
1743 &mut self,
1744 path: &ProjectPath,
1745 cx: &mut ModelContext<Self>,
1746 ) -> Option<ModelHandle<Buffer>> {
1747 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1748 self.opened_buffers.values().find_map(|buffer| {
1749 let buffer = buffer.upgrade(cx)?;
1750 let file = File::from_dyn(buffer.read(cx).file())?;
1751 if file.worktree == worktree && file.path() == &path.path {
1752 Some(buffer)
1753 } else {
1754 None
1755 }
1756 })
1757 }
1758
1759 fn register_buffer(
1760 &mut self,
1761 buffer: &ModelHandle<Buffer>,
1762 cx: &mut ModelContext<Self>,
1763 ) -> Result<()> {
1764 let remote_id = buffer.read(cx).remote_id();
1765 let open_buffer = if self.is_remote() || self.is_shared() {
1766 OpenBuffer::Strong(buffer.clone())
1767 } else {
1768 OpenBuffer::Weak(buffer.downgrade())
1769 };
1770
1771 match self.opened_buffers.insert(remote_id, open_buffer) {
1772 None => {}
1773 Some(OpenBuffer::Loading(operations)) => {
1774 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1775 }
1776 Some(OpenBuffer::Weak(existing_handle)) => {
1777 if existing_handle.upgrade(cx).is_some() {
1778 Err(anyhow!(
1779 "already registered buffer with remote id {}",
1780 remote_id
1781 ))?
1782 }
1783 }
1784 Some(OpenBuffer::Strong(_)) => Err(anyhow!(
1785 "already registered buffer with remote id {}",
1786 remote_id
1787 ))?,
1788 }
1789 cx.subscribe(buffer, |this, buffer, event, cx| {
1790 // TODO(isaac): should this be done in the background?
1791 this.on_buffer_event(buffer, event, cx).await;
1792 })
1793 .detach();
1794
1795 self.assign_language_to_buffer(buffer, cx);
1796 // TODO(isaac): should this be done in the background
1797 self.register_buffer_with_language_server(buffer, cx).await;
1798 cx.observe_release(buffer, |this, buffer, cx| {
1799 if let Some(file) = File::from_dyn(buffer.file()) {
1800 if file.is_local() {
1801 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1802 if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1803 server
1804 .notify::<lsp::notification::DidCloseTextDocument>(
1805 lsp::DidCloseTextDocumentParams {
1806 text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1807 },
1808 )
1809 .log_err();
1810 }
1811 }
1812 }
1813 })
1814 .detach();
1815
1816 Ok(())
1817 }
1818
1819 async fn register_buffer_with_language_server(
1820 &mut self,
1821 buffer_handle: &ModelHandle<Buffer>,
1822 cx: &mut ModelContext<'_, Self>,
1823 ) {
1824 let buffer = buffer_handle.read(cx);
1825 let buffer_id = buffer.remote_id();
1826 if let Some(file) = File::from_dyn(buffer.file()) {
1827 if file.is_local() {
1828 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1829 let initial_snapshot = buffer.text_snapshot();
1830
1831 let mut language_server = None;
1832 let mut language_id = None;
1833 if let Some(language) = buffer.language() {
1834 let worktree_id = file.worktree_id(cx);
1835 if let Some(adapter) = language.lsp_adapter() {
1836 language_id = adapter.id_for_language(language.name().as_ref()).await;
1837 language_server = self
1838 .language_server_ids
1839 .get(&(worktree_id, adapter.name()))
1840 .and_then(|id| self.language_servers.get(&id))
1841 .and_then(|server_state| {
1842 if let LanguageServerState::Running { server, .. } = server_state {
1843 Some(server.clone())
1844 } else {
1845 None
1846 }
1847 });
1848 }
1849 }
1850
1851 if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1852 if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1853 self.update_buffer_diagnostics(&buffer_handle, diagnostics, None, cx)
1854 .log_err();
1855 }
1856 }
1857
1858 if let Some(server) = language_server {
1859 server
1860 .notify::<lsp::notification::DidOpenTextDocument>(
1861 lsp::DidOpenTextDocumentParams {
1862 text_document: lsp::TextDocumentItem::new(
1863 uri,
1864 language_id.unwrap_or_default(),
1865 0,
1866 initial_snapshot.text(),
1867 ),
1868 }
1869 .clone(),
1870 )
1871 .log_err();
1872 buffer_handle.update(cx, |buffer, cx| {
1873 buffer.set_completion_triggers(
1874 server
1875 .capabilities()
1876 .completion_provider
1877 .as_ref()
1878 .and_then(|provider| provider.trigger_characters.clone())
1879 .unwrap_or(Vec::new()),
1880 cx,
1881 )
1882 });
1883 self.buffer_snapshots
1884 .insert(buffer_id, vec![(0, initial_snapshot)]);
1885 }
1886 }
1887 }
1888 }
1889
1890 fn unregister_buffer_from_language_server(
1891 &mut self,
1892 buffer: &ModelHandle<Buffer>,
1893 old_path: PathBuf,
1894 cx: &mut ModelContext<Self>,
1895 ) {
1896 buffer.update(cx, |buffer, cx| {
1897 buffer.update_diagnostics(Default::default(), cx);
1898 self.buffer_snapshots.remove(&buffer.remote_id());
1899 if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1900 language_server
1901 .notify::<lsp::notification::DidCloseTextDocument>(
1902 lsp::DidCloseTextDocumentParams {
1903 text_document: lsp::TextDocumentIdentifier::new(
1904 lsp::Url::from_file_path(old_path).unwrap(),
1905 ),
1906 },
1907 )
1908 .log_err();
1909 }
1910 });
1911 }
1912
1913 async fn on_buffer_event(
1914 &mut self,
1915 buffer: ModelHandle<Buffer>,
1916 event: &BufferEvent,
1917 cx: &mut ModelContext<'_, Self>,
1918 ) -> Option<()> {
1919 match event {
1920 BufferEvent::Operation(operation) => {
1921 if let Some(project_id) = self.shared_remote_id() {
1922 let request = self.client.request(proto::UpdateBuffer {
1923 project_id,
1924 buffer_id: buffer.read(cx).remote_id(),
1925 operations: vec![language::proto::serialize_operation(&operation)],
1926 });
1927 cx.background().spawn(request).detach_and_log_err(cx);
1928 } else if let Some(project_id) = self.remote_id() {
1929 let _ = self
1930 .client
1931 .send(proto::RegisterProjectActivity { project_id });
1932 }
1933 }
1934 BufferEvent::Edited { .. } => {
1935 let language_server = self
1936 .language_server_for_buffer(buffer.read(cx), cx)
1937 .map(|(_, server)| server.clone())?;
1938 let buffer = buffer.read(cx);
1939 let file = File::from_dyn(buffer.file())?;
1940 let abs_path = file.as_local()?.abs_path(cx);
1941 let uri = lsp::Url::from_file_path(abs_path).unwrap();
1942 let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1943 let (version, prev_snapshot) = buffer_snapshots.last()?;
1944 let next_snapshot = buffer.text_snapshot();
1945 let next_version = version + 1;
1946
1947 let content_changes = buffer
1948 .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1949 .map(|edit| {
1950 let edit_start = edit.new.start.0;
1951 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1952 let new_text = next_snapshot
1953 .text_for_range(edit.new.start.1..edit.new.end.1)
1954 .collect();
1955 lsp::TextDocumentContentChangeEvent {
1956 range: Some(lsp::Range::new(
1957 point_to_lsp(edit_start),
1958 point_to_lsp(edit_end),
1959 )),
1960 range_length: None,
1961 text: new_text,
1962 }
1963 })
1964 .collect();
1965
1966 buffer_snapshots.push((next_version, next_snapshot));
1967
1968 language_server
1969 .notify::<lsp::notification::DidChangeTextDocument>(
1970 lsp::DidChangeTextDocumentParams {
1971 text_document: lsp::VersionedTextDocumentIdentifier::new(
1972 uri,
1973 next_version,
1974 ),
1975 content_changes,
1976 },
1977 )
1978 .log_err();
1979 }
1980 BufferEvent::Saved => {
1981 let file = File::from_dyn(buffer.read(cx).file())?;
1982 let worktree_id = file.worktree_id(cx);
1983 let abs_path = file.as_local()?.abs_path(cx);
1984 let text_document = lsp::TextDocumentIdentifier {
1985 uri: lsp::Url::from_file_path(abs_path).unwrap(),
1986 };
1987
1988 for (_, server) in self.language_servers_for_worktree(worktree_id) {
1989 server
1990 .notify::<lsp::notification::DidSaveTextDocument>(
1991 lsp::DidSaveTextDocumentParams {
1992 text_document: text_document.clone(),
1993 text: None,
1994 },
1995 )
1996 .log_err();
1997 }
1998
1999 // After saving a buffer, simulate disk-based diagnostics being finished for languages
2000 // that don't support a disk-based progress token.
2001 let (lsp_adapter, language_server) =
2002 self.language_server_for_buffer(buffer.read(cx), cx)?;
2003 if lsp_adapter
2004 .disk_based_diagnostics_progress_token()
2005 .await
2006 .is_none()
2007 {
2008 let server_id = language_server.server_id();
2009 self.disk_based_diagnostics_finished(server_id, cx);
2010 self.broadcast_language_server_update(
2011 server_id,
2012 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2013 proto::LspDiskBasedDiagnosticsUpdated {},
2014 ),
2015 );
2016 }
2017 }
2018 _ => {}
2019 }
2020
2021 None
2022 }
2023
2024 fn language_servers_for_worktree(
2025 &self,
2026 worktree_id: WorktreeId,
2027 ) -> impl Iterator<Item = (&Arc<dyn LspAdapter>, &Arc<LanguageServer>)> {
2028 self.language_server_ids
2029 .iter()
2030 .filter_map(move |((language_server_worktree_id, _), id)| {
2031 if *language_server_worktree_id == worktree_id {
2032 if let Some(LanguageServerState::Running { adapter, server }) =
2033 self.language_servers.get(&id)
2034 {
2035 return Some((adapter, server));
2036 }
2037 }
2038 None
2039 })
2040 }
2041
2042 fn assign_language_to_buffer(
2043 &mut self,
2044 buffer: &ModelHandle<Buffer>,
2045 cx: &mut ModelContext<Self>,
2046 ) -> Option<()> {
2047 // If the buffer has a language, set it and start the language server if we haven't already.
2048 let full_path = buffer.read(cx).file()?.full_path(cx);
2049 let language = self.languages.select_language(&full_path)?;
2050 buffer.update(cx, |buffer, cx| {
2051 buffer.set_language(Some(language.clone()), cx);
2052 });
2053
2054 let file = File::from_dyn(buffer.read(cx).file())?;
2055 let worktree = file.worktree.read(cx).as_local()?;
2056 let worktree_id = worktree.id();
2057 let worktree_abs_path = worktree.abs_path().clone();
2058 self.start_language_server(worktree_id, worktree_abs_path, language, cx)
2059 .await;
2060
2061 None
2062 }
2063
2064 async fn start_language_server(
2065 &mut self,
2066 worktree_id: WorktreeId,
2067 worktree_path: Arc<Path>,
2068 language: Arc<Language>,
2069 cx: &mut ModelContext<'_, Self>,
2070 ) {
2071 if !cx
2072 .global::<Settings>()
2073 .enable_language_server(Some(&language.name()))
2074 {
2075 return;
2076 }
2077
2078 let adapter = if let Some(adapter) = language.lsp_adapter() {
2079 adapter
2080 } else {
2081 return;
2082 };
2083 let key = (worktree_id, adapter.name());
2084
2085 self.language_server_ids
2086 .entry(key.clone())
2087 .or_insert_with(|| {
2088 let server_id = post_inc(&mut self.next_language_server_id);
2089 let language_server = self.languages.start_language_server(
2090 server_id,
2091 language.clone(),
2092 worktree_path,
2093 self.client.http_client(),
2094 cx,
2095 );
2096
2097 self.language_servers.insert(
2098 server_id,
2099 LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
2100 let language_server = language_server?.await.log_err()?;
2101 let language_server = language_server
2102 .initialize(adapter.initialization_options())
2103 .await
2104 .log_err()?;
2105 let this = this.upgrade(&cx)?;
2106 let disk_based_diagnostics_progress_token =
2107 adapter.disk_based_diagnostics_progress_token();
2108
2109 language_server
2110 .on_notification::<lsp::notification::PublishDiagnostics, _>({
2111 let this = this.downgrade();
2112 let adapter = adapter.clone();
2113 move |params, mut cx| {
2114 if let Some(this) = this.upgrade(&cx) {
2115 this.update(&mut cx, |this, cx| {
2116 this.on_lsp_diagnostics_published(
2117 server_id, params, &adapter, cx,
2118 );
2119 });
2120 }
2121 }
2122 })
2123 .detach();
2124
2125 language_server
2126 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2127 let settings = this.read_with(&cx, |this, _| {
2128 this.language_server_settings.clone()
2129 });
2130 move |params, _| {
2131 let settings = settings.lock().clone();
2132 async move {
2133 Ok(params
2134 .items
2135 .into_iter()
2136 .map(|item| {
2137 if let Some(section) = &item.section {
2138 settings
2139 .get(section)
2140 .cloned()
2141 .unwrap_or(serde_json::Value::Null)
2142 } else {
2143 settings.clone()
2144 }
2145 })
2146 .collect())
2147 }
2148 }
2149 })
2150 .detach();
2151
2152 // Even though we don't have handling for these requests, respond to them to
2153 // avoid stalling any language server like `gopls` which waits for a response
2154 // to these requests when initializing.
2155 language_server
2156 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2157 let this = this.downgrade();
2158 move |params, mut cx| async move {
2159 if let Some(this) = this.upgrade(&cx) {
2160 this.update(&mut cx, |this, _| {
2161 if let Some(status) =
2162 this.language_server_statuses.get_mut(&server_id)
2163 {
2164 if let lsp::NumberOrString::String(token) =
2165 params.token
2166 {
2167 status.progress_tokens.insert(token);
2168 }
2169 }
2170 });
2171 }
2172 Ok(())
2173 }
2174 })
2175 .detach();
2176 language_server
2177 .on_request::<lsp::request::RegisterCapability, _, _>(|_, _| async {
2178 Ok(())
2179 })
2180 .detach();
2181
2182 language_server
2183 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2184 let this = this.downgrade();
2185 let adapter = adapter.clone();
2186 let language_server = language_server.clone();
2187 move |params, cx| {
2188 Self::on_lsp_workspace_edit(
2189 this,
2190 params,
2191 server_id,
2192 adapter.clone(),
2193 language_server.clone(),
2194 cx,
2195 )
2196
2197 }
2198 })
2199 .detach();
2200
2201 language_server
2202 .on_notification::<lsp::notification::Progress, _>({
2203 let this = this.downgrade();
2204 move |params, mut cx| {
2205 if let Some(this) = this.upgrade(&cx) {
2206 this.update(&mut cx, |this, cx| {
2207 this.on_lsp_progress(
2208 params,
2209 server_id,
2210 disk_based_diagnostics_progress_token,
2211 cx,
2212 );
2213 });
2214 }
2215 }
2216 })
2217 .detach();
2218
2219 this.update(&mut cx, |this, cx| {
2220 // If the language server for this key doesn't match the server id, don't store the
2221 // server. Which will cause it to be dropped, killing the process
2222 if this
2223 .language_server_ids
2224 .get(&key)
2225 .map(|id| id != &server_id)
2226 .unwrap_or(false)
2227 {
2228 return None;
2229 }
2230
2231 // Update language_servers collection with Running variant of LanguageServerState
2232 // indicating that the server is up and running and ready
2233 this.language_servers.insert(
2234 server_id,
2235 LanguageServerState::Running {
2236 adapter: adapter.clone(),
2237 server: language_server.clone(),
2238 },
2239 );
2240 this.language_server_statuses.insert(
2241 server_id,
2242 LanguageServerStatus {
2243 name: language_server.name().to_string(),
2244 pending_work: Default::default(),
2245 has_pending_diagnostic_updates: false,
2246 progress_tokens: Default::default(),
2247 },
2248 );
2249 language_server
2250 .notify::<lsp::notification::DidChangeConfiguration>(
2251 lsp::DidChangeConfigurationParams {
2252 settings: this.language_server_settings.lock().clone(),
2253 },
2254 )
2255 .ok();
2256
2257 if let Some(project_id) = this.shared_remote_id() {
2258 this.client
2259 .send(proto::StartLanguageServer {
2260 project_id,
2261 server: Some(proto::LanguageServer {
2262 id: server_id as u64,
2263 name: language_server.name().to_string(),
2264 }),
2265 })
2266 .log_err();
2267 }
2268
2269 // Tell the language server about every open buffer in the worktree that matches the language.
2270 for buffer in this.opened_buffers.values() {
2271 if let Some(buffer_handle) = buffer.upgrade(cx) {
2272 let buffer = buffer_handle.read(cx);
2273 let file = if let Some(file) = File::from_dyn(buffer.file()) {
2274 file
2275 } else {
2276 continue;
2277 };
2278 let language = if let Some(language) = buffer.language() {
2279 language
2280 } else {
2281 continue;
2282 };
2283 if file.worktree.read(cx).id() != key.0
2284 || language.lsp_adapter().map(|a| a.name())
2285 != Some(key.1.clone())
2286 {
2287 continue;
2288 }
2289
2290 let file = file.as_local()?;
2291 let versions = this
2292 .buffer_snapshots
2293 .entry(buffer.remote_id())
2294 .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2295 let (version, initial_snapshot) = versions.last().unwrap();
2296 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2297 let language_id =
2298 adapter.id_for_language(language.name().as_ref());
2299 language_server
2300 .notify::<lsp::notification::DidOpenTextDocument>(
2301 lsp::DidOpenTextDocumentParams {
2302 text_document: lsp::TextDocumentItem::new(
2303 uri,
2304 language_id.unwrap_or_default(),
2305 *version,
2306 initial_snapshot.text(),
2307 ),
2308 },
2309 )
2310 .log_err()?;
2311 buffer_handle.update(cx, |buffer, cx| {
2312 buffer.set_completion_triggers(
2313 language_server
2314 .capabilities()
2315 .completion_provider
2316 .as_ref()
2317 .and_then(|provider| {
2318 provider.trigger_characters.clone()
2319 })
2320 .unwrap_or(Vec::new()),
2321 cx,
2322 )
2323 });
2324 }
2325 }
2326
2327 cx.notify();
2328 Some(language_server)
2329 })
2330 })),
2331 );
2332
2333 server_id
2334 });
2335 }
2336
2337 // Returns a list of all of the worktrees which no longer have a language server and the root path
2338 // for the stopped server
2339 fn stop_language_server(
2340 &mut self,
2341 worktree_id: WorktreeId,
2342 adapter_name: LanguageServerName,
2343 cx: &mut ModelContext<Self>,
2344 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2345 let key = (worktree_id, adapter_name);
2346 if let Some(server_id) = self.language_server_ids.remove(&key) {
2347 // Remove other entries for this language server as well
2348 let mut orphaned_worktrees = vec![worktree_id];
2349 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2350 for other_key in other_keys {
2351 if self.language_server_ids.get(&other_key) == Some(&server_id) {
2352 self.language_server_ids.remove(&other_key);
2353 orphaned_worktrees.push(other_key.0);
2354 }
2355 }
2356
2357 self.language_server_statuses.remove(&server_id);
2358 cx.notify();
2359
2360 let server_state = self.language_servers.remove(&server_id);
2361 cx.spawn_weak(|this, mut cx| async move {
2362 let mut root_path = None;
2363
2364 let server = match server_state {
2365 Some(LanguageServerState::Starting(started_language_server)) => {
2366 started_language_server.await
2367 }
2368 Some(LanguageServerState::Running { server, .. }) => Some(server),
2369 None => None,
2370 };
2371
2372 if let Some(server) = server {
2373 root_path = Some(server.root_path().clone());
2374 if let Some(shutdown) = server.shutdown() {
2375 shutdown.await;
2376 }
2377 }
2378
2379 if let Some(this) = this.upgrade(&cx) {
2380 this.update(&mut cx, |this, cx| {
2381 this.language_server_statuses.remove(&server_id);
2382 cx.notify();
2383 });
2384 }
2385
2386 (root_path, orphaned_worktrees)
2387 })
2388 } else {
2389 Task::ready((None, Vec::new()))
2390 }
2391 }
2392
2393 pub fn restart_language_servers_for_buffers(
2394 &mut self,
2395 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2396 cx: &mut ModelContext<Self>,
2397 ) -> Option<()> {
2398 let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2399 .into_iter()
2400 .filter_map(|buffer| {
2401 let file = File::from_dyn(buffer.read(cx).file())?;
2402 let worktree = file.worktree.read(cx).as_local()?;
2403 let worktree_id = worktree.id();
2404 let worktree_abs_path = worktree.abs_path().clone();
2405 let full_path = file.full_path(cx);
2406 Some((worktree_id, worktree_abs_path, full_path))
2407 })
2408 .collect();
2409 for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2410 let language = self.languages.select_language(&full_path)?;
2411 self.restart_language_server(worktree_id, worktree_abs_path, language, cx)
2412 .await;
2413 }
2414
2415 None
2416 }
2417
2418 async fn restart_language_server(
2419 &mut self,
2420 worktree_id: WorktreeId,
2421 fallback_path: Arc<Path>,
2422 language: Arc<Language>,
2423 cx: &mut ModelContext<'_, Self>,
2424 ) {
2425 let adapter = if let Some(adapter) = language.lsp_adapter() {
2426 adapter
2427 } else {
2428 return;
2429 };
2430 let server_name = adapter.name();
2431 let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2432 cx.spawn_weak(|this, mut cx| async move {
2433 let (original_root_path, orphaned_worktrees) = stop.await;
2434 if let Some(this) = this.upgrade(&cx) {
2435 this.update(&mut cx, |this, cx| {
2436 // Attempt to restart using original server path. Fallback to passed in
2437 // path if we could not retrieve the root path
2438 let root_path = original_root_path
2439 .map(|path_buf| Arc::from(path_buf.as_path()))
2440 .unwrap_or(fallback_path);
2441
2442 this.start_language_server(worktree_id, root_path, language, cx);
2443
2444 // Lookup new server id and set it for each of the orphaned worktrees
2445 if let Some(new_server_id) = this
2446 .language_server_ids
2447 .get(&(worktree_id, server_name.clone()))
2448 .cloned()
2449 {
2450 for orphaned_worktree in orphaned_worktrees {
2451 this.language_server_ids.insert(
2452 (orphaned_worktree, server_name.clone()),
2453 new_server_id.clone(),
2454 );
2455 }
2456 }
2457 });
2458 }
2459 })
2460 .detach();
2461 }
2462
2463 async fn on_lsp_diagnostics_published(
2464 &mut self,
2465 server_id: usize,
2466 mut params: lsp::PublishDiagnosticsParams,
2467 adapter: &Arc<dyn LspAdapter>,
2468 cx: &mut ModelContext<'_, Self>,
2469 ) {
2470 adapter.process_diagnostics(&mut params).await;
2471 self.update_diagnostics(
2472 server_id,
2473 params,
2474 adapter.disk_based_diagnostic_sources().await,
2475 cx,
2476 )
2477 .log_err();
2478 }
2479
2480 fn on_lsp_progress(
2481 &mut self,
2482 progress: lsp::ProgressParams,
2483 server_id: usize,
2484 disk_based_diagnostics_progress_token: Option<String>,
2485 cx: &mut ModelContext<Self>,
2486 ) {
2487 let token = match progress.token {
2488 lsp::NumberOrString::String(token) => token,
2489 lsp::NumberOrString::Number(token) => {
2490 log::info!("skipping numeric progress token {}", token);
2491 return;
2492 }
2493 };
2494 let progress = match progress.value {
2495 lsp::ProgressParamsValue::WorkDone(value) => value,
2496 };
2497 let language_server_status =
2498 if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2499 status
2500 } else {
2501 return;
2502 };
2503
2504 if !language_server_status.progress_tokens.contains(&token) {
2505 return;
2506 }
2507
2508 let same_token =
2509 Some(token.as_ref()) == disk_based_diagnostics_progress_token.as_ref().map(|x| &**x);
2510
2511 match progress {
2512 lsp::WorkDoneProgress::Begin(report) => {
2513 if same_token {
2514 language_server_status.has_pending_diagnostic_updates = true;
2515 self.disk_based_diagnostics_started(server_id, cx);
2516 self.broadcast_language_server_update(
2517 server_id,
2518 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2519 proto::LspDiskBasedDiagnosticsUpdating {},
2520 ),
2521 );
2522 } else {
2523 self.on_lsp_work_start(
2524 server_id,
2525 token.clone(),
2526 LanguageServerProgress {
2527 message: report.message.clone(),
2528 percentage: report.percentage.map(|p| p as usize),
2529 last_update_at: Instant::now(),
2530 },
2531 cx,
2532 );
2533 self.broadcast_language_server_update(
2534 server_id,
2535 proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2536 token,
2537 message: report.message,
2538 percentage: report.percentage.map(|p| p as u32),
2539 }),
2540 );
2541 }
2542 }
2543 lsp::WorkDoneProgress::Report(report) => {
2544 if !same_token {
2545 self.on_lsp_work_progress(
2546 server_id,
2547 token.clone(),
2548 LanguageServerProgress {
2549 message: report.message.clone(),
2550 percentage: report.percentage.map(|p| p as usize),
2551 last_update_at: Instant::now(),
2552 },
2553 cx,
2554 );
2555 self.broadcast_language_server_update(
2556 server_id,
2557 proto::update_language_server::Variant::WorkProgress(
2558 proto::LspWorkProgress {
2559 token,
2560 message: report.message,
2561 percentage: report.percentage.map(|p| p as u32),
2562 },
2563 ),
2564 );
2565 }
2566 }
2567 lsp::WorkDoneProgress::End(_) => {
2568 language_server_status.progress_tokens.remove(&token);
2569
2570 if same_token {
2571 language_server_status.has_pending_diagnostic_updates = false;
2572 self.disk_based_diagnostics_finished(server_id, cx);
2573 self.broadcast_language_server_update(
2574 server_id,
2575 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2576 proto::LspDiskBasedDiagnosticsUpdated {},
2577 ),
2578 );
2579 } else {
2580 self.on_lsp_work_end(server_id, token.clone(), cx);
2581 self.broadcast_language_server_update(
2582 server_id,
2583 proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2584 token,
2585 }),
2586 );
2587 }
2588 }
2589 }
2590 }
2591
2592 fn on_lsp_work_start(
2593 &mut self,
2594 language_server_id: usize,
2595 token: String,
2596 progress: LanguageServerProgress,
2597 cx: &mut ModelContext<Self>,
2598 ) {
2599 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2600 status.pending_work.insert(token, progress);
2601 cx.notify();
2602 }
2603 }
2604
2605 fn on_lsp_work_progress(
2606 &mut self,
2607 language_server_id: usize,
2608 token: String,
2609 progress: LanguageServerProgress,
2610 cx: &mut ModelContext<Self>,
2611 ) {
2612 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2613 let entry = status
2614 .pending_work
2615 .entry(token)
2616 .or_insert(LanguageServerProgress {
2617 message: Default::default(),
2618 percentage: Default::default(),
2619 last_update_at: progress.last_update_at,
2620 });
2621 if progress.message.is_some() {
2622 entry.message = progress.message;
2623 }
2624 if progress.percentage.is_some() {
2625 entry.percentage = progress.percentage;
2626 }
2627 entry.last_update_at = progress.last_update_at;
2628 cx.notify();
2629 }
2630 }
2631
2632 fn on_lsp_work_end(
2633 &mut self,
2634 language_server_id: usize,
2635 token: String,
2636 cx: &mut ModelContext<Self>,
2637 ) {
2638 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2639 status.pending_work.remove(&token);
2640 cx.notify();
2641 }
2642 }
2643
2644 async fn on_lsp_workspace_edit(
2645 this: WeakModelHandle<Self>,
2646 params: lsp::ApplyWorkspaceEditParams,
2647 server_id: usize,
2648 adapter: Arc<dyn LspAdapter>,
2649 language_server: Arc<LanguageServer>,
2650 mut cx: AsyncAppContext,
2651 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2652 let this = this
2653 .upgrade(&cx)
2654 .ok_or_else(|| anyhow!("project project closed"))?;
2655 let transaction = Self::deserialize_workspace_edit(
2656 this.clone(),
2657 params.edit,
2658 true,
2659 adapter.clone(),
2660 language_server.clone(),
2661 &mut cx,
2662 )
2663 .await
2664 .log_err();
2665 this.update(&mut cx, |this, _| {
2666 if let Some(transaction) = transaction {
2667 this.last_workspace_edits_by_language_server
2668 .insert(server_id, transaction);
2669 }
2670 });
2671 Ok(lsp::ApplyWorkspaceEditResponse {
2672 applied: true,
2673 failed_change: None,
2674 failure_reason: None,
2675 })
2676 }
2677
2678 fn broadcast_language_server_update(
2679 &self,
2680 language_server_id: usize,
2681 event: proto::update_language_server::Variant,
2682 ) {
2683 if let Some(project_id) = self.shared_remote_id() {
2684 self.client
2685 .send(proto::UpdateLanguageServer {
2686 project_id,
2687 language_server_id: language_server_id as u64,
2688 variant: Some(event),
2689 })
2690 .log_err();
2691 }
2692 }
2693
2694 pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2695 for server_state in self.language_servers.values() {
2696 if let LanguageServerState::Running { server, .. } = server_state {
2697 server
2698 .notify::<lsp::notification::DidChangeConfiguration>(
2699 lsp::DidChangeConfigurationParams {
2700 settings: settings.clone(),
2701 },
2702 )
2703 .ok();
2704 }
2705 }
2706 *self.language_server_settings.lock() = settings;
2707 }
2708
2709 pub fn language_server_statuses(
2710 &self,
2711 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2712 self.language_server_statuses.values()
2713 }
2714
2715 pub fn update_diagnostics(
2716 &mut self,
2717 language_server_id: usize,
2718 params: lsp::PublishDiagnosticsParams,
2719 disk_based_sources: Vec<String>,
2720 cx: &mut ModelContext<Self>,
2721 ) -> Result<()> {
2722 let abs_path = params
2723 .uri
2724 .to_file_path()
2725 .map_err(|_| anyhow!("URI is not a file"))?;
2726 let mut diagnostics = Vec::default();
2727 let mut primary_diagnostic_group_ids = HashMap::default();
2728 let mut sources_by_group_id = HashMap::default();
2729 let mut supporting_diagnostics = HashMap::default();
2730 for diagnostic in ¶ms.diagnostics {
2731 let source = diagnostic.source.as_ref();
2732 let code = diagnostic.code.as_ref().map(|code| match code {
2733 lsp::NumberOrString::Number(code) => code.to_string(),
2734 lsp::NumberOrString::String(code) => code.clone(),
2735 });
2736 let range = range_from_lsp(diagnostic.range);
2737 let is_supporting = diagnostic
2738 .related_information
2739 .as_ref()
2740 .map_or(false, |infos| {
2741 infos.iter().any(|info| {
2742 primary_diagnostic_group_ids.contains_key(&(
2743 source,
2744 code.clone(),
2745 range_from_lsp(info.location.range),
2746 ))
2747 })
2748 });
2749
2750 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2751 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2752 });
2753
2754 if is_supporting {
2755 supporting_diagnostics.insert(
2756 (source, code.clone(), range),
2757 (diagnostic.severity, is_unnecessary),
2758 );
2759 } else {
2760 let group_id = post_inc(&mut self.next_diagnostic_group_id);
2761 let is_disk_based =
2762 source.map_or(false, |source| disk_based_sources.contains(&source));
2763
2764 sources_by_group_id.insert(group_id, source);
2765 primary_diagnostic_group_ids
2766 .insert((source, code.clone(), range.clone()), group_id);
2767
2768 diagnostics.push(DiagnosticEntry {
2769 range,
2770 diagnostic: Diagnostic {
2771 code: code.clone(),
2772 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2773 message: diagnostic.message.clone(),
2774 group_id,
2775 is_primary: true,
2776 is_valid: true,
2777 is_disk_based,
2778 is_unnecessary,
2779 },
2780 });
2781 if let Some(infos) = &diagnostic.related_information {
2782 for info in infos {
2783 if info.location.uri == params.uri && !info.message.is_empty() {
2784 let range = range_from_lsp(info.location.range);
2785 diagnostics.push(DiagnosticEntry {
2786 range,
2787 diagnostic: Diagnostic {
2788 code: code.clone(),
2789 severity: DiagnosticSeverity::INFORMATION,
2790 message: info.message.clone(),
2791 group_id,
2792 is_primary: false,
2793 is_valid: true,
2794 is_disk_based,
2795 is_unnecessary: false,
2796 },
2797 });
2798 }
2799 }
2800 }
2801 }
2802 }
2803
2804 for entry in &mut diagnostics {
2805 let diagnostic = &mut entry.diagnostic;
2806 if !diagnostic.is_primary {
2807 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2808 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2809 source,
2810 diagnostic.code.clone(),
2811 entry.range.clone(),
2812 )) {
2813 if let Some(severity) = severity {
2814 diagnostic.severity = severity;
2815 }
2816 diagnostic.is_unnecessary = is_unnecessary;
2817 }
2818 }
2819 }
2820
2821 self.update_diagnostic_entries(
2822 language_server_id,
2823 abs_path,
2824 params.version,
2825 diagnostics,
2826 cx,
2827 )?;
2828 Ok(())
2829 }
2830
2831 pub fn update_diagnostic_entries(
2832 &mut self,
2833 language_server_id: usize,
2834 abs_path: PathBuf,
2835 version: Option<i32>,
2836 diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2837 cx: &mut ModelContext<Project>,
2838 ) -> Result<(), anyhow::Error> {
2839 let (worktree, relative_path) = self
2840 .find_local_worktree(&abs_path, cx)
2841 .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2842
2843 let project_path = ProjectPath {
2844 worktree_id: worktree.read(cx).id(),
2845 path: relative_path.into(),
2846 };
2847 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2848 self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2849 }
2850
2851 let updated = worktree.update(cx, |worktree, cx| {
2852 worktree
2853 .as_local_mut()
2854 .ok_or_else(|| anyhow!("not a local worktree"))?
2855 .update_diagnostics(
2856 language_server_id,
2857 project_path.path.clone(),
2858 diagnostics,
2859 cx,
2860 )
2861 })?;
2862 if updated {
2863 cx.emit(Event::DiagnosticsUpdated {
2864 language_server_id,
2865 path: project_path,
2866 });
2867 }
2868 Ok(())
2869 }
2870
2871 fn update_buffer_diagnostics(
2872 &mut self,
2873 buffer: &ModelHandle<Buffer>,
2874 mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2875 version: Option<i32>,
2876 cx: &mut ModelContext<Self>,
2877 ) -> Result<()> {
2878 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2879 Ordering::Equal
2880 .then_with(|| b.is_primary.cmp(&a.is_primary))
2881 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2882 .then_with(|| a.severity.cmp(&b.severity))
2883 .then_with(|| a.message.cmp(&b.message))
2884 }
2885
2886 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2887
2888 diagnostics.sort_unstable_by(|a, b| {
2889 Ordering::Equal
2890 .then_with(|| a.range.start.cmp(&b.range.start))
2891 .then_with(|| b.range.end.cmp(&a.range.end))
2892 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2893 });
2894
2895 let mut sanitized_diagnostics = Vec::new();
2896 let edits_since_save = Patch::new(
2897 snapshot
2898 .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2899 .collect(),
2900 );
2901 for entry in diagnostics {
2902 let start;
2903 let end;
2904 if entry.diagnostic.is_disk_based {
2905 // Some diagnostics are based on files on disk instead of buffers'
2906 // current contents. Adjust these diagnostics' ranges to reflect
2907 // any unsaved edits.
2908 start = edits_since_save.old_to_new(entry.range.start);
2909 end = edits_since_save.old_to_new(entry.range.end);
2910 } else {
2911 start = entry.range.start;
2912 end = entry.range.end;
2913 }
2914
2915 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2916 ..snapshot.clip_point_utf16(end, Bias::Right);
2917
2918 // Expand empty ranges by one character
2919 if range.start == range.end {
2920 range.end.column += 1;
2921 range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2922 if range.start == range.end && range.end.column > 0 {
2923 range.start.column -= 1;
2924 range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2925 }
2926 }
2927
2928 sanitized_diagnostics.push(DiagnosticEntry {
2929 range,
2930 diagnostic: entry.diagnostic,
2931 });
2932 }
2933 drop(edits_since_save);
2934
2935 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2936 buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2937 Ok(())
2938 }
2939
2940 pub fn reload_buffers(
2941 &self,
2942 buffers: HashSet<ModelHandle<Buffer>>,
2943 push_to_history: bool,
2944 cx: &mut ModelContext<Self>,
2945 ) -> Task<Result<ProjectTransaction>> {
2946 let mut local_buffers = Vec::new();
2947 let mut remote_buffers = None;
2948 for buffer_handle in buffers {
2949 let buffer = buffer_handle.read(cx);
2950 if buffer.is_dirty() {
2951 if let Some(file) = File::from_dyn(buffer.file()) {
2952 if file.is_local() {
2953 local_buffers.push(buffer_handle);
2954 } else {
2955 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2956 }
2957 }
2958 }
2959 }
2960
2961 let remote_buffers = self.remote_id().zip(remote_buffers);
2962 let client = self.client.clone();
2963
2964 cx.spawn(|this, mut cx| async move {
2965 let mut project_transaction = ProjectTransaction::default();
2966
2967 if let Some((project_id, remote_buffers)) = remote_buffers {
2968 let response = client
2969 .request(proto::ReloadBuffers {
2970 project_id,
2971 buffer_ids: remote_buffers
2972 .iter()
2973 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2974 .collect(),
2975 })
2976 .await?
2977 .transaction
2978 .ok_or_else(|| anyhow!("missing transaction"))?;
2979 project_transaction = this
2980 .update(&mut cx, |this, cx| {
2981 this.deserialize_project_transaction(response, push_to_history, cx)
2982 })
2983 .await?;
2984 }
2985
2986 for buffer in local_buffers {
2987 let transaction = buffer
2988 .update(&mut cx, |buffer, cx| buffer.reload(cx))
2989 .await?;
2990 buffer.update(&mut cx, |buffer, cx| {
2991 if let Some(transaction) = transaction {
2992 if !push_to_history {
2993 buffer.forget_transaction(transaction.id);
2994 }
2995 project_transaction.0.insert(cx.handle(), transaction);
2996 }
2997 });
2998 }
2999
3000 Ok(project_transaction)
3001 })
3002 }
3003
3004 pub fn format(
3005 &self,
3006 buffers: HashSet<ModelHandle<Buffer>>,
3007 push_to_history: bool,
3008 cx: &mut ModelContext<Project>,
3009 ) -> Task<Result<ProjectTransaction>> {
3010 let mut local_buffers = Vec::new();
3011 let mut remote_buffers = None;
3012 for buffer_handle in buffers {
3013 let buffer = buffer_handle.read(cx);
3014 if let Some(file) = File::from_dyn(buffer.file()) {
3015 if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
3016 if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
3017 local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
3018 }
3019 } else {
3020 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3021 }
3022 } else {
3023 return Task::ready(Ok(Default::default()));
3024 }
3025 }
3026
3027 let remote_buffers = self.remote_id().zip(remote_buffers);
3028 let client = self.client.clone();
3029
3030 cx.spawn(|this, mut cx| async move {
3031 let mut project_transaction = ProjectTransaction::default();
3032
3033 if let Some((project_id, remote_buffers)) = remote_buffers {
3034 let response = client
3035 .request(proto::FormatBuffers {
3036 project_id,
3037 buffer_ids: remote_buffers
3038 .iter()
3039 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3040 .collect(),
3041 })
3042 .await?
3043 .transaction
3044 .ok_or_else(|| anyhow!("missing transaction"))?;
3045 project_transaction = this
3046 .update(&mut cx, |this, cx| {
3047 this.deserialize_project_transaction(response, push_to_history, cx)
3048 })
3049 .await?;
3050 }
3051
3052 for (buffer, buffer_abs_path, language_server) in local_buffers {
3053 let (format_on_save, tab_size) = buffer.read_with(&cx, |buffer, cx| {
3054 let settings = cx.global::<Settings>();
3055 let language_name = buffer.language().map(|language| language.name());
3056 (
3057 settings.format_on_save(language_name.as_deref()),
3058 settings.tab_size(language_name.as_deref()),
3059 )
3060 });
3061
3062 let transaction = match format_on_save {
3063 settings::FormatOnSave::Off => continue,
3064 settings::FormatOnSave::LanguageServer => Self::format_via_lsp(
3065 &this,
3066 &buffer,
3067 &buffer_abs_path,
3068 &language_server,
3069 tab_size,
3070 &mut cx,
3071 )
3072 .await
3073 .context("failed to format via language server")?,
3074 settings::FormatOnSave::External { command, arguments } => {
3075 Self::format_via_external_command(
3076 &buffer,
3077 &buffer_abs_path,
3078 &command,
3079 &arguments,
3080 &mut cx,
3081 )
3082 .await
3083 .context(format!(
3084 "failed to format via external command {:?}",
3085 command
3086 ))?
3087 }
3088 };
3089
3090 if let Some(transaction) = transaction {
3091 if !push_to_history {
3092 buffer.update(&mut cx, |buffer, _| {
3093 buffer.forget_transaction(transaction.id)
3094 });
3095 }
3096 project_transaction.0.insert(buffer, transaction);
3097 }
3098 }
3099
3100 Ok(project_transaction)
3101 })
3102 }
3103
3104 async fn format_via_lsp(
3105 this: &ModelHandle<Self>,
3106 buffer: &ModelHandle<Buffer>,
3107 abs_path: &Path,
3108 language_server: &Arc<LanguageServer>,
3109 tab_size: NonZeroU32,
3110 cx: &mut AsyncAppContext,
3111 ) -> Result<Option<Transaction>> {
3112 let text_document =
3113 lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3114 let capabilities = &language_server.capabilities();
3115 let lsp_edits = if capabilities
3116 .document_formatting_provider
3117 .as_ref()
3118 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3119 {
3120 language_server
3121 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3122 text_document,
3123 options: lsp::FormattingOptions {
3124 tab_size: tab_size.into(),
3125 insert_spaces: true,
3126 insert_final_newline: Some(true),
3127 ..Default::default()
3128 },
3129 work_done_progress_params: Default::default(),
3130 })
3131 .await?
3132 } else if capabilities
3133 .document_range_formatting_provider
3134 .as_ref()
3135 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3136 {
3137 let buffer_start = lsp::Position::new(0, 0);
3138 let buffer_end =
3139 buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3140 language_server
3141 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3142 text_document,
3143 range: lsp::Range::new(buffer_start, buffer_end),
3144 options: lsp::FormattingOptions {
3145 tab_size: tab_size.into(),
3146 insert_spaces: true,
3147 insert_final_newline: Some(true),
3148 ..Default::default()
3149 },
3150 work_done_progress_params: Default::default(),
3151 })
3152 .await?
3153 } else {
3154 None
3155 };
3156
3157 if let Some(lsp_edits) = lsp_edits {
3158 let edits = this
3159 .update(cx, |this, cx| {
3160 this.edits_from_lsp(&buffer, lsp_edits, None, cx)
3161 })
3162 .await?;
3163 buffer.update(cx, |buffer, cx| {
3164 buffer.finalize_last_transaction();
3165 buffer.start_transaction();
3166 for (range, text) in edits {
3167 buffer.edit([(range, text)], cx);
3168 }
3169 if buffer.end_transaction(cx).is_some() {
3170 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3171 Ok(Some(transaction))
3172 } else {
3173 Ok(None)
3174 }
3175 })
3176 } else {
3177 Ok(None)
3178 }
3179 }
3180
3181 async fn format_via_external_command(
3182 buffer: &ModelHandle<Buffer>,
3183 buffer_abs_path: &Path,
3184 command: &str,
3185 arguments: &[String],
3186 cx: &mut AsyncAppContext,
3187 ) -> Result<Option<Transaction>> {
3188 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3189 let file = File::from_dyn(buffer.file())?;
3190 let worktree = file.worktree.read(cx).as_local()?;
3191 let mut worktree_path = worktree.abs_path().to_path_buf();
3192 if worktree.root_entry()?.is_file() {
3193 worktree_path.pop();
3194 }
3195 Some(worktree_path)
3196 });
3197
3198 if let Some(working_dir_path) = working_dir_path {
3199 let mut child =
3200 smol::process::Command::new(command)
3201 .args(arguments.iter().map(|arg| {
3202 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3203 }))
3204 .current_dir(&working_dir_path)
3205 .stdin(smol::process::Stdio::piped())
3206 .stdout(smol::process::Stdio::piped())
3207 .stderr(smol::process::Stdio::piped())
3208 .spawn()?;
3209 let stdin = child
3210 .stdin
3211 .as_mut()
3212 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3213 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3214 for chunk in text.chunks() {
3215 stdin.write_all(chunk.as_bytes()).await?;
3216 }
3217 stdin.flush().await?;
3218
3219 let output = child.output().await?;
3220 if !output.status.success() {
3221 return Err(anyhow!(
3222 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3223 output.status.code(),
3224 String::from_utf8_lossy(&output.stdout),
3225 String::from_utf8_lossy(&output.stderr),
3226 ));
3227 }
3228
3229 let stdout = String::from_utf8(output.stdout)?;
3230 let diff = buffer
3231 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3232 .await;
3233 Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3234 } else {
3235 Ok(None)
3236 }
3237 }
3238
3239 pub fn definition<T: ToPointUtf16>(
3240 &self,
3241 buffer: &ModelHandle<Buffer>,
3242 position: T,
3243 cx: &mut ModelContext<Self>,
3244 ) -> Task<Result<Vec<LocationLink>>> {
3245 let position = position.to_point_utf16(buffer.read(cx));
3246 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3247 }
3248
3249 pub fn references<T: ToPointUtf16>(
3250 &self,
3251 buffer: &ModelHandle<Buffer>,
3252 position: T,
3253 cx: &mut ModelContext<Self>,
3254 ) -> Task<Result<Vec<Location>>> {
3255 let position = position.to_point_utf16(buffer.read(cx));
3256 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3257 }
3258
3259 pub fn document_highlights<T: ToPointUtf16>(
3260 &self,
3261 buffer: &ModelHandle<Buffer>,
3262 position: T,
3263 cx: &mut ModelContext<Self>,
3264 ) -> Task<Result<Vec<DocumentHighlight>>> {
3265 let position = position.to_point_utf16(buffer.read(cx));
3266
3267 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3268 }
3269
3270 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3271 if self.is_local() {
3272 let mut requests = Vec::new();
3273 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3274 let worktree_id = *worktree_id;
3275 if let Some(worktree) = self
3276 .worktree_for_id(worktree_id, cx)
3277 .and_then(|worktree| worktree.read(cx).as_local())
3278 {
3279 if let Some(LanguageServerState::Running { adapter, server }) =
3280 self.language_servers.get(server_id)
3281 {
3282 let adapter = adapter.clone();
3283 let worktree_abs_path = worktree.abs_path().clone();
3284 requests.push(
3285 server
3286 .request::<lsp::request::WorkspaceSymbol>(
3287 lsp::WorkspaceSymbolParams {
3288 query: query.to_string(),
3289 ..Default::default()
3290 },
3291 )
3292 .log_err()
3293 .map(move |response| {
3294 (
3295 adapter,
3296 worktree_id,
3297 worktree_abs_path,
3298 response.unwrap_or_default(),
3299 )
3300 }),
3301 );
3302 }
3303 }
3304 }
3305
3306 cx.spawn_weak(|this, cx| async move {
3307 let responses = futures::future::join_all(requests).await;
3308 let this = if let Some(this) = this.upgrade(&cx) {
3309 this
3310 } else {
3311 return Ok(Default::default());
3312 };
3313
3314 // TODO(isaac): also use join_all
3315 struct PartialSymbol {
3316 source_worktree_id: WorktreeId,
3317 worktree_id: WorktreeId,
3318 adapter: Arc<dyn LspAdapter>,
3319 path: PathBuf,
3320 language: Option<Arc<Language>>,
3321 name: String,
3322 kind: lsp::SymbolKind,
3323 range: Range<PointUtf16>,
3324 signature: [u8; 32],
3325 }
3326
3327 let partial_symbols = this.read_with(&cx, |this, cx| {
3328 let mut partial_symbols = Vec::new();
3329 for (adapter, source_worktree_id, worktree_abs_path, response) in responses {
3330 for lsp_symbol in response.into_iter().flatten() {
3331 let abs_path = match lsp_symbol.location.uri.to_file_path().ok() {
3332 Some(abs_path) => abs_path,
3333 None => continue,
3334 };
3335 let mut worktree_id = source_worktree_id;
3336 let path;
3337 if let Some((worktree, rel_path)) =
3338 this.find_local_worktree(&abs_path, cx)
3339 {
3340 worktree_id = worktree.read(cx).id();
3341 path = rel_path;
3342 } else {
3343 path = relativize_path(&worktree_abs_path, &abs_path);
3344 }
3345
3346 let language = this.languages.select_language(&path).clone();
3347 let signature = this.symbol_signature(worktree_id, &path);
3348
3349 partial_symbols.push(PartialSymbol {
3350 source_worktree_id,
3351 worktree_id,
3352 // TODO: just pass out single adapter?
3353 adapter: adapter.clone(),
3354 name: lsp_symbol.name,
3355 kind: lsp_symbol.kind,
3356 language,
3357 path,
3358 range: range_from_lsp(lsp_symbol.location.range),
3359 signature,
3360 });
3361 }
3362 }
3363
3364 partial_symbols
3365 });
3366
3367 let mut symbols = Vec::new();
3368 for ps in partial_symbols.into_iter() {
3369 let label = match ps.language {
3370 Some(language) => language.label_for_symbol(&ps.name, ps.kind).await,
3371 None => None,
3372 }
3373 .unwrap_or_else(|| CodeLabel::plain(ps.name.clone(), None));
3374
3375 let language_server_name = ps.adapter.name().await;
3376
3377 symbols.push(Symbol {
3378 source_worktree_id: ps.source_worktree_id,
3379 worktree_id: ps.worktree_id,
3380 language_server_name,
3381 name: ps.name,
3382 kind: ps.kind,
3383 label,
3384 path: ps.path,
3385 range: ps.range,
3386 signature: ps.signature,
3387 });
3388 }
3389
3390 Ok(symbols)
3391 })
3392 } else if let Some(project_id) = self.remote_id() {
3393 let request = self.client.request(proto::GetProjectSymbols {
3394 project_id,
3395 query: query.to_string(),
3396 });
3397 cx.spawn_weak(|this, cx| async move {
3398 let response = request.await?;
3399 let mut symbols = Vec::new();
3400 if let Some(this) = this.upgrade(&cx) {
3401 let new_symbols = this.read_with(&cx, |this, _| {
3402 let mut new_symbols = Vec::new();
3403 for symbol in response.symbols.into_iter() {
3404 new_symbols.push(this.deserialize_symbol(symbol));
3405 }
3406 new_symbols
3407 });
3408 for new_symbol in new_symbols {
3409 if let Some(new_symbol) = new_symbol.await.ok() {
3410 symbols.push(new_symbol);
3411 }
3412 }
3413 }
3414 Ok(symbols)
3415 })
3416 } else {
3417 Task::ready(Ok(Default::default()))
3418 }
3419 }
3420
3421 pub fn open_buffer_for_symbol(
3422 &mut self,
3423 symbol: &Symbol,
3424 cx: &mut ModelContext<Self>,
3425 ) -> Task<Result<ModelHandle<Buffer>>> {
3426 if self.is_local() {
3427 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3428 symbol.source_worktree_id,
3429 symbol.language_server_name.clone(),
3430 )) {
3431 *id
3432 } else {
3433 return Task::ready(Err(anyhow!(
3434 "language server for worktree and language not found"
3435 )));
3436 };
3437
3438 let worktree_abs_path = if let Some(worktree_abs_path) = self
3439 .worktree_for_id(symbol.worktree_id, cx)
3440 .and_then(|worktree| worktree.read(cx).as_local())
3441 .map(|local_worktree| local_worktree.abs_path())
3442 {
3443 worktree_abs_path
3444 } else {
3445 return Task::ready(Err(anyhow!("worktree not found for symbol")));
3446 };
3447 let symbol_abs_path = worktree_abs_path.join(&symbol.path);
3448 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3449 uri
3450 } else {
3451 return Task::ready(Err(anyhow!("invalid symbol path")));
3452 };
3453
3454 self.open_local_buffer_via_lsp(
3455 symbol_uri,
3456 language_server_id,
3457 symbol.language_server_name.clone(),
3458 cx,
3459 )
3460 } else if let Some(project_id) = self.remote_id() {
3461 let request = self.client.request(proto::OpenBufferForSymbol {
3462 project_id,
3463 symbol: Some(serialize_symbol(symbol)),
3464 });
3465 cx.spawn(|this, mut cx| async move {
3466 let response = request.await?;
3467 let buffer = response.buffer.ok_or_else(|| anyhow!("invalid buffer"))?;
3468 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
3469 .await
3470 })
3471 } else {
3472 Task::ready(Err(anyhow!("project does not have a remote id")))
3473 }
3474 }
3475
3476 pub fn hover<T: ToPointUtf16>(
3477 &self,
3478 buffer: &ModelHandle<Buffer>,
3479 position: T,
3480 cx: &mut ModelContext<Self>,
3481 ) -> Task<Result<Option<Hover>>> {
3482 let position = position.to_point_utf16(buffer.read(cx));
3483 self.request_lsp(buffer.clone(), GetHover { position }, cx)
3484 }
3485
3486 pub fn completions<T: ToPointUtf16>(
3487 &self,
3488 source_buffer_handle: &ModelHandle<Buffer>,
3489 position: T,
3490 cx: &mut ModelContext<Self>,
3491 ) -> Task<Result<Vec<Completion>>> {
3492 let source_buffer_handle = source_buffer_handle.clone();
3493 let source_buffer = source_buffer_handle.read(cx);
3494 let buffer_id = source_buffer.remote_id();
3495 let language = source_buffer.language().cloned();
3496 let worktree;
3497 let buffer_abs_path;
3498 if let Some(file) = File::from_dyn(source_buffer.file()) {
3499 worktree = file.worktree.clone();
3500 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3501 } else {
3502 return Task::ready(Ok(Default::default()));
3503 };
3504
3505 let position = position.to_point_utf16(source_buffer);
3506 let anchor = source_buffer.anchor_after(position);
3507
3508 if worktree.read(cx).as_local().is_some() {
3509 let buffer_abs_path = buffer_abs_path.unwrap();
3510 let lang_server =
3511 if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3512 server.clone()
3513 } else {
3514 return Task::ready(Ok(Default::default()));
3515 };
3516
3517 cx.spawn(|_, cx| async move {
3518 let completions = lang_server
3519 .request::<lsp::request::Completion>(lsp::CompletionParams {
3520 text_document_position: lsp::TextDocumentPositionParams::new(
3521 lsp::TextDocumentIdentifier::new(
3522 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3523 ),
3524 point_to_lsp(position),
3525 ),
3526 context: Default::default(),
3527 work_done_progress_params: Default::default(),
3528 partial_result_params: Default::default(),
3529 })
3530 .await
3531 .context("lsp completion request failed")?;
3532
3533 let completions = if let Some(completions) = completions {
3534 match completions {
3535 lsp::CompletionResponse::Array(completions) => completions,
3536 lsp::CompletionResponse::List(list) => list.items,
3537 }
3538 } else {
3539 Default::default()
3540 };
3541
3542 // TODO(isaac): use futures::future::join_all
3543 struct PartialCompletion {
3544 pub old_range: Range<Anchor>,
3545 pub new_text: String,
3546 pub language: Option<Arc<Language>>,
3547 pub lsp_completion: lsp::CompletionItem,
3548 }
3549
3550 let partial_completions = source_buffer_handle.read_with(&cx, |this, _| {
3551 let snapshot = this.snapshot();
3552 let clipped_position = this.clip_point_utf16(position, Bias::Left);
3553 let mut range_for_token = None;
3554 let mut partial_completions = Vec::new();
3555
3556 for lsp_completion in completions.into_iter() {
3557 // For now, we can only handle additional edits if they are returned
3558 // when resolving the completion, not if they are present initially.
3559 if lsp_completion
3560 .additional_text_edits
3561 .as_ref()
3562 .map_or(false, |edits| !edits.is_empty())
3563 {
3564 continue;
3565 }
3566 let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref()
3567 {
3568 // If the language server provides a range to overwrite, then
3569 // check that the range is valid.
3570 Some(lsp::CompletionTextEdit::Edit(edit)) => {
3571 let range = range_from_lsp(edit.range);
3572 let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3573 let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3574 if start != range.start || end != range.end {
3575 log::info!("completion out of expected range");
3576 return None;
3577 }
3578 (
3579 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3580 edit.new_text.clone(),
3581 )
3582 }
3583 // If the language server does not provide a range, then infer
3584 // the range based on the syntax tree.
3585 None => {
3586 if position != clipped_position {
3587 log::info!("completion out of expected range");
3588 return None;
3589 }
3590 let Range { start, end } = range_for_token
3591 .get_or_insert_with(|| {
3592 let offset = position.to_offset(&snapshot);
3593 let (range, kind) = snapshot.surrounding_word(offset);
3594 if kind == Some(CharKind::Word) {
3595 range
3596 } else {
3597 offset..offset
3598 }
3599 })
3600 .clone();
3601 let text = lsp_completion
3602 .insert_text
3603 .as_ref()
3604 .unwrap_or(&lsp_completion.label)
3605 .clone();
3606 (
3607 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3608 text.clone(),
3609 )
3610 }
3611 (
3612 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3613 edit.new_text.clone(),
3614 )
3615 }
3616 // If the language server does not provide a range, then infer
3617 // the range based on the syntax tree.
3618 None => {
3619 if position != clipped_position {
3620 log::info!("completion out of expected range");
3621 continue;
3622 }
3623 };
3624
3625 LineEnding::normalize(&mut new_text);
3626 Some(Completion {
3627 old_range,
3628 new_text,
3629 label: {
3630 match language.as_ref() {
3631 Some(l) => l.label_for_completion(&lsp_completion).await,
3632 None => None,
3633 }
3634 .unwrap_or_else(|| {
3635 CodeLabel::plain(
3636 lsp_completion.label.clone(),
3637 lsp_completion.filter_text.as_deref(),
3638 )
3639 let Range { start, end } = range_for_token
3640 .get_or_insert_with(|| {
3641 let offset = position.to_offset(&snapshot);
3642 let (range, kind) = snapshot.surrounding_word(offset);
3643 if kind == Some(CharKind::Word) {
3644 range
3645 } else {
3646 offset..offset
3647 }
3648 })
3649 .clone();
3650 let text = lsp_completion
3651 .insert_text
3652 .as_ref()
3653 .unwrap_or(&lsp_completion.label)
3654 .clone();
3655 (
3656 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3657 text.clone(),
3658 )
3659 }
3660 Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3661 log::info!("unsupported insert/replace completion");
3662 continue;
3663 }
3664 };
3665
3666 let partial_completion = PartialCompletion {
3667 old_range,
3668 new_text,
3669 language: language.clone(),
3670 lsp_completion,
3671 };
3672
3673 partial_completions.push(partial_completion);
3674 }
3675 partial_completions
3676 });
3677
3678 let mut result = Vec::new();
3679
3680 for pc in partial_completions.into_iter() {
3681 let label = match pc.language.as_ref() {
3682 Some(l) => l.label_for_completion(&pc.lsp_completion).await,
3683 None => None,
3684 }
3685 .unwrap_or_else(|| {
3686 CodeLabel::plain(
3687 pc.lsp_completion.label.clone(),
3688 pc.lsp_completion.filter_text.as_deref(),
3689 )
3690 });
3691
3692 let completion = Completion {
3693 old_range: pc.old_range,
3694 new_text: pc.new_text,
3695 label,
3696 lsp_completion: pc.lsp_completion,
3697 };
3698
3699 result.push(completion);
3700 }
3701
3702 Ok(result)
3703 })
3704 } else if let Some(project_id) = self.remote_id() {
3705 let rpc = self.client.clone();
3706 let message = proto::GetCompletions {
3707 project_id,
3708 buffer_id,
3709 position: Some(language::proto::serialize_anchor(&anchor)),
3710 version: serialize_version(&source_buffer.version()),
3711 };
3712 cx.spawn_weak(|_, mut cx| async move {
3713 let response = rpc.request(message).await?;
3714
3715 source_buffer_handle
3716 .update(&mut cx, |buffer, _| {
3717 buffer.wait_for_version(deserialize_version(response.version))
3718 })
3719 .await;
3720
3721 let mut completions = Vec::new();
3722 for completion in response.completions.into_iter() {
3723 completions.push(
3724 language::proto::deserialize_completion(completion, language.clone()).await,
3725 );
3726 }
3727 completions.into_iter().collect()
3728 })
3729 } else {
3730 Task::ready(Ok(Default::default()))
3731 }
3732 }
3733
3734 pub fn apply_additional_edits_for_completion(
3735 &self,
3736 buffer_handle: ModelHandle<Buffer>,
3737 completion: Completion,
3738 push_to_history: bool,
3739 cx: &mut ModelContext<Self>,
3740 ) -> Task<Result<Option<Transaction>>> {
3741 let buffer = buffer_handle.read(cx);
3742 let buffer_id = buffer.remote_id();
3743
3744 if self.is_local() {
3745 let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3746 {
3747 server.clone()
3748 } else {
3749 return Task::ready(Ok(Default::default()));
3750 };
3751
3752 cx.spawn(|this, mut cx| async move {
3753 let resolved_completion = lang_server
3754 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3755 .await?;
3756 if let Some(edits) = resolved_completion.additional_text_edits {
3757 let edits = this
3758 .update(&mut cx, |this, cx| {
3759 this.edits_from_lsp(&buffer_handle, edits, None, cx)
3760 })
3761 .await?;
3762 buffer_handle.update(&mut cx, |buffer, cx| {
3763 buffer.finalize_last_transaction();
3764 buffer.start_transaction();
3765 for (range, text) in edits {
3766 buffer.edit([(range, text)], cx);
3767 }
3768 let transaction = if buffer.end_transaction(cx).is_some() {
3769 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3770 if !push_to_history {
3771 buffer.forget_transaction(transaction.id);
3772 }
3773 Some(transaction)
3774 } else {
3775 None
3776 };
3777 Ok(transaction)
3778 })
3779 } else {
3780 Ok(None)
3781 }
3782 })
3783 } else if let Some(project_id) = self.remote_id() {
3784 let client = self.client.clone();
3785 cx.spawn(|_, mut cx| async move {
3786 let response = client
3787 .request(proto::ApplyCompletionAdditionalEdits {
3788 project_id,
3789 buffer_id,
3790 completion: Some(language::proto::serialize_completion(&completion)),
3791 })
3792 .await?;
3793
3794 if let Some(transaction) = response.transaction {
3795 let transaction = language::proto::deserialize_transaction(transaction)?;
3796 buffer_handle
3797 .update(&mut cx, |buffer, _| {
3798 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3799 })
3800 .await;
3801 if push_to_history {
3802 buffer_handle.update(&mut cx, |buffer, _| {
3803 buffer.push_transaction(transaction.clone(), Instant::now());
3804 });
3805 }
3806 Ok(Some(transaction))
3807 } else {
3808 Ok(None)
3809 }
3810 })
3811 } else {
3812 Task::ready(Err(anyhow!("project does not have a remote id")))
3813 }
3814 }
3815
3816 pub fn code_actions<T: Clone + ToOffset>(
3817 &self,
3818 buffer_handle: &ModelHandle<Buffer>,
3819 range: Range<T>,
3820 cx: &mut ModelContext<Self>,
3821 ) -> Task<Result<Vec<CodeAction>>> {
3822 let buffer_handle = buffer_handle.clone();
3823 let buffer = buffer_handle.read(cx);
3824 let snapshot = buffer.snapshot();
3825 let relevant_diagnostics = snapshot
3826 .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3827 .map(|entry| entry.to_lsp_diagnostic_stub())
3828 .collect();
3829 let buffer_id = buffer.remote_id();
3830 let worktree;
3831 let buffer_abs_path;
3832 if let Some(file) = File::from_dyn(buffer.file()) {
3833 worktree = file.worktree.clone();
3834 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3835 } else {
3836 return Task::ready(Ok(Default::default()));
3837 };
3838 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3839
3840 if worktree.read(cx).as_local().is_some() {
3841 let buffer_abs_path = buffer_abs_path.unwrap();
3842 let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3843 {
3844 server.clone()
3845 } else {
3846 return Task::ready(Ok(Default::default()));
3847 };
3848
3849 let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3850 cx.foreground().spawn(async move {
3851 if !lang_server.capabilities().code_action_provider.is_some() {
3852 return Ok(Default::default());
3853 }
3854
3855 Ok(lang_server
3856 .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3857 text_document: lsp::TextDocumentIdentifier::new(
3858 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3859 ),
3860 range: lsp_range,
3861 work_done_progress_params: Default::default(),
3862 partial_result_params: Default::default(),
3863 context: lsp::CodeActionContext {
3864 diagnostics: relevant_diagnostics,
3865 only: Some(vec![
3866 lsp::CodeActionKind::QUICKFIX,
3867 lsp::CodeActionKind::REFACTOR,
3868 lsp::CodeActionKind::REFACTOR_EXTRACT,
3869 lsp::CodeActionKind::SOURCE,
3870 ]),
3871 },
3872 })
3873 .await?
3874 .unwrap_or_default()
3875 .into_iter()
3876 .filter_map(|entry| {
3877 if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3878 Some(CodeAction {
3879 range: range.clone(),
3880 lsp_action,
3881 })
3882 } else {
3883 None
3884 }
3885 })
3886 .collect())
3887 })
3888 } else if let Some(project_id) = self.remote_id() {
3889 let rpc = self.client.clone();
3890 let version = buffer.version();
3891 cx.spawn_weak(|_, mut cx| async move {
3892 let response = rpc
3893 .request(proto::GetCodeActions {
3894 project_id,
3895 buffer_id,
3896 start: Some(language::proto::serialize_anchor(&range.start)),
3897 end: Some(language::proto::serialize_anchor(&range.end)),
3898 version: serialize_version(&version),
3899 })
3900 .await?;
3901
3902 buffer_handle
3903 .update(&mut cx, |buffer, _| {
3904 buffer.wait_for_version(deserialize_version(response.version))
3905 })
3906 .await;
3907
3908 response
3909 .actions
3910 .into_iter()
3911 .map(language::proto::deserialize_code_action)
3912 .collect()
3913 })
3914 } else {
3915 Task::ready(Ok(Default::default()))
3916 }
3917 }
3918
3919 pub fn apply_code_action(
3920 &self,
3921 buffer_handle: ModelHandle<Buffer>,
3922 mut action: CodeAction,
3923 push_to_history: bool,
3924 cx: &mut ModelContext<Self>,
3925 ) -> Task<Result<ProjectTransaction>> {
3926 if self.is_local() {
3927 let buffer = buffer_handle.read(cx);
3928 let (lsp_adapter, lang_server) =
3929 if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3930 (adapter.clone(), server.clone())
3931 } else {
3932 return Task::ready(Ok(Default::default()));
3933 };
3934 let range = action.range.to_point_utf16(buffer);
3935
3936 cx.spawn(|this, mut cx| async move {
3937 if let Some(lsp_range) = action
3938 .lsp_action
3939 .data
3940 .as_mut()
3941 .and_then(|d| d.get_mut("codeActionParams"))
3942 .and_then(|d| d.get_mut("range"))
3943 {
3944 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3945 action.lsp_action = lang_server
3946 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3947 .await?;
3948 } else {
3949 let actions = this
3950 .update(&mut cx, |this, cx| {
3951 this.code_actions(&buffer_handle, action.range, cx)
3952 })
3953 .await?;
3954 action.lsp_action = actions
3955 .into_iter()
3956 .find(|a| a.lsp_action.title == action.lsp_action.title)
3957 .ok_or_else(|| anyhow!("code action is outdated"))?
3958 .lsp_action;
3959 }
3960
3961 if let Some(edit) = action.lsp_action.edit {
3962 Self::deserialize_workspace_edit(
3963 this,
3964 edit,
3965 push_to_history,
3966 lsp_adapter.clone(),
3967 lang_server.clone(),
3968 &mut cx,
3969 )
3970 .await
3971 } else if let Some(command) = action.lsp_action.command {
3972 this.update(&mut cx, |this, _| {
3973 this.last_workspace_edits_by_language_server
3974 .remove(&lang_server.server_id());
3975 });
3976 lang_server
3977 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3978 command: command.command,
3979 arguments: command.arguments.unwrap_or_default(),
3980 ..Default::default()
3981 })
3982 .await?;
3983 Ok(this.update(&mut cx, |this, _| {
3984 this.last_workspace_edits_by_language_server
3985 .remove(&lang_server.server_id())
3986 .unwrap_or_default()
3987 }))
3988 } else {
3989 Ok(ProjectTransaction::default())
3990 }
3991 })
3992 } else if let Some(project_id) = self.remote_id() {
3993 let client = self.client.clone();
3994 let request = proto::ApplyCodeAction {
3995 project_id,
3996 buffer_id: buffer_handle.read(cx).remote_id(),
3997 action: Some(language::proto::serialize_code_action(&action)),
3998 };
3999 cx.spawn(|this, mut cx| async move {
4000 let response = client
4001 .request(request)
4002 .await?
4003 .transaction
4004 .ok_or_else(|| anyhow!("missing transaction"))?;
4005 this.update(&mut cx, |this, cx| {
4006 this.deserialize_project_transaction(response, push_to_history, cx)
4007 })
4008 .await
4009 })
4010 } else {
4011 Task::ready(Err(anyhow!("project does not have a remote id")))
4012 }
4013 }
4014
4015 async fn deserialize_workspace_edit(
4016 this: ModelHandle<Self>,
4017 edit: lsp::WorkspaceEdit,
4018 push_to_history: bool,
4019 lsp_adapter: Arc<dyn LspAdapter>,
4020 language_server: Arc<LanguageServer>,
4021 cx: &mut AsyncAppContext,
4022 ) -> Result<ProjectTransaction> {
4023 let fs = this.read_with(cx, |this, _| this.fs.clone());
4024 let mut operations = Vec::new();
4025 if let Some(document_changes) = edit.document_changes {
4026 match document_changes {
4027 lsp::DocumentChanges::Edits(edits) => {
4028 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
4029 }
4030 lsp::DocumentChanges::Operations(ops) => operations = ops,
4031 }
4032 } else if let Some(changes) = edit.changes {
4033 operations.extend(changes.into_iter().map(|(uri, edits)| {
4034 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
4035 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
4036 uri,
4037 version: None,
4038 },
4039 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
4040 })
4041 }));
4042 }
4043
4044 let mut project_transaction = ProjectTransaction::default();
4045 for operation in operations {
4046 match operation {
4047 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4048 let abs_path = op
4049 .uri
4050 .to_file_path()
4051 .map_err(|_| anyhow!("can't convert URI to path"))?;
4052
4053 if let Some(parent_path) = abs_path.parent() {
4054 fs.create_dir(parent_path).await?;
4055 }
4056 if abs_path.ends_with("/") {
4057 fs.create_dir(&abs_path).await?;
4058 } else {
4059 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4060 .await?;
4061 }
4062 }
4063 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4064 let source_abs_path = op
4065 .old_uri
4066 .to_file_path()
4067 .map_err(|_| anyhow!("can't convert URI to path"))?;
4068 let target_abs_path = op
4069 .new_uri
4070 .to_file_path()
4071 .map_err(|_| anyhow!("can't convert URI to path"))?;
4072 fs.rename(
4073 &source_abs_path,
4074 &target_abs_path,
4075 op.options.map(Into::into).unwrap_or_default(),
4076 )
4077 .await?;
4078 }
4079 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4080 let abs_path = op
4081 .uri
4082 .to_file_path()
4083 .map_err(|_| anyhow!("can't convert URI to path"))?;
4084 let options = op.options.map(Into::into).unwrap_or_default();
4085 if abs_path.ends_with("/") {
4086 fs.remove_dir(&abs_path, options).await?;
4087 } else {
4088 fs.remove_file(&abs_path, options).await?;
4089 }
4090 }
4091 lsp::DocumentChangeOperation::Edit(op) => {
4092 let buffer_to_edit = this
4093 .update(cx, |this, cx| {
4094 this.open_local_buffer_via_lsp(
4095 op.text_document.uri,
4096 language_server.server_id(),
4097 lsp_adapter.name(),
4098 cx,
4099 )
4100 })
4101 .await?;
4102
4103 let edits = this
4104 .update(cx, |this, cx| {
4105 let edits = op.edits.into_iter().map(|edit| match edit {
4106 lsp::OneOf::Left(edit) => edit,
4107 lsp::OneOf::Right(edit) => edit.text_edit,
4108 });
4109 this.edits_from_lsp(
4110 &buffer_to_edit,
4111 edits,
4112 op.text_document.version,
4113 cx,
4114 )
4115 })
4116 .await?;
4117
4118 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4119 buffer.finalize_last_transaction();
4120 buffer.start_transaction();
4121 for (range, text) in edits {
4122 buffer.edit([(range, text)], cx);
4123 }
4124 let transaction = if buffer.end_transaction(cx).is_some() {
4125 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4126 if !push_to_history {
4127 buffer.forget_transaction(transaction.id);
4128 }
4129 Some(transaction)
4130 } else {
4131 None
4132 };
4133
4134 transaction
4135 });
4136 if let Some(transaction) = transaction {
4137 project_transaction.0.insert(buffer_to_edit, transaction);
4138 }
4139 }
4140 }
4141 }
4142
4143 Ok(project_transaction)
4144 }
4145
4146 pub fn prepare_rename<T: ToPointUtf16>(
4147 &self,
4148 buffer: ModelHandle<Buffer>,
4149 position: T,
4150 cx: &mut ModelContext<Self>,
4151 ) -> Task<Result<Option<Range<Anchor>>>> {
4152 let position = position.to_point_utf16(buffer.read(cx));
4153 self.request_lsp(buffer, PrepareRename { position }, cx)
4154 }
4155
4156 pub fn perform_rename<T: ToPointUtf16>(
4157 &self,
4158 buffer: ModelHandle<Buffer>,
4159 position: T,
4160 new_name: String,
4161 push_to_history: bool,
4162 cx: &mut ModelContext<Self>,
4163 ) -> Task<Result<ProjectTransaction>> {
4164 let position = position.to_point_utf16(buffer.read(cx));
4165 self.request_lsp(
4166 buffer,
4167 PerformRename {
4168 position,
4169 new_name,
4170 push_to_history,
4171 },
4172 cx,
4173 )
4174 }
4175
4176 pub fn search(
4177 &self,
4178 query: SearchQuery,
4179 cx: &mut ModelContext<Self>,
4180 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4181 if self.is_local() {
4182 let snapshots = self
4183 .visible_worktrees(cx)
4184 .filter_map(|tree| {
4185 let tree = tree.read(cx).as_local()?;
4186 Some(tree.snapshot())
4187 })
4188 .collect::<Vec<_>>();
4189
4190 let background = cx.background().clone();
4191 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4192 if path_count == 0 {
4193 return Task::ready(Ok(Default::default()));
4194 }
4195 let workers = background.num_cpus().min(path_count);
4196 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4197 cx.background()
4198 .spawn({
4199 let fs = self.fs.clone();
4200 let background = cx.background().clone();
4201 let query = query.clone();
4202 async move {
4203 let fs = &fs;
4204 let query = &query;
4205 let matching_paths_tx = &matching_paths_tx;
4206 let paths_per_worker = (path_count + workers - 1) / workers;
4207 let snapshots = &snapshots;
4208 background
4209 .scoped(|scope| {
4210 for worker_ix in 0..workers {
4211 let worker_start_ix = worker_ix * paths_per_worker;
4212 let worker_end_ix = worker_start_ix + paths_per_worker;
4213 scope.spawn(async move {
4214 let mut snapshot_start_ix = 0;
4215 let mut abs_path = PathBuf::new();
4216 for snapshot in snapshots {
4217 let snapshot_end_ix =
4218 snapshot_start_ix + snapshot.visible_file_count();
4219 if worker_end_ix <= snapshot_start_ix {
4220 break;
4221 } else if worker_start_ix > snapshot_end_ix {
4222 snapshot_start_ix = snapshot_end_ix;
4223 continue;
4224 } else {
4225 let start_in_snapshot = worker_start_ix
4226 .saturating_sub(snapshot_start_ix);
4227 let end_in_snapshot =
4228 cmp::min(worker_end_ix, snapshot_end_ix)
4229 - snapshot_start_ix;
4230
4231 for entry in snapshot
4232 .files(false, start_in_snapshot)
4233 .take(end_in_snapshot - start_in_snapshot)
4234 {
4235 if matching_paths_tx.is_closed() {
4236 break;
4237 }
4238
4239 abs_path.clear();
4240 abs_path.push(&snapshot.abs_path());
4241 abs_path.push(&entry.path);
4242 let matches = if let Some(file) =
4243 fs.open_sync(&abs_path).await.log_err()
4244 {
4245 query.detect(file).unwrap_or(false)
4246 } else {
4247 false
4248 };
4249
4250 if matches {
4251 let project_path =
4252 (snapshot.id(), entry.path.clone());
4253 if matching_paths_tx
4254 .send(project_path)
4255 .await
4256 .is_err()
4257 {
4258 break;
4259 }
4260 }
4261 }
4262
4263 snapshot_start_ix = snapshot_end_ix;
4264 }
4265 }
4266 });
4267 }
4268 })
4269 .await;
4270 }
4271 })
4272 .detach();
4273
4274 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4275 let open_buffers = self
4276 .opened_buffers
4277 .values()
4278 .filter_map(|b| b.upgrade(cx))
4279 .collect::<HashSet<_>>();
4280 cx.spawn(|this, cx| async move {
4281 for buffer in &open_buffers {
4282 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4283 buffers_tx.send((buffer.clone(), snapshot)).await?;
4284 }
4285
4286 let open_buffers = Rc::new(RefCell::new(open_buffers));
4287 while let Some(project_path) = matching_paths_rx.next().await {
4288 if buffers_tx.is_closed() {
4289 break;
4290 }
4291
4292 let this = this.clone();
4293 let open_buffers = open_buffers.clone();
4294 let buffers_tx = buffers_tx.clone();
4295 cx.spawn(|mut cx| async move {
4296 if let Some(buffer) = this
4297 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4298 .await
4299 .log_err()
4300 {
4301 if open_buffers.borrow_mut().insert(buffer.clone()) {
4302 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4303 buffers_tx.send((buffer, snapshot)).await?;
4304 }
4305 }
4306
4307 Ok::<_, anyhow::Error>(())
4308 })
4309 .detach();
4310 }
4311
4312 Ok::<_, anyhow::Error>(())
4313 })
4314 .detach_and_log_err(cx);
4315
4316 let background = cx.background().clone();
4317 cx.background().spawn(async move {
4318 let query = &query;
4319 let mut matched_buffers = Vec::new();
4320 for _ in 0..workers {
4321 matched_buffers.push(HashMap::default());
4322 }
4323 background
4324 .scoped(|scope| {
4325 for worker_matched_buffers in matched_buffers.iter_mut() {
4326 let mut buffers_rx = buffers_rx.clone();
4327 scope.spawn(async move {
4328 while let Some((buffer, snapshot)) = buffers_rx.next().await {
4329 let buffer_matches = query
4330 .search(snapshot.as_rope())
4331 .await
4332 .iter()
4333 .map(|range| {
4334 snapshot.anchor_before(range.start)
4335 ..snapshot.anchor_after(range.end)
4336 })
4337 .collect::<Vec<_>>();
4338 if !buffer_matches.is_empty() {
4339 worker_matched_buffers
4340 .insert(buffer.clone(), buffer_matches);
4341 }
4342 }
4343 });
4344 }
4345 })
4346 .await;
4347 Ok(matched_buffers.into_iter().flatten().collect())
4348 })
4349 } else if let Some(project_id) = self.remote_id() {
4350 let request = self.client.request(query.to_proto(project_id));
4351 cx.spawn(|this, mut cx| async move {
4352 let response = request.await?;
4353 let mut result = HashMap::default();
4354 for location in response.locations {
4355 let buffer = location.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
4356 let target_buffer = this
4357 .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
4358 .await?;
4359 let start = location
4360 .start
4361 .and_then(deserialize_anchor)
4362 .ok_or_else(|| anyhow!("missing target start"))?;
4363 let end = location
4364 .end
4365 .and_then(deserialize_anchor)
4366 .ok_or_else(|| anyhow!("missing target end"))?;
4367 result
4368 .entry(target_buffer)
4369 .or_insert(Vec::new())
4370 .push(start..end)
4371 }
4372 Ok(result)
4373 })
4374 } else {
4375 Task::ready(Ok(Default::default()))
4376 }
4377 }
4378
4379 fn request_lsp<R: LspCommand>(
4380 &self,
4381 buffer_handle: ModelHandle<Buffer>,
4382 request: R,
4383 cx: &mut ModelContext<Self>,
4384 ) -> Task<Result<R::Response>>
4385 where
4386 <R::LspRequest as lsp::request::Request>::Result: Send,
4387 {
4388 let buffer = buffer_handle.read(cx);
4389 if self.is_local() {
4390 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4391 if let Some((file, language_server)) = file.zip(
4392 self.language_server_for_buffer(buffer, cx)
4393 .map(|(_, server)| server.clone()),
4394 ) {
4395 let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4396 return cx.spawn(|this, cx| async move {
4397 if !request.check_capabilities(&language_server.capabilities()) {
4398 return Ok(Default::default());
4399 }
4400
4401 let response = language_server
4402 .request::<R::LspRequest>(lsp_params)
4403 .await
4404 .context("lsp request failed")?;
4405 request
4406 .response_from_lsp(response, this, buffer_handle, cx)
4407 .await
4408 });
4409 }
4410 } else if let Some(project_id) = self.remote_id() {
4411 let rpc = self.client.clone();
4412 let message = request.to_proto(project_id, buffer);
4413 return cx.spawn(|this, cx| async move {
4414 let response = rpc.request(message).await?;
4415 request
4416 .response_from_proto(response, this, buffer_handle, cx)
4417 .await
4418 });
4419 }
4420 Task::ready(Ok(Default::default()))
4421 }
4422
4423 pub fn find_or_create_local_worktree(
4424 &mut self,
4425 abs_path: impl AsRef<Path>,
4426 visible: bool,
4427 cx: &mut ModelContext<Self>,
4428 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4429 let abs_path = abs_path.as_ref();
4430 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4431 Task::ready(Ok((tree.clone(), relative_path.into())))
4432 } else {
4433 let worktree = self.create_local_worktree(abs_path, visible, cx);
4434 cx.foreground()
4435 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4436 }
4437 }
4438
4439 pub fn find_local_worktree(
4440 &self,
4441 abs_path: &Path,
4442 cx: &AppContext,
4443 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4444 for tree in &self.worktrees {
4445 if let Some(tree) = tree.upgrade(cx) {
4446 if let Some(relative_path) = tree
4447 .read(cx)
4448 .as_local()
4449 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4450 {
4451 return Some((tree.clone(), relative_path.into()));
4452 }
4453 }
4454 }
4455 None
4456 }
4457
4458 pub fn is_shared(&self) -> bool {
4459 match &self.client_state {
4460 ProjectClientState::Local { is_shared, .. } => *is_shared,
4461 ProjectClientState::Remote { .. } => false,
4462 }
4463 }
4464
4465 fn create_local_worktree(
4466 &mut self,
4467 abs_path: impl AsRef<Path>,
4468 visible: bool,
4469 cx: &mut ModelContext<Self>,
4470 ) -> Task<Result<ModelHandle<Worktree>>> {
4471 let fs = self.fs.clone();
4472 let client = self.client.clone();
4473 let next_entry_id = self.next_entry_id.clone();
4474 let path: Arc<Path> = abs_path.as_ref().into();
4475 let task = self
4476 .loading_local_worktrees
4477 .entry(path.clone())
4478 .or_insert_with(|| {
4479 cx.spawn(|project, mut cx| {
4480 async move {
4481 let worktree = Worktree::local(
4482 client.clone(),
4483 path.clone(),
4484 visible,
4485 fs,
4486 next_entry_id,
4487 &mut cx,
4488 )
4489 .await;
4490 project.update(&mut cx, |project, _| {
4491 project.loading_local_worktrees.remove(&path);
4492 });
4493 let worktree = worktree?;
4494
4495 let project_id = project.update(&mut cx, |project, cx| {
4496 project.add_worktree(&worktree, cx);
4497 project.shared_remote_id()
4498 });
4499
4500 if let Some(project_id) = project_id {
4501 worktree
4502 .update(&mut cx, |worktree, cx| {
4503 worktree.as_local_mut().unwrap().share(project_id, cx)
4504 })
4505 .await
4506 .log_err();
4507 }
4508
4509 Ok(worktree)
4510 }
4511 .map_err(|err| Arc::new(err))
4512 })
4513 .shared()
4514 })
4515 .clone();
4516 cx.foreground().spawn(async move {
4517 match task.await {
4518 Ok(worktree) => Ok(worktree),
4519 Err(err) => Err(anyhow!("{}", err)),
4520 }
4521 })
4522 }
4523
4524 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4525 self.worktrees.retain(|worktree| {
4526 if let Some(worktree) = worktree.upgrade(cx) {
4527 let id = worktree.read(cx).id();
4528 if id == id_to_remove {
4529 cx.emit(Event::WorktreeRemoved(id));
4530 false
4531 } else {
4532 true
4533 }
4534 } else {
4535 false
4536 }
4537 });
4538 self.metadata_changed(true, cx);
4539 cx.notify();
4540 }
4541
4542 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4543 cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
4544 if worktree.read(cx).is_local() {
4545 cx.subscribe(&worktree, |this, worktree, _, cx| {
4546 this.update_local_worktree_buffers(worktree, cx);
4547 })
4548 .detach();
4549 }
4550
4551 let push_strong_handle = {
4552 let worktree = worktree.read(cx);
4553 self.is_shared() || worktree.is_visible() || worktree.is_remote()
4554 };
4555 if push_strong_handle {
4556 self.worktrees
4557 .push(WorktreeHandle::Strong(worktree.clone()));
4558 } else {
4559 self.worktrees
4560 .push(WorktreeHandle::Weak(worktree.downgrade()));
4561 }
4562
4563 self.metadata_changed(true, cx);
4564 cx.observe_release(&worktree, |this, worktree, cx| {
4565 this.remove_worktree(worktree.id(), cx);
4566 cx.notify();
4567 })
4568 .detach();
4569
4570 cx.emit(Event::WorktreeAdded);
4571 cx.notify();
4572 }
4573
4574 fn update_local_worktree_buffers(
4575 &mut self,
4576 worktree_handle: ModelHandle<Worktree>,
4577 cx: &mut ModelContext<Self>,
4578 ) {
4579 let snapshot = worktree_handle.read(cx).snapshot();
4580 let mut buffers_to_delete = Vec::new();
4581 let mut renamed_buffers = Vec::new();
4582 for (buffer_id, buffer) in &self.opened_buffers {
4583 if let Some(buffer) = buffer.upgrade(cx) {
4584 buffer.update(cx, |buffer, cx| {
4585 if let Some(old_file) = File::from_dyn(buffer.file()) {
4586 if old_file.worktree != worktree_handle {
4587 return;
4588 }
4589
4590 let new_file = if let Some(entry) = old_file
4591 .entry_id
4592 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
4593 {
4594 File {
4595 is_local: true,
4596 entry_id: Some(entry.id),
4597 mtime: entry.mtime,
4598 path: entry.path.clone(),
4599 worktree: worktree_handle.clone(),
4600 }
4601 } else if let Some(entry) =
4602 snapshot.entry_for_path(old_file.path().as_ref())
4603 {
4604 File {
4605 is_local: true,
4606 entry_id: Some(entry.id),
4607 mtime: entry.mtime,
4608 path: entry.path.clone(),
4609 worktree: worktree_handle.clone(),
4610 }
4611 } else {
4612 File {
4613 is_local: true,
4614 entry_id: None,
4615 path: old_file.path().clone(),
4616 mtime: old_file.mtime(),
4617 worktree: worktree_handle.clone(),
4618 }
4619 };
4620
4621 let old_path = old_file.abs_path(cx);
4622 if new_file.abs_path(cx) != old_path {
4623 renamed_buffers.push((cx.handle(), old_path));
4624 }
4625
4626 if let Some(project_id) = self.shared_remote_id() {
4627 self.client
4628 .send(proto::UpdateBufferFile {
4629 project_id,
4630 buffer_id: *buffer_id as u64,
4631 file: Some(new_file.to_proto()),
4632 })
4633 .log_err();
4634 }
4635 buffer.file_updated(Arc::new(new_file), cx).detach();
4636 }
4637 });
4638 } else {
4639 buffers_to_delete.push(*buffer_id);
4640 }
4641 }
4642
4643 for buffer_id in buffers_to_delete {
4644 self.opened_buffers.remove(&buffer_id);
4645 }
4646
4647 for (buffer, old_path) in renamed_buffers {
4648 self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4649 self.assign_language_to_buffer(&buffer, cx);
4650 self.register_buffer_with_language_server(&buffer, cx).await;
4651 }
4652 }
4653
4654 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4655 let new_active_entry = entry.and_then(|project_path| {
4656 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4657 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4658 Some(entry.id)
4659 });
4660 if new_active_entry != self.active_entry {
4661 self.active_entry = new_active_entry;
4662 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4663 }
4664 }
4665
4666 pub fn language_servers_running_disk_based_diagnostics<'a>(
4667 &'a self,
4668 ) -> impl 'a + Iterator<Item = usize> {
4669 self.language_server_statuses
4670 .iter()
4671 .filter_map(|(id, status)| {
4672 if status.has_pending_diagnostic_updates {
4673 Some(*id)
4674 } else {
4675 None
4676 }
4677 })
4678 }
4679
4680 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4681 let mut summary = DiagnosticSummary::default();
4682 for (_, path_summary) in self.diagnostic_summaries(cx) {
4683 summary.error_count += path_summary.error_count;
4684 summary.warning_count += path_summary.warning_count;
4685 }
4686 summary
4687 }
4688
4689 pub fn diagnostic_summaries<'a>(
4690 &'a self,
4691 cx: &'a AppContext,
4692 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4693 self.visible_worktrees(cx).flat_map(move |worktree| {
4694 let worktree = worktree.read(cx);
4695 let worktree_id = worktree.id();
4696 worktree
4697 .diagnostic_summaries()
4698 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4699 })
4700 }
4701
4702 pub fn disk_based_diagnostics_started(
4703 &mut self,
4704 language_server_id: usize,
4705 cx: &mut ModelContext<Self>,
4706 ) {
4707 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4708 }
4709
4710 pub fn disk_based_diagnostics_finished(
4711 &mut self,
4712 language_server_id: usize,
4713 cx: &mut ModelContext<Self>,
4714 ) {
4715 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4716 }
4717
4718 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4719 self.active_entry
4720 }
4721
4722 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<ProjectEntryId> {
4723 self.worktree_for_id(path.worktree_id, cx)?
4724 .read(cx)
4725 .entry_for_path(&path.path)
4726 .map(|entry| entry.id)
4727 }
4728
4729 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4730 let worktree = self.worktree_for_entry(entry_id, cx)?;
4731 let worktree = worktree.read(cx);
4732 let worktree_id = worktree.id();
4733 let path = worktree.entry_for_id(entry_id)?.path.clone();
4734 Some(ProjectPath { worktree_id, path })
4735 }
4736
4737 // RPC message handlers
4738
4739 async fn handle_request_join_project(
4740 this: ModelHandle<Self>,
4741 message: TypedEnvelope<proto::RequestJoinProject>,
4742 _: Arc<Client>,
4743 mut cx: AsyncAppContext,
4744 ) -> Result<()> {
4745 let user_id = message.payload.requester_id;
4746 if this.read_with(&cx, |project, _| {
4747 project.collaborators.values().any(|c| c.user.id == user_id)
4748 }) {
4749 this.update(&mut cx, |this, cx| {
4750 this.respond_to_join_request(user_id, true, cx)
4751 });
4752 } else {
4753 let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4754 let user = user_store
4755 .update(&mut cx, |store, cx| store.fetch_user(user_id, cx))
4756 .await?;
4757 this.update(&mut cx, |_, cx| cx.emit(Event::ContactRequestedJoin(user)));
4758 }
4759 Ok(())
4760 }
4761
4762 async fn handle_unregister_project(
4763 this: ModelHandle<Self>,
4764 _: TypedEnvelope<proto::UnregisterProject>,
4765 _: Arc<Client>,
4766 mut cx: AsyncAppContext,
4767 ) -> Result<()> {
4768 this.update(&mut cx, |this, cx| this.removed_from_project(cx));
4769 Ok(())
4770 }
4771
4772 async fn handle_project_unshared(
4773 this: ModelHandle<Self>,
4774 _: TypedEnvelope<proto::ProjectUnshared>,
4775 _: Arc<Client>,
4776 mut cx: AsyncAppContext,
4777 ) -> Result<()> {
4778 this.update(&mut cx, |this, cx| this.unshared(cx));
4779 Ok(())
4780 }
4781
4782 async fn handle_add_collaborator(
4783 this: ModelHandle<Self>,
4784 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4785 _: Arc<Client>,
4786 mut cx: AsyncAppContext,
4787 ) -> Result<()> {
4788 let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4789 let collaborator = envelope
4790 .payload
4791 .collaborator
4792 .take()
4793 .ok_or_else(|| anyhow!("empty collaborator"))?;
4794
4795 let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
4796 this.update(&mut cx, |this, cx| {
4797 this.collaborators
4798 .insert(collaborator.peer_id, collaborator);
4799 cx.notify();
4800 });
4801
4802 Ok(())
4803 }
4804
4805 async fn handle_remove_collaborator(
4806 this: ModelHandle<Self>,
4807 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4808 _: Arc<Client>,
4809 mut cx: AsyncAppContext,
4810 ) -> Result<()> {
4811 this.update(&mut cx, |this, cx| {
4812 let peer_id = PeerId(envelope.payload.peer_id);
4813 let replica_id = this
4814 .collaborators
4815 .remove(&peer_id)
4816 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4817 .replica_id;
4818 for (_, buffer) in &this.opened_buffers {
4819 if let Some(buffer) = buffer.upgrade(cx) {
4820 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4821 }
4822 }
4823
4824 cx.emit(Event::CollaboratorLeft(peer_id));
4825 cx.notify();
4826 Ok(())
4827 })
4828 }
4829
4830 async fn handle_join_project_request_cancelled(
4831 this: ModelHandle<Self>,
4832 envelope: TypedEnvelope<proto::JoinProjectRequestCancelled>,
4833 _: Arc<Client>,
4834 mut cx: AsyncAppContext,
4835 ) -> Result<()> {
4836 let user = this
4837 .update(&mut cx, |this, cx| {
4838 this.user_store.update(cx, |user_store, cx| {
4839 user_store.fetch_user(envelope.payload.requester_id, cx)
4840 })
4841 })
4842 .await?;
4843
4844 this.update(&mut cx, |_, cx| {
4845 cx.emit(Event::ContactCancelledJoinRequest(user));
4846 });
4847
4848 Ok(())
4849 }
4850
4851 async fn handle_update_project(
4852 this: ModelHandle<Self>,
4853 envelope: TypedEnvelope<proto::UpdateProject>,
4854 client: Arc<Client>,
4855 mut cx: AsyncAppContext,
4856 ) -> Result<()> {
4857 this.update(&mut cx, |this, cx| {
4858 let replica_id = this.replica_id();
4859 let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4860
4861 let mut old_worktrees_by_id = this
4862 .worktrees
4863 .drain(..)
4864 .filter_map(|worktree| {
4865 let worktree = worktree.upgrade(cx)?;
4866 Some((worktree.read(cx).id(), worktree))
4867 })
4868 .collect::<HashMap<_, _>>();
4869
4870 for worktree in envelope.payload.worktrees {
4871 if let Some(old_worktree) =
4872 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4873 {
4874 this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4875 } else {
4876 let worktree =
4877 Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4878 this.add_worktree(&worktree, cx);
4879 }
4880 }
4881
4882 this.metadata_changed(true, cx);
4883 for (id, _) in old_worktrees_by_id {
4884 cx.emit(Event::WorktreeRemoved(id));
4885 }
4886
4887 Ok(())
4888 })
4889 }
4890
4891 async fn handle_update_worktree(
4892 this: ModelHandle<Self>,
4893 envelope: TypedEnvelope<proto::UpdateWorktree>,
4894 _: Arc<Client>,
4895 mut cx: AsyncAppContext,
4896 ) -> Result<()> {
4897 this.update(&mut cx, |this, cx| {
4898 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4899 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4900 worktree.update(cx, |worktree, _| {
4901 let worktree = worktree.as_remote_mut().unwrap();
4902 worktree.update_from_remote(envelope.payload);
4903 });
4904 }
4905 Ok(())
4906 })
4907 }
4908
4909 async fn handle_create_project_entry(
4910 this: ModelHandle<Self>,
4911 envelope: TypedEnvelope<proto::CreateProjectEntry>,
4912 _: Arc<Client>,
4913 mut cx: AsyncAppContext,
4914 ) -> Result<proto::ProjectEntryResponse> {
4915 let worktree = this.update(&mut cx, |this, cx| {
4916 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4917 this.worktree_for_id(worktree_id, cx)
4918 .ok_or_else(|| anyhow!("worktree not found"))
4919 })?;
4920 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4921 let entry = worktree
4922 .update(&mut cx, |worktree, cx| {
4923 let worktree = worktree.as_local_mut().unwrap();
4924 let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
4925 worktree.create_entry(path, envelope.payload.is_directory, cx)
4926 })
4927 .await?;
4928 Ok(proto::ProjectEntryResponse {
4929 entry: Some((&entry).into()),
4930 worktree_scan_id: worktree_scan_id as u64,
4931 })
4932 }
4933
4934 async fn handle_rename_project_entry(
4935 this: ModelHandle<Self>,
4936 envelope: TypedEnvelope<proto::RenameProjectEntry>,
4937 _: Arc<Client>,
4938 mut cx: AsyncAppContext,
4939 ) -> Result<proto::ProjectEntryResponse> {
4940 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4941 let worktree = this.read_with(&cx, |this, cx| {
4942 this.worktree_for_entry(entry_id, cx)
4943 .ok_or_else(|| anyhow!("worktree not found"))
4944 })?;
4945 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4946 let entry = worktree
4947 .update(&mut cx, |worktree, cx| {
4948 let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4949 worktree
4950 .as_local_mut()
4951 .unwrap()
4952 .rename_entry(entry_id, new_path, cx)
4953 .ok_or_else(|| anyhow!("invalid entry"))
4954 })?
4955 .await?;
4956 Ok(proto::ProjectEntryResponse {
4957 entry: Some((&entry).into()),
4958 worktree_scan_id: worktree_scan_id as u64,
4959 })
4960 }
4961
4962 async fn handle_copy_project_entry(
4963 this: ModelHandle<Self>,
4964 envelope: TypedEnvelope<proto::CopyProjectEntry>,
4965 _: Arc<Client>,
4966 mut cx: AsyncAppContext,
4967 ) -> Result<proto::ProjectEntryResponse> {
4968 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4969 let worktree = this.read_with(&cx, |this, cx| {
4970 this.worktree_for_entry(entry_id, cx)
4971 .ok_or_else(|| anyhow!("worktree not found"))
4972 })?;
4973 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4974 let entry = worktree
4975 .update(&mut cx, |worktree, cx| {
4976 let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4977 worktree
4978 .as_local_mut()
4979 .unwrap()
4980 .copy_entry(entry_id, new_path, cx)
4981 .ok_or_else(|| anyhow!("invalid entry"))
4982 })?
4983 .await?;
4984 Ok(proto::ProjectEntryResponse {
4985 entry: Some((&entry).into()),
4986 worktree_scan_id: worktree_scan_id as u64,
4987 })
4988 }
4989
4990 async fn handle_delete_project_entry(
4991 this: ModelHandle<Self>,
4992 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4993 _: Arc<Client>,
4994 mut cx: AsyncAppContext,
4995 ) -> Result<proto::ProjectEntryResponse> {
4996 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4997 let worktree = this.read_with(&cx, |this, cx| {
4998 this.worktree_for_entry(entry_id, cx)
4999 .ok_or_else(|| anyhow!("worktree not found"))
5000 })?;
5001 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5002 worktree
5003 .update(&mut cx, |worktree, cx| {
5004 worktree
5005 .as_local_mut()
5006 .unwrap()
5007 .delete_entry(entry_id, cx)
5008 .ok_or_else(|| anyhow!("invalid entry"))
5009 })?
5010 .await?;
5011 Ok(proto::ProjectEntryResponse {
5012 entry: None,
5013 worktree_scan_id: worktree_scan_id as u64,
5014 })
5015 }
5016
5017 async fn handle_update_diagnostic_summary(
5018 this: ModelHandle<Self>,
5019 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
5020 _: Arc<Client>,
5021 mut cx: AsyncAppContext,
5022 ) -> Result<()> {
5023 this.update(&mut cx, |this, cx| {
5024 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5025 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5026 if let Some(summary) = envelope.payload.summary {
5027 let project_path = ProjectPath {
5028 worktree_id,
5029 path: Path::new(&summary.path).into(),
5030 };
5031 worktree.update(cx, |worktree, _| {
5032 worktree
5033 .as_remote_mut()
5034 .unwrap()
5035 .update_diagnostic_summary(project_path.path.clone(), &summary);
5036 });
5037 cx.emit(Event::DiagnosticsUpdated {
5038 language_server_id: summary.language_server_id as usize,
5039 path: project_path,
5040 });
5041 }
5042 }
5043 Ok(())
5044 })
5045 }
5046
5047 async fn handle_start_language_server(
5048 this: ModelHandle<Self>,
5049 envelope: TypedEnvelope<proto::StartLanguageServer>,
5050 _: Arc<Client>,
5051 mut cx: AsyncAppContext,
5052 ) -> Result<()> {
5053 let server = envelope
5054 .payload
5055 .server
5056 .ok_or_else(|| anyhow!("invalid server"))?;
5057 this.update(&mut cx, |this, cx| {
5058 this.language_server_statuses.insert(
5059 server.id as usize,
5060 LanguageServerStatus {
5061 name: server.name,
5062 pending_work: Default::default(),
5063 has_pending_diagnostic_updates: false,
5064 progress_tokens: Default::default(),
5065 },
5066 );
5067 cx.notify();
5068 });
5069 Ok(())
5070 }
5071
5072 async fn handle_update_language_server(
5073 this: ModelHandle<Self>,
5074 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5075 _: Arc<Client>,
5076 mut cx: AsyncAppContext,
5077 ) -> Result<()> {
5078 let language_server_id = envelope.payload.language_server_id as usize;
5079 match envelope
5080 .payload
5081 .variant
5082 .ok_or_else(|| anyhow!("invalid variant"))?
5083 {
5084 proto::update_language_server::Variant::WorkStart(payload) => {
5085 this.update(&mut cx, |this, cx| {
5086 this.on_lsp_work_start(
5087 language_server_id,
5088 payload.token,
5089 LanguageServerProgress {
5090 message: payload.message,
5091 percentage: payload.percentage.map(|p| p as usize),
5092 last_update_at: Instant::now(),
5093 },
5094 cx,
5095 );
5096 })
5097 }
5098 proto::update_language_server::Variant::WorkProgress(payload) => {
5099 this.update(&mut cx, |this, cx| {
5100 this.on_lsp_work_progress(
5101 language_server_id,
5102 payload.token,
5103 LanguageServerProgress {
5104 message: payload.message,
5105 percentage: payload.percentage.map(|p| p as usize),
5106 last_update_at: Instant::now(),
5107 },
5108 cx,
5109 );
5110 })
5111 }
5112 proto::update_language_server::Variant::WorkEnd(payload) => {
5113 this.update(&mut cx, |this, cx| {
5114 this.on_lsp_work_end(language_server_id, payload.token, cx);
5115 })
5116 }
5117 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5118 this.update(&mut cx, |this, cx| {
5119 this.disk_based_diagnostics_started(language_server_id, cx);
5120 })
5121 }
5122 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5123 this.update(&mut cx, |this, cx| {
5124 this.disk_based_diagnostics_finished(language_server_id, cx)
5125 });
5126 }
5127 }
5128
5129 Ok(())
5130 }
5131
5132 async fn handle_update_buffer(
5133 this: ModelHandle<Self>,
5134 envelope: TypedEnvelope<proto::UpdateBuffer>,
5135 _: Arc<Client>,
5136 mut cx: AsyncAppContext,
5137 ) -> Result<()> {
5138 this.update(&mut cx, |this, cx| {
5139 let payload = envelope.payload.clone();
5140 let buffer_id = payload.buffer_id;
5141 let ops = payload
5142 .operations
5143 .into_iter()
5144 .map(|op| language::proto::deserialize_operation(op))
5145 .collect::<Result<Vec<_>, _>>()?;
5146 let is_remote = this.is_remote();
5147 match this.opened_buffers.entry(buffer_id) {
5148 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5149 OpenBuffer::Strong(buffer) => {
5150 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5151 }
5152 OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
5153 OpenBuffer::Weak(_) => {}
5154 },
5155 hash_map::Entry::Vacant(e) => {
5156 assert!(
5157 is_remote,
5158 "received buffer update from {:?}",
5159 envelope.original_sender_id
5160 );
5161 e.insert(OpenBuffer::Loading(ops));
5162 }
5163 }
5164 Ok(())
5165 })
5166 }
5167
5168 async fn handle_update_buffer_file(
5169 this: ModelHandle<Self>,
5170 envelope: TypedEnvelope<proto::UpdateBufferFile>,
5171 _: Arc<Client>,
5172 mut cx: AsyncAppContext,
5173 ) -> Result<()> {
5174 this.update(&mut cx, |this, cx| {
5175 let payload = envelope.payload.clone();
5176 let buffer_id = payload.buffer_id;
5177 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5178 let worktree = this
5179 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5180 .ok_or_else(|| anyhow!("no such worktree"))?;
5181 let file = File::from_proto(file, worktree.clone(), cx)?;
5182 let buffer = this
5183 .opened_buffers
5184 .get_mut(&buffer_id)
5185 .and_then(|b| b.upgrade(cx))
5186 .ok_or_else(|| anyhow!("no such buffer"))?;
5187 buffer.update(cx, |buffer, cx| {
5188 buffer.file_updated(Arc::new(file), cx).detach();
5189 });
5190 Ok(())
5191 })
5192 }
5193
5194 async fn handle_save_buffer(
5195 this: ModelHandle<Self>,
5196 envelope: TypedEnvelope<proto::SaveBuffer>,
5197 _: Arc<Client>,
5198 mut cx: AsyncAppContext,
5199 ) -> Result<proto::BufferSaved> {
5200 let buffer_id = envelope.payload.buffer_id;
5201 let requested_version = deserialize_version(envelope.payload.version);
5202
5203 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5204 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5205 let buffer = this
5206 .opened_buffers
5207 .get(&buffer_id)
5208 .and_then(|buffer| buffer.upgrade(cx))
5209 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5210 Ok::<_, anyhow::Error>((project_id, buffer))
5211 })?;
5212 buffer
5213 .update(&mut cx, |buffer, _| {
5214 buffer.wait_for_version(requested_version)
5215 })
5216 .await;
5217
5218 let (saved_version, fingerprint, mtime) =
5219 buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
5220 Ok(proto::BufferSaved {
5221 project_id,
5222 buffer_id,
5223 version: serialize_version(&saved_version),
5224 mtime: Some(mtime.into()),
5225 fingerprint,
5226 })
5227 }
5228
5229 async fn handle_reload_buffers(
5230 this: ModelHandle<Self>,
5231 envelope: TypedEnvelope<proto::ReloadBuffers>,
5232 _: Arc<Client>,
5233 mut cx: AsyncAppContext,
5234 ) -> Result<proto::ReloadBuffersResponse> {
5235 let sender_id = envelope.original_sender_id()?;
5236 let reload = this.update(&mut cx, |this, cx| {
5237 let mut buffers = HashSet::default();
5238 for buffer_id in &envelope.payload.buffer_ids {
5239 buffers.insert(
5240 this.opened_buffers
5241 .get(buffer_id)
5242 .and_then(|buffer| buffer.upgrade(cx))
5243 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5244 );
5245 }
5246 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5247 })?;
5248
5249 let project_transaction = reload.await?;
5250 let project_transaction = this.update(&mut cx, |this, cx| {
5251 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5252 });
5253 Ok(proto::ReloadBuffersResponse {
5254 transaction: Some(project_transaction),
5255 })
5256 }
5257
5258 async fn handle_format_buffers(
5259 this: ModelHandle<Self>,
5260 envelope: TypedEnvelope<proto::FormatBuffers>,
5261 _: Arc<Client>,
5262 mut cx: AsyncAppContext,
5263 ) -> Result<proto::FormatBuffersResponse> {
5264 let sender_id = envelope.original_sender_id()?;
5265 let format = this.update(&mut cx, |this, cx| {
5266 let mut buffers = HashSet::default();
5267 for buffer_id in &envelope.payload.buffer_ids {
5268 buffers.insert(
5269 this.opened_buffers
5270 .get(buffer_id)
5271 .and_then(|buffer| buffer.upgrade(cx))
5272 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5273 );
5274 }
5275 Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
5276 })?;
5277
5278 let project_transaction = format.await?;
5279 let project_transaction = this.update(&mut cx, |this, cx| {
5280 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5281 });
5282 Ok(proto::FormatBuffersResponse {
5283 transaction: Some(project_transaction),
5284 })
5285 }
5286
5287 async fn handle_get_completions(
5288 this: ModelHandle<Self>,
5289 envelope: TypedEnvelope<proto::GetCompletions>,
5290 _: Arc<Client>,
5291 mut cx: AsyncAppContext,
5292 ) -> Result<proto::GetCompletionsResponse> {
5293 let position = envelope
5294 .payload
5295 .position
5296 .and_then(language::proto::deserialize_anchor)
5297 .ok_or_else(|| anyhow!("invalid position"))?;
5298 let version = deserialize_version(envelope.payload.version);
5299 let buffer = this.read_with(&cx, |this, cx| {
5300 this.opened_buffers
5301 .get(&envelope.payload.buffer_id)
5302 .and_then(|buffer| buffer.upgrade(cx))
5303 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5304 })?;
5305 buffer
5306 .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5307 .await;
5308 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5309 let completions = this
5310 .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5311 .await?;
5312
5313 Ok(proto::GetCompletionsResponse {
5314 completions: completions
5315 .iter()
5316 .map(language::proto::serialize_completion)
5317 .collect(),
5318 version: serialize_version(&version),
5319 })
5320 }
5321
5322 async fn handle_apply_additional_edits_for_completion(
5323 this: ModelHandle<Self>,
5324 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5325 _: Arc<Client>,
5326 mut cx: AsyncAppContext,
5327 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5328 let (buffer, completion) = this.update(&mut cx, |this, cx| {
5329 let buffer = this
5330 .opened_buffers
5331 .get(&envelope.payload.buffer_id)
5332 .and_then(|buffer| buffer.upgrade(cx))
5333 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5334 let language = buffer.read(cx).language();
5335 let completion = language::proto::deserialize_completion(
5336 envelope
5337 .payload
5338 .completion
5339 .ok_or_else(|| anyhow!("invalid completion"))?,
5340 language.cloned(),
5341 );
5342 Ok::<_, anyhow::Error>((buffer, completion))
5343 })?;
5344
5345 let completion = completion.await?;
5346
5347 let apply_additional_edits = this.update(&mut cx, |this, cx| {
5348 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5349 });
5350
5351 Ok(proto::ApplyCompletionAdditionalEditsResponse {
5352 transaction: apply_additional_edits
5353 .await?
5354 .as_ref()
5355 .map(language::proto::serialize_transaction),
5356 })
5357 }
5358
5359 async fn handle_get_code_actions(
5360 this: ModelHandle<Self>,
5361 envelope: TypedEnvelope<proto::GetCodeActions>,
5362 _: Arc<Client>,
5363 mut cx: AsyncAppContext,
5364 ) -> Result<proto::GetCodeActionsResponse> {
5365 let start = envelope
5366 .payload
5367 .start
5368 .and_then(language::proto::deserialize_anchor)
5369 .ok_or_else(|| anyhow!("invalid start"))?;
5370 let end = envelope
5371 .payload
5372 .end
5373 .and_then(language::proto::deserialize_anchor)
5374 .ok_or_else(|| anyhow!("invalid end"))?;
5375 let buffer = this.update(&mut cx, |this, cx| {
5376 this.opened_buffers
5377 .get(&envelope.payload.buffer_id)
5378 .and_then(|buffer| buffer.upgrade(cx))
5379 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5380 })?;
5381 buffer
5382 .update(&mut cx, |buffer, _| {
5383 buffer.wait_for_version(deserialize_version(envelope.payload.version))
5384 })
5385 .await;
5386
5387 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5388 let code_actions = this.update(&mut cx, |this, cx| {
5389 Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5390 })?;
5391
5392 Ok(proto::GetCodeActionsResponse {
5393 actions: code_actions
5394 .await?
5395 .iter()
5396 .map(language::proto::serialize_code_action)
5397 .collect(),
5398 version: serialize_version(&version),
5399 })
5400 }
5401
5402 async fn handle_apply_code_action(
5403 this: ModelHandle<Self>,
5404 envelope: TypedEnvelope<proto::ApplyCodeAction>,
5405 _: Arc<Client>,
5406 mut cx: AsyncAppContext,
5407 ) -> Result<proto::ApplyCodeActionResponse> {
5408 let sender_id = envelope.original_sender_id()?;
5409 let action = language::proto::deserialize_code_action(
5410 envelope
5411 .payload
5412 .action
5413 .ok_or_else(|| anyhow!("invalid action"))?,
5414 )?;
5415 let apply_code_action = this.update(&mut cx, |this, cx| {
5416 let buffer = this
5417 .opened_buffers
5418 .get(&envelope.payload.buffer_id)
5419 .and_then(|buffer| buffer.upgrade(cx))
5420 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5421 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5422 })?;
5423
5424 let project_transaction = apply_code_action.await?;
5425 let project_transaction = this.update(&mut cx, |this, cx| {
5426 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5427 });
5428 Ok(proto::ApplyCodeActionResponse {
5429 transaction: Some(project_transaction),
5430 })
5431 }
5432
5433 async fn handle_lsp_command<T: LspCommand>(
5434 this: ModelHandle<Self>,
5435 envelope: TypedEnvelope<T::ProtoRequest>,
5436 _: Arc<Client>,
5437 mut cx: AsyncAppContext,
5438 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5439 where
5440 <T::LspRequest as lsp::request::Request>::Result: Send,
5441 {
5442 let sender_id = envelope.original_sender_id()?;
5443 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5444 let buffer_handle = this.read_with(&cx, |this, _| {
5445 this.opened_buffers
5446 .get(&buffer_id)
5447 .and_then(|buffer| buffer.upgrade(&cx))
5448 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5449 })?;
5450 let request = T::from_proto(
5451 envelope.payload,
5452 this.clone(),
5453 buffer_handle.clone(),
5454 cx.clone(),
5455 )
5456 .await?;
5457 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5458 let response = this
5459 .update(&mut cx, |this, cx| {
5460 this.request_lsp(buffer_handle, request, cx)
5461 })
5462 .await?;
5463 this.update(&mut cx, |this, cx| {
5464 Ok(T::response_to_proto(
5465 response,
5466 this,
5467 sender_id,
5468 &buffer_version,
5469 cx,
5470 ))
5471 })
5472 }
5473
5474 async fn handle_get_project_symbols(
5475 this: ModelHandle<Self>,
5476 envelope: TypedEnvelope<proto::GetProjectSymbols>,
5477 _: Arc<Client>,
5478 mut cx: AsyncAppContext,
5479 ) -> Result<proto::GetProjectSymbolsResponse> {
5480 let symbols = this
5481 .update(&mut cx, |this, cx| {
5482 this.symbols(&envelope.payload.query, cx)
5483 })
5484 .await?;
5485
5486 Ok(proto::GetProjectSymbolsResponse {
5487 symbols: symbols.iter().map(serialize_symbol).collect(),
5488 })
5489 }
5490
5491 async fn handle_search_project(
5492 this: ModelHandle<Self>,
5493 envelope: TypedEnvelope<proto::SearchProject>,
5494 _: Arc<Client>,
5495 mut cx: AsyncAppContext,
5496 ) -> Result<proto::SearchProjectResponse> {
5497 let peer_id = envelope.original_sender_id()?;
5498 let query = SearchQuery::from_proto(envelope.payload)?;
5499 let result = this
5500 .update(&mut cx, |this, cx| this.search(query, cx))
5501 .await?;
5502
5503 this.update(&mut cx, |this, cx| {
5504 let mut locations = Vec::new();
5505 for (buffer, ranges) in result {
5506 for range in ranges {
5507 let start = serialize_anchor(&range.start);
5508 let end = serialize_anchor(&range.end);
5509 let buffer = this.serialize_buffer_for_peer(&buffer, peer_id, cx);
5510 locations.push(proto::Location {
5511 buffer: Some(buffer),
5512 start: Some(start),
5513 end: Some(end),
5514 });
5515 }
5516 }
5517 Ok(proto::SearchProjectResponse { locations })
5518 })
5519 }
5520
5521 async fn handle_open_buffer_for_symbol(
5522 this: ModelHandle<Self>,
5523 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5524 _: Arc<Client>,
5525 mut cx: AsyncAppContext,
5526 ) -> Result<proto::OpenBufferForSymbolResponse> {
5527 let peer_id = envelope.original_sender_id()?;
5528 let symbol = envelope
5529 .payload
5530 .symbol
5531 .ok_or_else(|| anyhow!("invalid symbol"))?;
5532 let symbol = this
5533 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5534 .await?;
5535 let symbol = this.read_with(&cx, |this, _| {
5536 let signature = this.symbol_signature(symbol.worktree_id, &symbol.path);
5537 if signature == symbol.signature {
5538 Ok(symbol)
5539 } else {
5540 Err(anyhow!("invalid symbol signature"))
5541 }
5542 })?;
5543 let buffer = this
5544 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5545 .await?;
5546
5547 Ok(proto::OpenBufferForSymbolResponse {
5548 buffer: Some(this.update(&mut cx, |this, cx| {
5549 this.serialize_buffer_for_peer(&buffer, peer_id, cx)
5550 })),
5551 })
5552 }
5553
5554 fn symbol_signature(&self, worktree_id: WorktreeId, path: &Path) -> [u8; 32] {
5555 let mut hasher = Sha256::new();
5556 hasher.update(worktree_id.to_proto().to_be_bytes());
5557 hasher.update(path.to_string_lossy().as_bytes());
5558 hasher.update(self.nonce.to_be_bytes());
5559 hasher.finalize().as_slice().try_into().unwrap()
5560 }
5561
5562 async fn handle_open_buffer_by_id(
5563 this: ModelHandle<Self>,
5564 envelope: TypedEnvelope<proto::OpenBufferById>,
5565 _: Arc<Client>,
5566 mut cx: AsyncAppContext,
5567 ) -> Result<proto::OpenBufferResponse> {
5568 let peer_id = envelope.original_sender_id()?;
5569 let buffer = this
5570 .update(&mut cx, |this, cx| {
5571 this.open_buffer_by_id(envelope.payload.id, cx)
5572 })
5573 .await?;
5574 this.update(&mut cx, |this, cx| {
5575 Ok(proto::OpenBufferResponse {
5576 buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
5577 })
5578 })
5579 }
5580
5581 async fn handle_open_buffer_by_path(
5582 this: ModelHandle<Self>,
5583 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5584 _: Arc<Client>,
5585 mut cx: AsyncAppContext,
5586 ) -> Result<proto::OpenBufferResponse> {
5587 let peer_id = envelope.original_sender_id()?;
5588 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5589 let open_buffer = this.update(&mut cx, |this, cx| {
5590 this.open_buffer(
5591 ProjectPath {
5592 worktree_id,
5593 path: PathBuf::from(envelope.payload.path).into(),
5594 },
5595 cx,
5596 )
5597 });
5598
5599 let buffer = open_buffer.await?;
5600 this.update(&mut cx, |this, cx| {
5601 Ok(proto::OpenBufferResponse {
5602 buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
5603 })
5604 })
5605 }
5606
5607 fn serialize_project_transaction_for_peer(
5608 &mut self,
5609 project_transaction: ProjectTransaction,
5610 peer_id: PeerId,
5611 cx: &AppContext,
5612 ) -> proto::ProjectTransaction {
5613 let mut serialized_transaction = proto::ProjectTransaction {
5614 buffers: Default::default(),
5615 transactions: Default::default(),
5616 };
5617 for (buffer, transaction) in project_transaction.0 {
5618 serialized_transaction
5619 .buffers
5620 .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
5621 serialized_transaction
5622 .transactions
5623 .push(language::proto::serialize_transaction(&transaction));
5624 }
5625 serialized_transaction
5626 }
5627
5628 fn deserialize_project_transaction(
5629 &mut self,
5630 message: proto::ProjectTransaction,
5631 push_to_history: bool,
5632 cx: &mut ModelContext<Self>,
5633 ) -> Task<Result<ProjectTransaction>> {
5634 cx.spawn(|this, mut cx| async move {
5635 let mut project_transaction = ProjectTransaction::default();
5636 for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
5637 let buffer = this
5638 .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
5639 .await?;
5640 let transaction = language::proto::deserialize_transaction(transaction)?;
5641 project_transaction.0.insert(buffer, transaction);
5642 }
5643
5644 for (buffer, transaction) in &project_transaction.0 {
5645 buffer
5646 .update(&mut cx, |buffer, _| {
5647 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5648 })
5649 .await;
5650
5651 if push_to_history {
5652 buffer.update(&mut cx, |buffer, _| {
5653 buffer.push_transaction(transaction.clone(), Instant::now());
5654 });
5655 }
5656 }
5657
5658 Ok(project_transaction)
5659 })
5660 }
5661
5662 fn serialize_buffer_for_peer(
5663 &mut self,
5664 buffer: &ModelHandle<Buffer>,
5665 peer_id: PeerId,
5666 cx: &AppContext,
5667 ) -> proto::Buffer {
5668 let buffer_id = buffer.read(cx).remote_id();
5669 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5670 if shared_buffers.insert(buffer_id) {
5671 proto::Buffer {
5672 variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
5673 }
5674 } else {
5675 proto::Buffer {
5676 variant: Some(proto::buffer::Variant::Id(buffer_id)),
5677 }
5678 }
5679 }
5680
5681 fn deserialize_buffer(
5682 &mut self,
5683 buffer: proto::Buffer,
5684 cx: &mut ModelContext<Self>,
5685 ) -> Task<Result<ModelHandle<Buffer>>> {
5686 let replica_id = self.replica_id();
5687
5688 let opened_buffer_tx = self.opened_buffer.0.clone();
5689 let mut opened_buffer_rx = self.opened_buffer.1.clone();
5690 cx.spawn(|this, mut cx| async move {
5691 match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
5692 proto::buffer::Variant::Id(id) => {
5693 let buffer = loop {
5694 let buffer = this.read_with(&cx, |this, cx| {
5695 this.opened_buffers
5696 .get(&id)
5697 .and_then(|buffer| buffer.upgrade(cx))
5698 });
5699 if let Some(buffer) = buffer {
5700 break buffer;
5701 }
5702 opened_buffer_rx
5703 .next()
5704 .await
5705 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5706 };
5707 Ok(buffer)
5708 }
5709 proto::buffer::Variant::State(mut buffer) => {
5710 let mut buffer_worktree = None;
5711 let mut buffer_file = None;
5712 if let Some(file) = buffer.file.take() {
5713 this.read_with(&cx, |this, cx| {
5714 let worktree_id = WorktreeId::from_proto(file.worktree_id);
5715 let worktree =
5716 this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5717 anyhow!("no worktree found for id {}", file.worktree_id)
5718 })?;
5719 buffer_file =
5720 Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5721 as Arc<dyn language::File>);
5722 buffer_worktree = Some(worktree);
5723 Ok::<_, anyhow::Error>(())
5724 })?;
5725 }
5726
5727 let buffer = cx.add_model(|cx| {
5728 Buffer::from_proto(replica_id, buffer, buffer_file, cx).unwrap()
5729 });
5730
5731 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
5732
5733 *opened_buffer_tx.borrow_mut().borrow_mut() = ();
5734 Ok(buffer)
5735 }
5736 }
5737 })
5738 }
5739
5740 fn deserialize_symbol(
5741 &self,
5742 serialized_symbol: proto::Symbol,
5743 ) -> impl Future<Output = Result<Symbol>> {
5744 let languages = self.languages.clone();
5745 async move {
5746 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5747 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5748 let start = serialized_symbol
5749 .start
5750 .ok_or_else(|| anyhow!("invalid start"))?;
5751 let end = serialized_symbol
5752 .end
5753 .ok_or_else(|| anyhow!("invalid end"))?;
5754 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5755 let path = PathBuf::from(serialized_symbol.path);
5756 let language = languages.select_language(&path);
5757 Ok(Symbol {
5758 source_worktree_id,
5759 worktree_id,
5760 language_server_name: LanguageServerName(
5761 serialized_symbol.language_server_name.into(),
5762 ),
5763 label: {
5764 match language {
5765 Some(language) => {
5766 language
5767 .label_for_symbol(&serialized_symbol.name, kind)
5768 .await
5769 }
5770 None => None,
5771 }
5772 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
5773 },
5774
5775 name: serialized_symbol.name,
5776 path,
5777 range: PointUtf16::new(start.row, start.column)
5778 ..PointUtf16::new(end.row, end.column),
5779 kind,
5780 signature: serialized_symbol
5781 .signature
5782 .try_into()
5783 .map_err(|_| anyhow!("invalid signature"))?,
5784 })
5785 }
5786 }
5787
5788 async fn handle_buffer_saved(
5789 this: ModelHandle<Self>,
5790 envelope: TypedEnvelope<proto::BufferSaved>,
5791 _: Arc<Client>,
5792 mut cx: AsyncAppContext,
5793 ) -> Result<()> {
5794 let version = deserialize_version(envelope.payload.version);
5795 let mtime = envelope
5796 .payload
5797 .mtime
5798 .ok_or_else(|| anyhow!("missing mtime"))?
5799 .into();
5800
5801 this.update(&mut cx, |this, cx| {
5802 let buffer = this
5803 .opened_buffers
5804 .get(&envelope.payload.buffer_id)
5805 .and_then(|buffer| buffer.upgrade(cx));
5806 if let Some(buffer) = buffer {
5807 buffer.update(cx, |buffer, cx| {
5808 buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5809 });
5810 }
5811 Ok(())
5812 })
5813 }
5814
5815 async fn handle_buffer_reloaded(
5816 this: ModelHandle<Self>,
5817 envelope: TypedEnvelope<proto::BufferReloaded>,
5818 _: Arc<Client>,
5819 mut cx: AsyncAppContext,
5820 ) -> Result<()> {
5821 let payload = envelope.payload;
5822 let version = deserialize_version(payload.version);
5823 let line_ending = deserialize_line_ending(
5824 proto::LineEnding::from_i32(payload.line_ending)
5825 .ok_or_else(|| anyhow!("missing line ending"))?,
5826 );
5827 let mtime = payload
5828 .mtime
5829 .ok_or_else(|| anyhow!("missing mtime"))?
5830 .into();
5831 this.update(&mut cx, |this, cx| {
5832 let buffer = this
5833 .opened_buffers
5834 .get(&payload.buffer_id)
5835 .and_then(|buffer| buffer.upgrade(cx));
5836 if let Some(buffer) = buffer {
5837 buffer.update(cx, |buffer, cx| {
5838 buffer.did_reload(version, payload.fingerprint, line_ending, mtime, cx);
5839 });
5840 }
5841 Ok(())
5842 })
5843 }
5844
5845 pub fn match_paths<'a>(
5846 &self,
5847 query: &'a str,
5848 include_ignored: bool,
5849 smart_case: bool,
5850 max_results: usize,
5851 cancel_flag: &'a AtomicBool,
5852 cx: &AppContext,
5853 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
5854 let worktrees = self
5855 .worktrees(cx)
5856 .filter(|worktree| worktree.read(cx).is_visible())
5857 .collect::<Vec<_>>();
5858 let include_root_name = worktrees.len() > 1;
5859 let candidate_sets = worktrees
5860 .into_iter()
5861 .map(|worktree| CandidateSet {
5862 snapshot: worktree.read(cx).snapshot(),
5863 include_ignored,
5864 include_root_name,
5865 })
5866 .collect::<Vec<_>>();
5867
5868 let background = cx.background().clone();
5869 async move {
5870 fuzzy::match_paths(
5871 candidate_sets.as_slice(),
5872 query,
5873 smart_case,
5874 max_results,
5875 cancel_flag,
5876 background,
5877 )
5878 .await
5879 }
5880 }
5881
5882 fn edits_from_lsp(
5883 &mut self,
5884 buffer: &ModelHandle<Buffer>,
5885 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5886 version: Option<i32>,
5887 cx: &mut ModelContext<Self>,
5888 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
5889 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
5890 cx.background().spawn(async move {
5891 let snapshot = snapshot?;
5892 let mut lsp_edits = lsp_edits
5893 .into_iter()
5894 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
5895 .collect::<Vec<_>>();
5896 lsp_edits.sort_by_key(|(range, _)| range.start);
5897
5898 let mut lsp_edits = lsp_edits.into_iter().peekable();
5899 let mut edits = Vec::new();
5900 while let Some((mut range, mut new_text)) = lsp_edits.next() {
5901 // Combine any LSP edits that are adjacent.
5902 //
5903 // Also, combine LSP edits that are separated from each other by only
5904 // a newline. This is important because for some code actions,
5905 // Rust-analyzer rewrites the entire buffer via a series of edits that
5906 // are separated by unchanged newline characters.
5907 //
5908 // In order for the diffing logic below to work properly, any edits that
5909 // cancel each other out must be combined into one.
5910 while let Some((next_range, next_text)) = lsp_edits.peek() {
5911 if next_range.start > range.end {
5912 if next_range.start.row > range.end.row + 1
5913 || next_range.start.column > 0
5914 || snapshot.clip_point_utf16(
5915 PointUtf16::new(range.end.row, u32::MAX),
5916 Bias::Left,
5917 ) > range.end
5918 {
5919 break;
5920 }
5921 new_text.push('\n');
5922 }
5923 range.end = next_range.end;
5924 new_text.push_str(&next_text);
5925 lsp_edits.next();
5926 }
5927
5928 if snapshot.clip_point_utf16(range.start, Bias::Left) != range.start
5929 || snapshot.clip_point_utf16(range.end, Bias::Left) != range.end
5930 {
5931 return Err(anyhow!("invalid edits received from language server"));
5932 }
5933
5934 // For multiline edits, perform a diff of the old and new text so that
5935 // we can identify the changes more precisely, preserving the locations
5936 // of any anchors positioned in the unchanged regions.
5937 if range.end.row > range.start.row {
5938 let mut offset = range.start.to_offset(&snapshot);
5939 let old_text = snapshot.text_for_range(range).collect::<String>();
5940
5941 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
5942 let mut moved_since_edit = true;
5943 for change in diff.iter_all_changes() {
5944 let tag = change.tag();
5945 let value = change.value();
5946 match tag {
5947 ChangeTag::Equal => {
5948 offset += value.len();
5949 moved_since_edit = true;
5950 }
5951 ChangeTag::Delete => {
5952 let start = snapshot.anchor_after(offset);
5953 let end = snapshot.anchor_before(offset + value.len());
5954 if moved_since_edit {
5955 edits.push((start..end, String::new()));
5956 } else {
5957 edits.last_mut().unwrap().0.end = end;
5958 }
5959 offset += value.len();
5960 moved_since_edit = false;
5961 }
5962 ChangeTag::Insert => {
5963 if moved_since_edit {
5964 let anchor = snapshot.anchor_after(offset);
5965 edits.push((anchor.clone()..anchor, value.to_string()));
5966 } else {
5967 edits.last_mut().unwrap().1.push_str(value);
5968 }
5969 moved_since_edit = false;
5970 }
5971 }
5972 }
5973 } else if range.end == range.start {
5974 let anchor = snapshot.anchor_after(range.start);
5975 edits.push((anchor.clone()..anchor, new_text));
5976 } else {
5977 let edit_start = snapshot.anchor_after(range.start);
5978 let edit_end = snapshot.anchor_before(range.end);
5979 edits.push((edit_start..edit_end, new_text));
5980 }
5981 }
5982
5983 Ok(edits)
5984 })
5985 }
5986
5987 fn buffer_snapshot_for_lsp_version(
5988 &mut self,
5989 buffer: &ModelHandle<Buffer>,
5990 version: Option<i32>,
5991 cx: &AppContext,
5992 ) -> Result<TextBufferSnapshot> {
5993 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
5994
5995 if let Some(version) = version {
5996 let buffer_id = buffer.read(cx).remote_id();
5997 let snapshots = self
5998 .buffer_snapshots
5999 .get_mut(&buffer_id)
6000 .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
6001 let mut found_snapshot = None;
6002 snapshots.retain(|(snapshot_version, snapshot)| {
6003 if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
6004 false
6005 } else {
6006 if *snapshot_version == version {
6007 found_snapshot = Some(snapshot.clone());
6008 }
6009 true
6010 }
6011 });
6012
6013 found_snapshot.ok_or_else(|| {
6014 anyhow!(
6015 "snapshot not found for buffer {} at version {}",
6016 buffer_id,
6017 version
6018 )
6019 })
6020 } else {
6021 Ok((buffer.read(cx)).text_snapshot())
6022 }
6023 }
6024
6025 fn language_server_for_buffer(
6026 &self,
6027 buffer: &Buffer,
6028 cx: &AppContext,
6029 ) -> Option<(&Arc<dyn LspAdapter>, &Arc<LanguageServer>)> {
6030 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6031 // TODO(isaac): this is not a good idea
6032 let name = cx.background().block(language.lsp_adapter()?.name());
6033 let worktree_id = file.worktree_id(cx);
6034 let key = (worktree_id, language.lsp_adapter()?.name());
6035
6036 if let Some(server_id) = self.language_server_ids.get(&key) {
6037 if let Some(LanguageServerState::Running { adapter, server }) =
6038 self.language_servers.get(&server_id)
6039 {
6040 return Some((adapter, server));
6041 }
6042 }
6043 }
6044
6045 None
6046 }
6047}
6048
6049impl ProjectStore {
6050 pub fn new(db: Arc<Db>) -> Self {
6051 Self {
6052 db,
6053 projects: Default::default(),
6054 }
6055 }
6056
6057 pub fn projects<'a>(
6058 &'a self,
6059 cx: &'a AppContext,
6060 ) -> impl 'a + Iterator<Item = ModelHandle<Project>> {
6061 self.projects
6062 .iter()
6063 .filter_map(|project| project.upgrade(cx))
6064 }
6065
6066 fn add_project(&mut self, project: WeakModelHandle<Project>, cx: &mut ModelContext<Self>) {
6067 if let Err(ix) = self
6068 .projects
6069 .binary_search_by_key(&project.id(), WeakModelHandle::id)
6070 {
6071 self.projects.insert(ix, project);
6072 }
6073 cx.notify();
6074 }
6075
6076 fn prune_projects(&mut self, cx: &mut ModelContext<Self>) {
6077 let mut did_change = false;
6078 self.projects.retain(|project| {
6079 if project.is_upgradable(cx) {
6080 true
6081 } else {
6082 did_change = true;
6083 false
6084 }
6085 });
6086 if did_change {
6087 cx.notify();
6088 }
6089 }
6090}
6091
6092impl WorktreeHandle {
6093 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6094 match self {
6095 WorktreeHandle::Strong(handle) => Some(handle.clone()),
6096 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6097 }
6098 }
6099}
6100
6101impl OpenBuffer {
6102 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6103 match self {
6104 OpenBuffer::Strong(handle) => Some(handle.clone()),
6105 OpenBuffer::Weak(handle) => handle.upgrade(cx),
6106 OpenBuffer::Loading(_) => None,
6107 }
6108 }
6109}
6110
6111struct CandidateSet {
6112 snapshot: Snapshot,
6113 include_ignored: bool,
6114 include_root_name: bool,
6115}
6116
6117impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
6118 type Candidates = CandidateSetIter<'a>;
6119
6120 fn id(&self) -> usize {
6121 self.snapshot.id().to_usize()
6122 }
6123
6124 fn len(&self) -> usize {
6125 if self.include_ignored {
6126 self.snapshot.file_count()
6127 } else {
6128 self.snapshot.visible_file_count()
6129 }
6130 }
6131
6132 fn prefix(&self) -> Arc<str> {
6133 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6134 self.snapshot.root_name().into()
6135 } else if self.include_root_name {
6136 format!("{}/", self.snapshot.root_name()).into()
6137 } else {
6138 "".into()
6139 }
6140 }
6141
6142 fn candidates(&'a self, start: usize) -> Self::Candidates {
6143 CandidateSetIter {
6144 traversal: self.snapshot.files(self.include_ignored, start),
6145 }
6146 }
6147}
6148
6149struct CandidateSetIter<'a> {
6150 traversal: Traversal<'a>,
6151}
6152
6153impl<'a> Iterator for CandidateSetIter<'a> {
6154 type Item = PathMatchCandidate<'a>;
6155
6156 fn next(&mut self) -> Option<Self::Item> {
6157 self.traversal.next().map(|entry| {
6158 if let EntryKind::File(char_bag) = entry.kind {
6159 PathMatchCandidate {
6160 path: &entry.path,
6161 char_bag,
6162 }
6163 } else {
6164 unreachable!()
6165 }
6166 })
6167 }
6168}
6169
6170impl Entity for ProjectStore {
6171 type Event = ();
6172}
6173
6174impl Entity for Project {
6175 type Event = Event;
6176
6177 fn release(&mut self, cx: &mut gpui::MutableAppContext) {
6178 self.project_store.update(cx, ProjectStore::prune_projects);
6179
6180 match &self.client_state {
6181 ProjectClientState::Local { remote_id_rx, .. } => {
6182 if let Some(project_id) = *remote_id_rx.borrow() {
6183 self.client
6184 .send(proto::UnregisterProject { project_id })
6185 .log_err();
6186 }
6187 }
6188 ProjectClientState::Remote { remote_id, .. } => {
6189 self.client
6190 .send(proto::LeaveProject {
6191 project_id: *remote_id,
6192 })
6193 .log_err();
6194 }
6195 }
6196 }
6197
6198 fn app_will_quit(
6199 &mut self,
6200 _: &mut MutableAppContext,
6201 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6202 let shutdown_futures = self
6203 .language_servers
6204 .drain()
6205 .map(|(_, server_state)| async {
6206 match server_state {
6207 LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6208 LanguageServerState::Starting(starting_server) => {
6209 starting_server.await?.shutdown()?.await
6210 }
6211 }
6212 })
6213 .collect::<Vec<_>>();
6214
6215 Some(
6216 async move {
6217 futures::future::join_all(shutdown_futures).await;
6218 }
6219 .boxed(),
6220 )
6221 }
6222}
6223
6224impl Collaborator {
6225 fn from_proto(
6226 message: proto::Collaborator,
6227 user_store: &ModelHandle<UserStore>,
6228 cx: &mut AsyncAppContext,
6229 ) -> impl Future<Output = Result<Self>> {
6230 let user = user_store.update(cx, |user_store, cx| {
6231 user_store.fetch_user(message.user_id, cx)
6232 });
6233
6234 async move {
6235 Ok(Self {
6236 peer_id: PeerId(message.peer_id),
6237 user: user.await?,
6238 replica_id: message.replica_id as ReplicaId,
6239 })
6240 }
6241 }
6242}
6243
6244impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6245 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6246 Self {
6247 worktree_id,
6248 path: path.as_ref().into(),
6249 }
6250 }
6251}
6252
6253impl From<lsp::CreateFileOptions> for fs::CreateOptions {
6254 fn from(options: lsp::CreateFileOptions) -> Self {
6255 Self {
6256 overwrite: options.overwrite.unwrap_or(false),
6257 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6258 }
6259 }
6260}
6261
6262impl From<lsp::RenameFileOptions> for fs::RenameOptions {
6263 fn from(options: lsp::RenameFileOptions) -> Self {
6264 Self {
6265 overwrite: options.overwrite.unwrap_or(false),
6266 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6267 }
6268 }
6269}
6270
6271impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
6272 fn from(options: lsp::DeleteFileOptions) -> Self {
6273 Self {
6274 recursive: options.recursive.unwrap_or(false),
6275 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
6276 }
6277 }
6278}
6279
6280fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6281 proto::Symbol {
6282 source_worktree_id: symbol.source_worktree_id.to_proto(),
6283 worktree_id: symbol.worktree_id.to_proto(),
6284 language_server_name: symbol.language_server_name.0.to_string(),
6285 name: symbol.name.clone(),
6286 kind: unsafe { mem::transmute(symbol.kind) },
6287 path: symbol.path.to_string_lossy().to_string(),
6288 start: Some(proto::Point {
6289 row: symbol.range.start.row,
6290 column: symbol.range.start.column,
6291 }),
6292 end: Some(proto::Point {
6293 row: symbol.range.end.row,
6294 column: symbol.range.end.column,
6295 }),
6296 signature: symbol.signature.to_vec(),
6297 }
6298}
6299
6300fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6301 let mut path_components = path.components();
6302 let mut base_components = base.components();
6303 let mut components: Vec<Component> = Vec::new();
6304 loop {
6305 match (path_components.next(), base_components.next()) {
6306 (None, None) => break,
6307 (Some(a), None) => {
6308 components.push(a);
6309 components.extend(path_components.by_ref());
6310 break;
6311 }
6312 (None, _) => components.push(Component::ParentDir),
6313 (Some(a), Some(b)) if components.is_empty() && a == b => (),
6314 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6315 (Some(a), Some(_)) => {
6316 components.push(Component::ParentDir);
6317 for _ in base_components {
6318 components.push(Component::ParentDir);
6319 }
6320 components.push(a);
6321 components.extend(path_components.by_ref());
6322 break;
6323 }
6324 }
6325 }
6326 components.iter().map(|c| c.as_os_str()).collect()
6327}
6328
6329impl Item for Buffer {
6330 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6331 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6332 }
6333}