proposed_changes_editor.rs

  1use crate::{ApplyAllDiffHunks, Editor, EditorEvent, SemanticsProvider};
  2use collections::HashSet;
  3use futures::{channel::mpsc, future::join_all};
  4use gpui::{App, Entity, EventEmitter, Focusable, Render, Subscription, Task};
  5use language::{Buffer, BufferEvent, Capability};
  6use multi_buffer::{ExcerptRange, MultiBuffer};
  7use project::{buffer_store::BufferChangeSet, Project};
  8use smol::stream::StreamExt;
  9use std::{any::TypeId, ops::Range, rc::Rc, time::Duration};
 10use text::ToOffset;
 11use ui::{prelude::*, ButtonLike, KeyBinding};
 12use workspace::{
 13    searchable::SearchableItemHandle, Item, ItemHandle as _, ToolbarItemEvent, ToolbarItemLocation,
 14    ToolbarItemView, Workspace,
 15};
 16
 17pub struct ProposedChangesEditor {
 18    editor: Entity<Editor>,
 19    multibuffer: Entity<MultiBuffer>,
 20    title: SharedString,
 21    buffer_entries: Vec<BufferEntry>,
 22    _recalculate_diffs_task: Task<Option<()>>,
 23    recalculate_diffs_tx: mpsc::UnboundedSender<RecalculateDiff>,
 24}
 25
 26pub struct ProposedChangeLocation<T> {
 27    pub buffer: Entity<Buffer>,
 28    pub ranges: Vec<Range<T>>,
 29}
 30
 31struct BufferEntry {
 32    base: Entity<Buffer>,
 33    branch: Entity<Buffer>,
 34    _subscription: Subscription,
 35}
 36
 37pub struct ProposedChangesEditorToolbar {
 38    current_editor: Option<Entity<ProposedChangesEditor>>,
 39}
 40
 41struct RecalculateDiff {
 42    buffer: Entity<Buffer>,
 43    debounce: bool,
 44}
 45
 46/// A provider of code semantics for branch buffers.
 47///
 48/// Requests in edited regions will return nothing, but requests in unchanged
 49/// regions will be translated into the base buffer's coordinates.
 50struct BranchBufferSemanticsProvider(Rc<dyn SemanticsProvider>);
 51
 52impl ProposedChangesEditor {
 53    pub fn new<T: ToOffset>(
 54        title: impl Into<SharedString>,
 55        locations: Vec<ProposedChangeLocation<T>>,
 56        project: Option<Entity<Project>>,
 57        window: &mut Window,
 58        cx: &mut Context<Self>,
 59    ) -> Self {
 60        let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 61        let (recalculate_diffs_tx, mut recalculate_diffs_rx) = mpsc::unbounded();
 62        let mut this = Self {
 63            editor: cx.new(|cx| {
 64                let mut editor =
 65                    Editor::for_multibuffer(multibuffer.clone(), project, true, window, cx);
 66                editor.set_expand_all_diff_hunks(cx);
 67                editor.set_completion_provider(None);
 68                editor.clear_code_action_providers();
 69                editor.set_semantics_provider(
 70                    editor
 71                        .semantics_provider()
 72                        .map(|provider| Rc::new(BranchBufferSemanticsProvider(provider)) as _),
 73                );
 74                editor
 75            }),
 76            multibuffer,
 77            title: title.into(),
 78            buffer_entries: Vec::new(),
 79            recalculate_diffs_tx,
 80            _recalculate_diffs_task: cx.spawn_in(window, |this, mut cx| async move {
 81                let mut buffers_to_diff = HashSet::default();
 82                while let Some(mut recalculate_diff) = recalculate_diffs_rx.next().await {
 83                    buffers_to_diff.insert(recalculate_diff.buffer);
 84
 85                    while recalculate_diff.debounce {
 86                        cx.background_executor()
 87                            .timer(Duration::from_millis(50))
 88                            .await;
 89                        let mut had_further_changes = false;
 90                        while let Ok(next_recalculate_diff) = recalculate_diffs_rx.try_next() {
 91                            let next_recalculate_diff = next_recalculate_diff?;
 92                            recalculate_diff.debounce &= next_recalculate_diff.debounce;
 93                            buffers_to_diff.insert(next_recalculate_diff.buffer);
 94                            had_further_changes = true;
 95                        }
 96                        if !had_further_changes {
 97                            break;
 98                        }
 99                    }
100
101                    let recalculate_diff_futures = this
102                        .update(&mut cx, |this, cx| {
103                            buffers_to_diff
104                                .drain()
105                                .filter_map(|buffer| {
106                                    let buffer = buffer.read(cx);
107                                    let base_buffer = buffer.base_buffer()?;
108                                    let buffer = buffer.text_snapshot();
109                                    let change_set = this
110                                        .multibuffer
111                                        .read(cx)
112                                        .change_set_for(buffer.remote_id())?;
113                                    Some(change_set.update(cx, |change_set, cx| {
114                                        change_set.set_base_text(base_buffer.clone(), buffer, cx)
115                                    }))
116                                })
117                                .collect::<Vec<_>>()
118                        })
119                        .ok()?;
120
121                    join_all(recalculate_diff_futures).await;
122                }
123                None
124            }),
125        };
126        this.reset_locations(locations, window, cx);
127        this
128    }
129
130    pub fn branch_buffer_for_base(&self, base_buffer: &Entity<Buffer>) -> Option<Entity<Buffer>> {
131        self.buffer_entries.iter().find_map(|entry| {
132            if &entry.base == base_buffer {
133                Some(entry.branch.clone())
134            } else {
135                None
136            }
137        })
138    }
139
140    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
141        self.title = title;
142        cx.notify();
143    }
144
145    pub fn reset_locations<T: ToOffset>(
146        &mut self,
147        locations: Vec<ProposedChangeLocation<T>>,
148        window: &mut Window,
149        cx: &mut Context<Self>,
150    ) {
151        // Undo all branch changes
152        for entry in &self.buffer_entries {
153            let base_version = entry.base.read(cx).version();
154            entry.branch.update(cx, |buffer, cx| {
155                let undo_counts = buffer
156                    .operations()
157                    .iter()
158                    .filter_map(|(timestamp, _)| {
159                        if !base_version.observed(*timestamp) {
160                            Some((*timestamp, u32::MAX))
161                        } else {
162                            None
163                        }
164                    })
165                    .collect();
166                buffer.undo_operations(undo_counts, cx);
167            });
168        }
169
170        self.multibuffer.update(cx, |multibuffer, cx| {
171            multibuffer.clear(cx);
172        });
173
174        let mut buffer_entries = Vec::new();
175        let mut new_change_sets = Vec::new();
176        for location in locations {
177            let branch_buffer;
178            if let Some(ix) = self
179                .buffer_entries
180                .iter()
181                .position(|entry| entry.base == location.buffer)
182            {
183                let entry = self.buffer_entries.remove(ix);
184                branch_buffer = entry.branch.clone();
185                buffer_entries.push(entry);
186            } else {
187                branch_buffer = location.buffer.update(cx, |buffer, cx| buffer.branch(cx));
188                new_change_sets.push(cx.new(|cx| {
189                    let mut change_set = BufferChangeSet::new(&branch_buffer, cx);
190                    let _ = change_set.set_base_text(
191                        location.buffer.clone(),
192                        branch_buffer.read(cx).text_snapshot(),
193                        cx,
194                    );
195                    change_set
196                }));
197                buffer_entries.push(BufferEntry {
198                    branch: branch_buffer.clone(),
199                    base: location.buffer.clone(),
200                    _subscription: cx.subscribe(&branch_buffer, Self::on_buffer_event),
201                });
202            }
203
204            self.multibuffer.update(cx, |multibuffer, cx| {
205                multibuffer.push_excerpts(
206                    branch_buffer,
207                    location.ranges.into_iter().map(|range| ExcerptRange {
208                        context: range,
209                        primary: None,
210                    }),
211                    cx,
212                );
213            });
214        }
215
216        self.buffer_entries = buffer_entries;
217        self.editor.update(cx, |editor, cx| {
218            editor.change_selections(None, window, cx, |selections| selections.refresh());
219            editor.buffer.update(cx, |buffer, cx| {
220                for change_set in new_change_sets {
221                    buffer.add_change_set(change_set, cx)
222                }
223            })
224        });
225    }
226
227    pub fn recalculate_all_buffer_diffs(&self) {
228        for (ix, entry) in self.buffer_entries.iter().enumerate().rev() {
229            self.recalculate_diffs_tx
230                .unbounded_send(RecalculateDiff {
231                    buffer: entry.branch.clone(),
232                    debounce: ix > 0,
233                })
234                .ok();
235        }
236    }
237
238    fn on_buffer_event(
239        &mut self,
240        buffer: Entity<Buffer>,
241        event: &BufferEvent,
242        _cx: &mut Context<Self>,
243    ) {
244        match event {
245            BufferEvent::Operation { .. } => {
246                self.recalculate_diffs_tx
247                    .unbounded_send(RecalculateDiff {
248                        buffer,
249                        debounce: true,
250                    })
251                    .ok();
252            }
253            // BufferEvent::DiffBaseChanged => {
254            //     self.recalculate_diffs_tx
255            //         .unbounded_send(RecalculateDiff {
256            //             buffer,
257            //             debounce: false,
258            //         })
259            //         .ok();
260            // }
261            _ => (),
262        }
263    }
264}
265
266impl Render for ProposedChangesEditor {
267    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
268        div()
269            .size_full()
270            .key_context("ProposedChangesEditor")
271            .child(self.editor.clone())
272    }
273}
274
275impl Focusable for ProposedChangesEditor {
276    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
277        self.editor.focus_handle(cx)
278    }
279}
280
281impl EventEmitter<EditorEvent> for ProposedChangesEditor {}
282
283impl Item for ProposedChangesEditor {
284    type Event = EditorEvent;
285
286    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
287        Some(Icon::new(IconName::Diff))
288    }
289
290    fn tab_content_text(&self, _window: &Window, _cx: &App) -> Option<SharedString> {
291        Some(self.title.clone())
292    }
293
294    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
295        Some(Box::new(self.editor.clone()))
296    }
297
298    fn act_as_type<'a>(
299        &'a self,
300        type_id: TypeId,
301        self_handle: &'a Entity<Self>,
302        _: &'a App,
303    ) -> Option<gpui::AnyView> {
304        if type_id == TypeId::of::<Self>() {
305            Some(self_handle.to_any())
306        } else if type_id == TypeId::of::<Editor>() {
307            Some(self.editor.to_any())
308        } else {
309            None
310        }
311    }
312
313    fn added_to_workspace(
314        &mut self,
315        workspace: &mut Workspace,
316        window: &mut Window,
317        cx: &mut Context<Self>,
318    ) {
319        self.editor.update(cx, |editor, cx| {
320            Item::added_to_workspace(editor, workspace, window, cx)
321        });
322    }
323
324    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
325        self.editor
326            .update(cx, |editor, cx| editor.deactivated(window, cx));
327    }
328
329    fn navigate(
330        &mut self,
331        data: Box<dyn std::any::Any>,
332        window: &mut Window,
333        cx: &mut Context<Self>,
334    ) -> bool {
335        self.editor
336            .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
337    }
338
339    fn set_nav_history(
340        &mut self,
341        nav_history: workspace::ItemNavHistory,
342        window: &mut Window,
343        cx: &mut Context<Self>,
344    ) {
345        self.editor.update(cx, |editor, cx| {
346            Item::set_nav_history(editor, nav_history, window, cx)
347        });
348    }
349
350    fn can_save(&self, cx: &App) -> bool {
351        self.editor.read(cx).can_save(cx)
352    }
353
354    fn save(
355        &mut self,
356        format: bool,
357        project: Entity<Project>,
358        window: &mut Window,
359        cx: &mut Context<Self>,
360    ) -> Task<gpui::Result<()>> {
361        self.editor.update(cx, |editor, cx| {
362            Item::save(editor, format, project, window, cx)
363        })
364    }
365}
366
367impl ProposedChangesEditorToolbar {
368    pub fn new() -> Self {
369        Self {
370            current_editor: None,
371        }
372    }
373
374    fn get_toolbar_item_location(&self) -> ToolbarItemLocation {
375        if self.current_editor.is_some() {
376            ToolbarItemLocation::PrimaryRight
377        } else {
378            ToolbarItemLocation::Hidden
379        }
380    }
381}
382
383impl Render for ProposedChangesEditorToolbar {
384    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
385        let button_like = ButtonLike::new("apply-changes").child(Label::new("Apply All"));
386
387        match &self.current_editor {
388            Some(editor) => {
389                let focus_handle = editor.focus_handle(cx);
390                let keybinding =
391                    KeyBinding::for_action_in(&ApplyAllDiffHunks, &focus_handle, window)
392                        .map(|binding| binding.into_any_element());
393
394                button_like.children(keybinding).on_click({
395                    move |_event, window, cx| {
396                        focus_handle.dispatch_action(&ApplyAllDiffHunks, window, cx)
397                    }
398                })
399            }
400            None => button_like.disabled(true),
401        }
402    }
403}
404
405impl EventEmitter<ToolbarItemEvent> for ProposedChangesEditorToolbar {}
406
407impl ToolbarItemView for ProposedChangesEditorToolbar {
408    fn set_active_pane_item(
409        &mut self,
410        active_pane_item: Option<&dyn workspace::ItemHandle>,
411        _window: &mut Window,
412        _cx: &mut Context<Self>,
413    ) -> workspace::ToolbarItemLocation {
414        self.current_editor =
415            active_pane_item.and_then(|item| item.downcast::<ProposedChangesEditor>());
416        self.get_toolbar_item_location()
417    }
418}
419
420impl BranchBufferSemanticsProvider {
421    fn to_base(
422        &self,
423        buffer: &Entity<Buffer>,
424        positions: &[text::Anchor],
425        cx: &App,
426    ) -> Option<Entity<Buffer>> {
427        let base_buffer = buffer.read(cx).base_buffer()?;
428        let version = base_buffer.read(cx).version();
429        if positions
430            .iter()
431            .any(|position| !version.observed(position.timestamp))
432        {
433            return None;
434        }
435        Some(base_buffer)
436    }
437}
438
439impl SemanticsProvider for BranchBufferSemanticsProvider {
440    fn hover(
441        &self,
442        buffer: &Entity<Buffer>,
443        position: text::Anchor,
444        cx: &mut App,
445    ) -> Option<Task<Vec<project::Hover>>> {
446        let buffer = self.to_base(buffer, &[position], cx)?;
447        self.0.hover(&buffer, position, cx)
448    }
449
450    fn inlay_hints(
451        &self,
452        buffer: Entity<Buffer>,
453        range: Range<text::Anchor>,
454        cx: &mut App,
455    ) -> Option<Task<anyhow::Result<Vec<project::InlayHint>>>> {
456        let buffer = self.to_base(&buffer, &[range.start, range.end], cx)?;
457        self.0.inlay_hints(buffer, range, cx)
458    }
459
460    fn resolve_inlay_hint(
461        &self,
462        hint: project::InlayHint,
463        buffer: Entity<Buffer>,
464        server_id: lsp::LanguageServerId,
465        cx: &mut App,
466    ) -> Option<Task<anyhow::Result<project::InlayHint>>> {
467        let buffer = self.to_base(&buffer, &[], cx)?;
468        self.0.resolve_inlay_hint(hint, buffer, server_id, cx)
469    }
470
471    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
472        if let Some(buffer) = self.to_base(&buffer, &[], cx) {
473            self.0.supports_inlay_hints(&buffer, cx)
474        } else {
475            false
476        }
477    }
478
479    fn document_highlights(
480        &self,
481        buffer: &Entity<Buffer>,
482        position: text::Anchor,
483        cx: &mut App,
484    ) -> Option<Task<gpui::Result<Vec<project::DocumentHighlight>>>> {
485        let buffer = self.to_base(&buffer, &[position], cx)?;
486        self.0.document_highlights(&buffer, position, cx)
487    }
488
489    fn definitions(
490        &self,
491        buffer: &Entity<Buffer>,
492        position: text::Anchor,
493        kind: crate::GotoDefinitionKind,
494        cx: &mut App,
495    ) -> Option<Task<gpui::Result<Vec<project::LocationLink>>>> {
496        let buffer = self.to_base(&buffer, &[position], cx)?;
497        self.0.definitions(&buffer, position, kind, cx)
498    }
499
500    fn range_for_rename(
501        &self,
502        _: &Entity<Buffer>,
503        _: text::Anchor,
504        _: &mut App,
505    ) -> Option<Task<gpui::Result<Option<Range<text::Anchor>>>>> {
506        None
507    }
508
509    fn perform_rename(
510        &self,
511        _: &Entity<Buffer>,
512        _: text::Anchor,
513        _: String,
514        _: &mut App,
515    ) -> Option<Task<gpui::Result<project::ProjectTransaction>>> {
516        None
517    }
518}