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