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