1use crate::{
2 display_map::ToDisplayPoint, link_go_to_definition::hide_link_definition,
3 movement::surrounding_word, persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll, Editor,
4 Event, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, NavigationData, ToPoint as _,
5};
6use anyhow::{Context, Result};
7use collections::HashSet;
8use futures::future::try_join_all;
9use gpui::{
10 point, AnyElement, AppContext, AsyncAppContext, Entity, Model, Pixels, SharedString,
11 Subscription, Task, View, ViewContext, WeakView,
12};
13use language::{
14 proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, OffsetRangeExt, Point,
15 SelectionGoal,
16};
17use project::{search::SearchQuery, FormatTrigger, Item as _, Project, ProjectPath};
18use rpc::proto::{self, update_view, PeerId};
19use smallvec::SmallVec;
20use std::{
21 borrow::Cow,
22 cmp::{self, Ordering},
23 iter,
24 ops::Range,
25 path::{Path, PathBuf},
26 sync::Arc,
27};
28use text::Selection;
29use util::{paths::PathExt, ResultExt, TryFutureExt};
30use workspace::item::{BreadcrumbText, FollowableItemHandle};
31use workspace::{
32 item::{FollowableItem, Item, ItemEvent, ItemHandle, ProjectItem},
33 searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
34 ItemId, ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
35};
36
37pub const MAX_TAB_TITLE_LEN: usize = 24;
38
39impl FollowableItem for Editor {
40 fn remote_id(&self) -> Option<ViewId> {
41 self.remote_id
42 }
43
44 fn from_state_proto(
45 pane: View<workspace::Pane>,
46 workspace: View<Workspace>,
47 remote_id: ViewId,
48 state: &mut Option<proto::view::Variant>,
49 cx: &mut AppContext,
50 ) -> Option<Task<Result<View<Self>>>> {
51 todo!()
52 }
53 // let project = workspace.read(cx).project().to_owned();
54 // let Some(proto::view::Variant::Editor(_)) = state else {
55 // return None;
56 // };
57 // let Some(proto::view::Variant::Editor(state)) = state.take() else {
58 // unreachable!()
59 // };
60
61 // let client = project.read(cx).client();
62 // let replica_id = project.read(cx).replica_id();
63 // let buffer_ids = state
64 // .excerpts
65 // .iter()
66 // .map(|excerpt| excerpt.buffer_id)
67 // .collect::<HashSet<_>>();
68 // let buffers = project.update(cx, |project, cx| {
69 // buffer_ids
70 // .iter()
71 // .map(|id| project.open_buffer_by_id(*id, cx))
72 // .collect::<Vec<_>>()
73 // });
74
75 // let pane = pane.downgrade();
76 // Some(cx.spawn(|mut cx| async move {
77 // let mut buffers = futures::future::try_join_all(buffers).await?;
78 // let editor = pane.read_with(&cx, |pane, cx| {
79 // let mut editors = pane.items_of_type::<Self>();
80 // editors.find(|editor| {
81 // let ids_match = editor.remote_id(&client, cx) == Some(remote_id);
82 // let singleton_buffer_matches = state.singleton
83 // && buffers.first()
84 // == editor.read(cx).buffer.read(cx).as_singleton().as_ref();
85 // ids_match || singleton_buffer_matches
86 // })
87 // })?;
88
89 // let editor = if let Some(editor) = editor {
90 // editor
91 // } else {
92 // pane.update(&mut cx, |_, cx| {
93 // let multibuffer = cx.add_model(|cx| {
94 // let mut multibuffer;
95 // if state.singleton && buffers.len() == 1 {
96 // multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
97 // } else {
98 // multibuffer = MultiBuffer::new(replica_id);
99 // let mut excerpts = state.excerpts.into_iter().peekable();
100 // while let Some(excerpt) = excerpts.peek() {
101 // let buffer_id = excerpt.buffer_id;
102 // let buffer_excerpts = iter::from_fn(|| {
103 // let excerpt = excerpts.peek()?;
104 // (excerpt.buffer_id == buffer_id)
105 // .then(|| excerpts.next().unwrap())
106 // });
107 // let buffer =
108 // buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
109 // if let Some(buffer) = buffer {
110 // multibuffer.push_excerpts(
111 // buffer.clone(),
112 // buffer_excerpts.filter_map(deserialize_excerpt_range),
113 // cx,
114 // );
115 // }
116 // }
117 // };
118
119 // if let Some(title) = &state.title {
120 // multibuffer = multibuffer.with_title(title.clone())
121 // }
122
123 // multibuffer
124 // });
125
126 // cx.add_view(|cx| {
127 // let mut editor =
128 // Editor::for_multibuffer(multibuffer, Some(project.clone()), cx);
129 // editor.remote_id = Some(remote_id);
130 // editor
131 // })
132 // })?
133 // };
134
135 // update_editor_from_message(
136 // editor.downgrade(),
137 // project,
138 // proto::update_view::Editor {
139 // selections: state.selections,
140 // pending_selection: state.pending_selection,
141 // scroll_top_anchor: state.scroll_top_anchor,
142 // scroll_x: state.scroll_x,
143 // scroll_y: state.scroll_y,
144 // ..Default::default()
145 // },
146 // &mut cx,
147 // )
148 // .await?;
149
150 // Ok(editor)
151 // }))
152 // }
153
154 fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
155 self.leader_peer_id = leader_peer_id;
156 if self.leader_peer_id.is_some() {
157 self.buffer.update(cx, |buffer, cx| {
158 buffer.remove_active_selections(cx);
159 });
160 } else {
161 self.buffer.update(cx, |buffer, cx| {
162 if self.focused {
163 buffer.set_active_selections(
164 &self.selections.disjoint_anchors(),
165 self.selections.line_mode,
166 self.cursor_shape,
167 cx,
168 );
169 }
170 });
171 }
172 cx.notify();
173 }
174
175 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
176 let buffer = self.buffer.read(cx);
177 let scroll_anchor = self.scroll_manager.anchor();
178 let excerpts = buffer
179 .read(cx)
180 .excerpts()
181 .map(|(id, buffer, range)| proto::Excerpt {
182 id: id.to_proto(),
183 buffer_id: buffer.remote_id(),
184 context_start: Some(serialize_text_anchor(&range.context.start)),
185 context_end: Some(serialize_text_anchor(&range.context.end)),
186 primary_start: range
187 .primary
188 .as_ref()
189 .map(|range| serialize_text_anchor(&range.start)),
190 primary_end: range
191 .primary
192 .as_ref()
193 .map(|range| serialize_text_anchor(&range.end)),
194 })
195 .collect();
196
197 Some(proto::view::Variant::Editor(proto::view::Editor {
198 singleton: buffer.is_singleton(),
199 title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
200 excerpts,
201 scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
202 scroll_x: scroll_anchor.offset.x,
203 scroll_y: scroll_anchor.offset.y,
204 selections: self
205 .selections
206 .disjoint_anchors()
207 .iter()
208 .map(serialize_selection)
209 .collect(),
210 pending_selection: self
211 .selections
212 .pending_anchor()
213 .as_ref()
214 .map(serialize_selection),
215 }))
216 }
217
218 fn add_event_to_update_proto(
219 &self,
220 event: &Self::Event,
221 update: &mut Option<proto::update_view::Variant>,
222 cx: &AppContext,
223 ) -> bool {
224 let update =
225 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
226
227 match update {
228 proto::update_view::Variant::Editor(update) => match event {
229 Event::ExcerptsAdded {
230 buffer,
231 predecessor,
232 excerpts,
233 } => {
234 let buffer_id = buffer.read(cx).remote_id();
235 let mut excerpts = excerpts.iter();
236 if let Some((id, range)) = excerpts.next() {
237 update.inserted_excerpts.push(proto::ExcerptInsertion {
238 previous_excerpt_id: Some(predecessor.to_proto()),
239 excerpt: serialize_excerpt(buffer_id, id, range),
240 });
241 update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
242 proto::ExcerptInsertion {
243 previous_excerpt_id: None,
244 excerpt: serialize_excerpt(buffer_id, id, range),
245 }
246 }))
247 }
248 true
249 }
250 Event::ExcerptsRemoved { ids } => {
251 update
252 .deleted_excerpts
253 .extend(ids.iter().map(ExcerptId::to_proto));
254 true
255 }
256 Event::ScrollPositionChanged { .. } => {
257 let scroll_anchor = self.scroll_manager.anchor();
258 update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
259 update.scroll_x = scroll_anchor.offset.x;
260 update.scroll_y = scroll_anchor.offset.y;
261 true
262 }
263 Event::SelectionsChanged { .. } => {
264 update.selections = self
265 .selections
266 .disjoint_anchors()
267 .iter()
268 .map(serialize_selection)
269 .collect();
270 update.pending_selection = self
271 .selections
272 .pending_anchor()
273 .as_ref()
274 .map(serialize_selection);
275 true
276 }
277 _ => false,
278 },
279 }
280 }
281
282 fn apply_update_proto(
283 &mut self,
284 project: &Model<Project>,
285 message: update_view::Variant,
286 cx: &mut ViewContext<Self>,
287 ) -> Task<Result<()>> {
288 let update_view::Variant::Editor(message) = message;
289 let project = project.clone();
290 cx.spawn(|this, mut cx| async move {
291 update_editor_from_message(this, project, message, &mut cx).await
292 })
293 }
294
295 fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {
296 match event {
297 Event::Edited => true,
298 Event::SelectionsChanged { local } => *local,
299 Event::ScrollPositionChanged { local, .. } => *local,
300 _ => false,
301 }
302 }
303
304 fn is_project_item(&self, _cx: &AppContext) -> bool {
305 true
306 }
307}
308
309// async fn update_editor_from_message(
310// this: WeakView<Editor>,
311// project: Model<Project>,
312// message: proto::update_view::Editor,
313// cx: &mut AsyncAppContext,
314// ) -> Result<()> {
315// // Open all of the buffers of which excerpts were added to the editor.
316// let inserted_excerpt_buffer_ids = message
317// .inserted_excerpts
318// .iter()
319// .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
320// .collect::<HashSet<_>>();
321// let inserted_excerpt_buffers = project.update(cx, |project, cx| {
322// inserted_excerpt_buffer_ids
323// .into_iter()
324// .map(|id| project.open_buffer_by_id(id, cx))
325// .collect::<Vec<_>>()
326// })?;
327// let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
328
329// // Update the editor's excerpts.
330// this.update(cx, |editor, cx| {
331// editor.buffer.update(cx, |multibuffer, cx| {
332// let mut removed_excerpt_ids = message
333// .deleted_excerpts
334// .into_iter()
335// .map(ExcerptId::from_proto)
336// .collect::<Vec<_>>();
337// removed_excerpt_ids.sort_by({
338// let multibuffer = multibuffer.read(cx);
339// move |a, b| a.cmp(&b, &multibuffer)
340// });
341
342// let mut insertions = message.inserted_excerpts.into_iter().peekable();
343// while let Some(insertion) = insertions.next() {
344// let Some(excerpt) = insertion.excerpt else {
345// continue;
346// };
347// let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
348// continue;
349// };
350// let buffer_id = excerpt.buffer_id;
351// let Some(buffer) = project.read(cx).buffer_for_id(buffer_id) else {
352// continue;
353// };
354
355// let adjacent_excerpts = iter::from_fn(|| {
356// let insertion = insertions.peek()?;
357// if insertion.previous_excerpt_id.is_none()
358// && insertion.excerpt.as_ref()?.buffer_id == buffer_id
359// {
360// insertions.next()?.excerpt
361// } else {
362// None
363// }
364// });
365
366// multibuffer.insert_excerpts_with_ids_after(
367// ExcerptId::from_proto(previous_excerpt_id),
368// buffer,
369// [excerpt]
370// .into_iter()
371// .chain(adjacent_excerpts)
372// .filter_map(|excerpt| {
373// Some((
374// ExcerptId::from_proto(excerpt.id),
375// deserialize_excerpt_range(excerpt)?,
376// ))
377// }),
378// cx,
379// );
380// }
381
382// multibuffer.remove_excerpts(removed_excerpt_ids, cx);
383// });
384// })?;
385
386// // Deserialize the editor state.
387// let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
388// let buffer = editor.buffer.read(cx).read(cx);
389// let selections = message
390// .selections
391// .into_iter()
392// .filter_map(|selection| deserialize_selection(&buffer, selection))
393// .collect::<Vec<_>>();
394// let pending_selection = message
395// .pending_selection
396// .and_then(|selection| deserialize_selection(&buffer, selection));
397// let scroll_top_anchor = message
398// .scroll_top_anchor
399// .and_then(|anchor| deserialize_anchor(&buffer, anchor));
400// anyhow::Ok((selections, pending_selection, scroll_top_anchor))
401// })??;
402
403// // Wait until the buffer has received all of the operations referenced by
404// // the editor's new state.
405// this.update(cx, |editor, cx| {
406// editor.buffer.update(cx, |buffer, cx| {
407// buffer.wait_for_anchors(
408// selections
409// .iter()
410// .chain(pending_selection.as_ref())
411// .flat_map(|selection| [selection.start, selection.end])
412// .chain(scroll_top_anchor),
413// cx,
414// )
415// })
416// })?
417// .await?;
418
419// // Update the editor's state.
420// this.update(cx, |editor, cx| {
421// if !selections.is_empty() || pending_selection.is_some() {
422// editor.set_selections_from_remote(selections, pending_selection, cx);
423// editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
424// } else if let Some(scroll_top_anchor) = scroll_top_anchor {
425// editor.set_scroll_anchor_remote(
426// ScrollAnchor {
427// anchor: scroll_top_anchor,
428// offset: point(message.scroll_x, message.scroll_y),
429// },
430// cx,
431// );
432// }
433// })?;
434// Ok(())
435// }
436
437fn serialize_excerpt(
438 buffer_id: u64,
439 id: &ExcerptId,
440 range: &ExcerptRange<language::Anchor>,
441) -> Option<proto::Excerpt> {
442 Some(proto::Excerpt {
443 id: id.to_proto(),
444 buffer_id,
445 context_start: Some(serialize_text_anchor(&range.context.start)),
446 context_end: Some(serialize_text_anchor(&range.context.end)),
447 primary_start: range
448 .primary
449 .as_ref()
450 .map(|r| serialize_text_anchor(&r.start)),
451 primary_end: range
452 .primary
453 .as_ref()
454 .map(|r| serialize_text_anchor(&r.end)),
455 })
456}
457
458fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
459 proto::Selection {
460 id: selection.id as u64,
461 start: Some(serialize_anchor(&selection.start)),
462 end: Some(serialize_anchor(&selection.end)),
463 reversed: selection.reversed,
464 }
465}
466
467fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
468 proto::EditorAnchor {
469 excerpt_id: anchor.excerpt_id.to_proto(),
470 anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
471 }
472}
473
474fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
475 let context = {
476 let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
477 let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
478 start..end
479 };
480 let primary = excerpt
481 .primary_start
482 .zip(excerpt.primary_end)
483 .and_then(|(start, end)| {
484 let start = language::proto::deserialize_anchor(start)?;
485 let end = language::proto::deserialize_anchor(end)?;
486 Some(start..end)
487 });
488 Some(ExcerptRange { context, primary })
489}
490
491fn deserialize_selection(
492 buffer: &MultiBufferSnapshot,
493 selection: proto::Selection,
494) -> Option<Selection<Anchor>> {
495 Some(Selection {
496 id: selection.id as usize,
497 start: deserialize_anchor(buffer, selection.start?)?,
498 end: deserialize_anchor(buffer, selection.end?)?,
499 reversed: selection.reversed,
500 goal: SelectionGoal::None,
501 })
502}
503
504fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
505 let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
506 Some(Anchor {
507 excerpt_id,
508 text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
509 buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
510 })
511}
512
513impl Item for Editor {
514 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
515 if let Ok(data) = data.downcast::<NavigationData>() {
516 let newest_selection = self.selections.newest::<Point>(cx);
517 let buffer = self.buffer.read(cx).read(cx);
518 let offset = if buffer.can_resolve(&data.cursor_anchor) {
519 data.cursor_anchor.to_point(&buffer)
520 } else {
521 buffer.clip_point(data.cursor_position, Bias::Left)
522 };
523
524 let mut scroll_anchor = data.scroll_anchor;
525 if !buffer.can_resolve(&scroll_anchor.anchor) {
526 scroll_anchor.anchor = buffer.anchor_before(
527 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
528 );
529 }
530
531 drop(buffer);
532
533 if newest_selection.head() == offset {
534 false
535 } else {
536 let nav_history = self.nav_history.take();
537 self.set_scroll_anchor(scroll_anchor, cx);
538 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
539 s.select_ranges([offset..offset])
540 });
541 self.nav_history = nav_history;
542 true
543 }
544 } else {
545 false
546 }
547 }
548
549 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
550 let file_path = self
551 .buffer()
552 .read(cx)
553 .as_singleton()?
554 .read(cx)
555 .file()
556 .and_then(|f| f.as_local())?
557 .abs_path(cx);
558
559 let file_path = file_path.compact().to_string_lossy().to_string();
560
561 Some(file_path.into())
562 }
563
564 fn tab_description<'a>(&'a self, detail: usize, cx: &'a AppContext) -> Option<SharedString> {
565 match path_for_buffer(&self.buffer, detail, true, cx)? {
566 Cow::Borrowed(path) => Some(path.to_string_lossy),
567 Cow::Owned(path) => Some(path.to_string_lossy.to_string().into()),
568 }
569 }
570
571 fn tab_content<T: 'static>(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<T> {
572 todo!();
573
574 // Flex::row()
575 // .with_child(Label::new(self.title(cx).to_string(), style.label.clone()).into_any())
576 // .with_children(detail.and_then(|detail| {
577 // let path = path_for_buffer(&self.buffer, detail, false, cx)?;
578 // let description = path.to_string_lossy();
579 // Some(
580 // Label::new(
581 // util::truncate_and_trailoff(&description, MAX_TAB_TITLE_LEN),
582 // style.description.text.clone(),
583 // )
584 // .contained()
585 // .with_style(style.description.container)
586 // .aligned(),
587 // )
588 // }))
589 // .align_children_center()
590 // .into_any()
591 }
592
593 fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
594 self.buffer
595 .read(cx)
596 .for_each_buffer(|buffer| f(buffer.id(), buffer.read(cx)));
597 }
598
599 fn is_singleton(&self, cx: &AppContext) -> bool {
600 self.buffer.read(cx).is_singleton()
601 }
602
603 fn clone_on_split(
604 &self,
605 _workspace_id: WorkspaceId,
606 cx: &mut ViewContext<Self>,
607 ) -> Option<View<Self>>
608 where
609 Self: Sized,
610 {
611 Some(self.clone())
612 }
613
614 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
615 self.nav_history = Some(history);
616 }
617
618 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
619 let selection = self.selections.newest_anchor();
620 todo!()
621 // self.push_to_nav_history(selection.head(), None, cx);
622 }
623
624 fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
625 hide_link_definition(self, cx);
626 self.link_go_to_definition_state.last_trigger_point = None;
627 }
628
629 fn is_dirty(&self, cx: &AppContext) -> bool {
630 self.buffer().read(cx).read(cx).is_dirty()
631 }
632
633 fn has_conflict(&self, cx: &AppContext) -> bool {
634 self.buffer().read(cx).read(cx).has_conflict()
635 }
636
637 fn can_save(&self, cx: &AppContext) -> bool {
638 let buffer = &self.buffer().read(cx);
639 if let Some(buffer) = buffer.as_singleton() {
640 buffer.read(cx).project_path(cx).is_some()
641 } else {
642 true
643 }
644 }
645
646 fn save(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
647 self.report_editor_event("save", None, cx);
648 let format = self.perform_format(project.clone(), FormatTrigger::Save, cx);
649 let buffers = self.buffer().clone().read(cx).all_buffers();
650 cx.spawn(|_, mut cx| async move {
651 format.await?;
652
653 if buffers.len() == 1 {
654 project
655 .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))
656 .await?;
657 } else {
658 // For multi-buffers, only save those ones that contain changes. For clean buffers
659 // we simulate saving by calling `Buffer::did_save`, so that language servers or
660 // other downstream listeners of save events get notified.
661 let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
662 buffer.read_with(&cx, |buffer, _| buffer.is_dirty || buffer.has_conflict())
663 });
664
665 project
666 .update(&mut cx, |project, cx| {
667 project.save_buffers(dirty_buffers, cx)
668 })
669 .await?;
670 for buffer in clean_buffers {
671 buffer.update(&mut cx, |buffer, cx| {
672 let version = buffer.saved_version().clone();
673 let fingerprint = buffer.saved_version_fingerprint();
674 let mtime = buffer.saved_mtime();
675 buffer.did_save(version, fingerprint, mtime, cx);
676 });
677 }
678 }
679
680 Ok(())
681 })
682 }
683
684 fn save_as(
685 &mut self,
686 project: Model<Project>,
687 abs_path: PathBuf,
688 cx: &mut ViewContext<Self>,
689 ) -> Task<Result<()>> {
690 let buffer = self
691 .buffer()
692 .read(cx)
693 .as_singleton()
694 .expect("cannot call save_as on an excerpt list");
695
696 let file_extension = abs_path.extension().map(|a| a.to_string_lossy.to_string());
697 self.report_editor_event("save", file_extension, cx);
698
699 project.update(cx, |project, cx| {
700 project.save_buffer_as(buffer, abs_path, cx)
701 })
702 }
703
704 fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
705 let buffer = self.buffer().clone();
706 let buffers = self.buffer.read(cx).all_buffers();
707 let reload_buffers =
708 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
709 cx.spawn(|this, mut cx| async move {
710 let transaction = reload_buffers.log_err().await;
711 this.update(&mut cx, |editor, cx| {
712 editor.request_autoscroll(Autoscroll::fit(), cx)
713 })?;
714 buffer.update(&mut cx, |buffer, cx| {
715 if let Some(transaction) = transaction {
716 if !buffer.is_singleton() {
717 buffer.push_transaction(&transaction.0, cx);
718 }
719 }
720 });
721 Ok(())
722 })
723 }
724
725 fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
726 let mut result = SmallVec::new();
727 match event {
728 Event::Closed => result.push(ItemEvent::CloseItem),
729 Event::Saved | Event::TitleChanged => {
730 result.push(ItemEvent::UpdateTab);
731 result.push(ItemEvent::UpdateBreadcrumbs);
732 }
733 Event::Reparsed => {
734 result.push(ItemEvent::UpdateBreadcrumbs);
735 }
736 Event::SelectionsChanged { local } if *local => {
737 result.push(ItemEvent::UpdateBreadcrumbs);
738 }
739 Event::DirtyChanged => {
740 result.push(ItemEvent::UpdateTab);
741 }
742 Event::BufferEdited => {
743 result.push(ItemEvent::Edit);
744 result.push(ItemEvent::UpdateBreadcrumbs);
745 }
746 _ => {}
747 }
748 result
749 }
750
751 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
752 Some(Box::new(handle.clone()))
753 }
754
755 fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
756 self.pixel_position_of_newest_cursor
757 }
758
759 fn breadcrumb_location(&self) -> ToolbarItemLocation {
760 ToolbarItemLocation::PrimaryLeft { flex: None }
761 }
762
763 fn breadcrumbs(&self, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
764 todo!();
765 // let cursor = self.selections.newest_anchor().head();
766 // let multibuffer = &self.buffer().read(cx);
767 // let (buffer_id, symbols) =
768 // multibuffer.symbols_containing(cursor, Some(&theme.editor.syntax), cx)?;
769 // let buffer = multibuffer.buffer(buffer_id)?;
770
771 // let buffer = buffer.read(cx);
772 // let filename = buffer
773 // .snapshot()
774 // .resolve_file_path(
775 // cx,
776 // self.project
777 // .as_ref()
778 // .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
779 // .unwrap_or_default(),
780 // )
781 // .map(|path| path.to_string_lossy().to_string())
782 // .unwrap_or_else(|| "untitled".to_string());
783
784 // let mut breadcrumbs = vec![BreadcrumbText {
785 // text: filename,
786 // highlights: None,
787 // }];
788 // breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
789 // text: symbol.text,
790 // highlights: Some(symbol.highlight_ranges),
791 // }));
792 // Some(breadcrumbs)
793 }
794
795 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
796 let workspace_id = workspace.database_id();
797 let item_id = cx.view_id();
798 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
799
800 fn serialize(
801 buffer: Model<Buffer>,
802 workspace_id: WorkspaceId,
803 item_id: ItemId,
804 cx: &mut AppContext,
805 ) {
806 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
807 let path = file.abs_path(cx);
808
809 cx.background()
810 .spawn(async move {
811 DB.save_path(item_id, workspace_id, path.clone())
812 .await
813 .log_err()
814 })
815 .detach();
816 }
817 }
818
819 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
820 serialize(buffer.clone(), workspace_id, item_id, cx);
821
822 cx.subscribe(&buffer, |this, buffer, event, cx| {
823 if let Some((_, workspace_id)) = this.workspace.as_ref() {
824 if let language::Event::FileHandleChanged = event {
825 serialize(buffer, *workspace_id, cx.view_id(), cx);
826 }
827 }
828 })
829 .detach();
830 }
831 }
832
833 fn serialized_item_kind() -> Option<&'static str> {
834 Some("Editor")
835 }
836
837 fn deserialize(
838 project: Model<Project>,
839 _workspace: WeakView<Workspace>,
840 workspace_id: workspace::WorkspaceId,
841 item_id: ItemId,
842 cx: &mut ViewContext<Pane>,
843 ) -> Task<Result<View<Self>>> {
844 let project_item: Result<_> = project.update(cx, |project, cx| {
845 // Look up the path with this key associated, create a self with that path
846 let path = DB
847 .get_path(item_id, workspace_id)?
848 .context("No path stored for this editor")?;
849
850 let (worktree, path) = project
851 .find_local_worktree(&path, cx)
852 .with_context(|| format!("No worktree for path: {path:?}"))?;
853 let project_path = ProjectPath {
854 worktree_id: worktree.read(cx).id(),
855 path: path.into(),
856 };
857
858 Ok(project.open_path(project_path, cx))
859 });
860
861 project_item
862 .map(|project_item| {
863 cx.spawn(|pane, mut cx| async move {
864 let (_, project_item) = project_item.await?;
865 let buffer = project_item
866 .downcast::<Buffer>()
867 .context("Project item at stored path was not a buffer")?;
868 Ok(pane.update(&mut cx, |_, cx| {
869 cx.add_view(|cx| {
870 let mut editor = Editor::for_buffer(buffer, Some(project), cx);
871 editor.read_scroll_position_from_db(item_id, workspace_id, cx);
872 editor
873 })
874 })?)
875 })
876 })
877 .unwrap_or_else(|error| Task::ready(Err(error)))
878 }
879}
880
881impl ProjectItem for Editor {
882 type Item = Buffer;
883
884 fn for_project_item(
885 project: Model<Project>,
886 buffer: Model<Buffer>,
887 cx: &mut ViewContext<Self>,
888 ) -> Self {
889 Self::for_buffer(buffer, Some(project), cx)
890 }
891}
892
893pub(crate) enum BufferSearchHighlights {}
894impl SearchableItem for Editor {
895 type Match = Range<Anchor>;
896
897 fn to_search_event(
898 &mut self,
899 event: &Self::Event,
900 _: &mut ViewContext<Self>,
901 ) -> Option<SearchEvent> {
902 match event {
903 Event::BufferEdited => Some(SearchEvent::MatchesInvalidated),
904 Event::SelectionsChanged { .. } => {
905 if self.selections.disjoint_anchors().len() == 1 {
906 Some(SearchEvent::ActiveMatchChanged)
907 } else {
908 None
909 }
910 }
911 _ => None,
912 }
913 }
914
915 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
916 self.clear_background_highlights::<BufferSearchHighlights>(cx);
917 }
918
919 fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
920 self.highlight_background::<BufferSearchHighlights>(
921 matches,
922 |theme| theme.search.match_background,
923 cx,
924 );
925 }
926
927 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
928 let display_map = self.snapshot(cx).display_snapshot;
929 let selection = self.selections.newest::<usize>(cx);
930 if selection.start == selection.end {
931 let point = selection.start.to_display_point(&display_map);
932 let range = surrounding_word(&display_map, point);
933 let range = range.start.to_offset(&display_map, Bias::Left)
934 ..range.end.to_offset(&display_map, Bias::Right);
935 let text: String = display_map.buffer_snapshot.text_for_range(range).collect();
936 if text.trim().is_empty() {
937 String::new()
938 } else {
939 text
940 }
941 } else {
942 display_map
943 .buffer_snapshot
944 .text_for_range(selection.start..selection.end)
945 .collect()
946 }
947 }
948
949 fn activate_match(
950 &mut self,
951 index: usize,
952 matches: Vec<Range<Anchor>>,
953 cx: &mut ViewContext<Self>,
954 ) {
955 self.unfold_ranges([matches[index].clone()], false, true, cx);
956 let range = self.range_for_match(&matches[index]);
957 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
958 s.select_ranges([range]);
959 })
960 }
961
962 fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
963 self.unfold_ranges(matches.clone(), false, false, cx);
964 let mut ranges = Vec::new();
965 for m in &matches {
966 ranges.push(self.range_for_match(&m))
967 }
968 self.change_selections(None, cx, |s| s.select_ranges(ranges));
969 }
970 fn replace(
971 &mut self,
972 identifier: &Self::Match,
973 query: &SearchQuery,
974 cx: &mut ViewContext<Self>,
975 ) {
976 let text = self.buffer.read(cx);
977 let text = text.snapshot(cx);
978 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
979 let text: Cow<_> = if text.len() == 1 {
980 text.first().cloned().unwrap().into()
981 } else {
982 let joined_chunks = text.join("");
983 joined_chunks.into()
984 };
985
986 if let Some(replacement) = query.replacement_for(&text) {
987 self.transact(cx, |this, cx| {
988 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
989 });
990 }
991 }
992 fn match_index_for_direction(
993 &mut self,
994 matches: &Vec<Range<Anchor>>,
995 current_index: usize,
996 direction: Direction,
997 count: usize,
998 cx: &mut ViewContext<Self>,
999 ) -> usize {
1000 let buffer = self.buffer().read(cx).snapshot(cx);
1001 let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1002 self.selections.newest_anchor().head()
1003 } else {
1004 matches[current_index].start
1005 };
1006
1007 let mut count = count % matches.len();
1008 if count == 0 {
1009 return current_index;
1010 }
1011 match direction {
1012 Direction::Next => {
1013 if matches[current_index]
1014 .start
1015 .cmp(¤t_index_position, &buffer)
1016 .is_gt()
1017 {
1018 count = count - 1
1019 }
1020
1021 (current_index + count) % matches.len()
1022 }
1023 Direction::Prev => {
1024 if matches[current_index]
1025 .end
1026 .cmp(¤t_index_position, &buffer)
1027 .is_lt()
1028 {
1029 count = count - 1;
1030 }
1031
1032 if current_index >= count {
1033 current_index - count
1034 } else {
1035 matches.len() - (count - current_index)
1036 }
1037 }
1038 }
1039 }
1040
1041 fn find_matches(
1042 &mut self,
1043 query: Arc<project::search::SearchQuery>,
1044 cx: &mut ViewContext<Self>,
1045 ) -> Task<Vec<Range<Anchor>>> {
1046 let buffer = self.buffer().read(cx).snapshot(cx);
1047 cx.background().spawn(async move {
1048 let mut ranges = Vec::new();
1049 if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1050 ranges.extend(
1051 query
1052 .search(excerpt_buffer, None)
1053 .await
1054 .into_iter()
1055 .map(|range| {
1056 buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1057 }),
1058 );
1059 } else {
1060 for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1061 let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1062 ranges.extend(
1063 query
1064 .search(&excerpt.buffer, Some(excerpt_range.clone()))
1065 .await
1066 .into_iter()
1067 .map(|range| {
1068 let start = excerpt
1069 .buffer
1070 .anchor_after(excerpt_range.start + range.start);
1071 let end = excerpt
1072 .buffer
1073 .anchor_before(excerpt_range.start + range.end);
1074 buffer.anchor_in_excerpt(excerpt.id.clone(), start)
1075 ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
1076 }),
1077 );
1078 }
1079 }
1080 ranges
1081 })
1082 }
1083
1084 fn active_match_index(
1085 &mut self,
1086 matches: Vec<Range<Anchor>>,
1087 cx: &mut ViewContext<Self>,
1088 ) -> Option<usize> {
1089 active_match_index(
1090 &matches,
1091 &self.selections.newest_anchor().head(),
1092 &self.buffer().read(cx).snapshot(cx),
1093 )
1094 }
1095}
1096
1097pub fn active_match_index(
1098 ranges: &[Range<Anchor>],
1099 cursor: &Anchor,
1100 buffer: &MultiBufferSnapshot,
1101) -> Option<usize> {
1102 if ranges.is_empty() {
1103 None
1104 } else {
1105 match ranges.binary_search_by(|probe| {
1106 if probe.end.cmp(cursor, &*buffer).is_lt() {
1107 Ordering::Less
1108 } else if probe.start.cmp(cursor, &*buffer).is_gt() {
1109 Ordering::Greater
1110 } else {
1111 Ordering::Equal
1112 }
1113 }) {
1114 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1115 }
1116 }
1117}
1118
1119pub struct CursorPosition {
1120 position: Option<Point>,
1121 selected_count: usize,
1122 _observe_active_editor: Option<Subscription>,
1123}
1124
1125// impl Default for CursorPosition {
1126// fn default() -> Self {
1127// Self::new()
1128// }
1129// }
1130
1131// impl CursorPosition {
1132// pub fn new() -> Self {
1133// Self {
1134// position: None,
1135// selected_count: 0,
1136// _observe_active_editor: None,
1137// }
1138// }
1139
1140// fn update_position(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
1141// let editor = editor.read(cx);
1142// let buffer = editor.buffer().read(cx).snapshot(cx);
1143
1144// self.selected_count = 0;
1145// let mut last_selection: Option<Selection<usize>> = None;
1146// for selection in editor.selections.all::<usize>(cx) {
1147// self.selected_count += selection.end - selection.start;
1148// if last_selection
1149// .as_ref()
1150// .map_or(true, |last_selection| selection.id > last_selection.id)
1151// {
1152// last_selection = Some(selection);
1153// }
1154// }
1155// self.position = last_selection.map(|s| s.head().to_point(&buffer));
1156
1157// cx.notify();
1158// }
1159// }
1160
1161// impl Entity for CursorPosition {
1162// type Event = ();
1163// }
1164
1165// impl View for CursorPosition {
1166// fn ui_name() -> &'static str {
1167// "CursorPosition"
1168// }
1169
1170// fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1171// if let Some(position) = self.position {
1172// let theme = &theme::current(cx).workspace.status_bar;
1173// let mut text = format!(
1174// "{}{FILE_ROW_COLUMN_DELIMITER}{}",
1175// position.row + 1,
1176// position.column + 1
1177// );
1178// if self.selected_count > 0 {
1179// write!(text, " ({} selected)", self.selected_count).unwrap();
1180// }
1181// Label::new(text, theme.cursor_position.clone()).into_any()
1182// } else {
1183// Empty::new().into_any()
1184// }
1185// }
1186// }
1187
1188// impl StatusItemView for CursorPosition {
1189// fn set_active_pane_item(
1190// &mut self,
1191// active_pane_item: Option<&dyn ItemHandle>,
1192// cx: &mut ViewContext<Self>,
1193// ) {
1194// if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
1195// self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
1196// self.update_position(editor, cx);
1197// } else {
1198// self.position = None;
1199// self._observe_active_editor = None;
1200// }
1201
1202// cx.notify();
1203// }
1204// }
1205
1206fn path_for_buffer<'a>(
1207 buffer: &Model<MultiBuffer>,
1208 height: usize,
1209 include_filename: bool,
1210 cx: &'a AppContext,
1211) -> Option<Cow<'a, Path>> {
1212 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1213 path_for_file(file.as_ref(), height, include_filename, cx)
1214}
1215
1216fn path_for_file<'a>(
1217 file: &'a dyn language::File,
1218 mut height: usize,
1219 include_filename: bool,
1220 cx: &'a AppContext,
1221) -> Option<Cow<'a, Path>> {
1222 // Ensure we always render at least the filename.
1223 height += 1;
1224
1225 let mut prefix = file.path().as_ref();
1226 while height > 0 {
1227 if let Some(parent) = prefix.parent() {
1228 prefix = parent;
1229 height -= 1;
1230 } else {
1231 break;
1232 }
1233 }
1234
1235 // Here we could have just always used `full_path`, but that is very
1236 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1237 // traversed all the way up to the worktree's root.
1238 if height > 0 {
1239 let full_path = file.full_path(cx);
1240 if include_filename {
1241 Some(full_path.into())
1242 } else {
1243 Some(full_path.parent()?.to_path_buf().into())
1244 }
1245 } else {
1246 let mut path = file.path().strip_prefix(prefix).ok()?;
1247 if !include_filename {
1248 path = path.parent()?;
1249 }
1250 Some(path.into())
1251 }
1252}
1253
1254#[cfg(test)]
1255mod tests {
1256 use super::*;
1257 use gpui::AppContext;
1258 use std::{
1259 path::{Path, PathBuf},
1260 sync::Arc,
1261 time::SystemTime,
1262 };
1263
1264 #[gpui::test]
1265 fn test_path_for_file(cx: &mut AppContext) {
1266 let file = TestFile {
1267 path: Path::new("").into(),
1268 full_path: PathBuf::from(""),
1269 };
1270 assert_eq!(path_for_file(&file, 0, false, cx), None);
1271 }
1272
1273 struct TestFile {
1274 path: Arc<Path>,
1275 full_path: PathBuf,
1276 }
1277
1278 impl language::File for TestFile {
1279 fn path(&self) -> &Arc<Path> {
1280 &self.path
1281 }
1282
1283 fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1284 self.full_path.clone()
1285 }
1286
1287 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1288 unimplemented!()
1289 }
1290
1291 fn mtime(&self) -> SystemTime {
1292 unimplemented!()
1293 }
1294
1295 fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1296 unimplemented!()
1297 }
1298
1299 fn worktree_id(&self) -> usize {
1300 0
1301 }
1302
1303 fn is_deleted(&self) -> bool {
1304 unimplemented!()
1305 }
1306
1307 fn as_any(&self) -> &dyn std::any::Any {
1308 unimplemented!()
1309 }
1310
1311 fn to_proto(&self) -> rpc::proto::File {
1312 unimplemented!()
1313 }
1314 }
1315}