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