proposed_changes_editor.rs

  1use crate::{ApplyAllDiffHunks, Editor, EditorEvent, SelectionEffects, SemanticsProvider};
  2use buffer_diff::BufferDiff;
  3use collections::HashSet;
  4use futures::{channel::mpsc, future::join_all};
  5use gpui::{App, Entity, EventEmitter, Focusable, Render, Subscription, Task};
  6use language::{Buffer, BufferEvent, Capability};
  7use multi_buffer::{ExcerptRange, MultiBuffer};
  8use project::Project;
  9use smol::stream::StreamExt;
 10use std::{any::TypeId, ops::Range, rc::Rc, time::Duration};
 11use text::ToOffset;
 12use ui::{ButtonLike, KeyBinding, prelude::*};
 13use workspace::{
 14    Item, ItemHandle as _, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
 15    item::SaveOptions, searchable::SearchableItemHandle,
 16};
 17
 18pub struct ProposedChangesEditor {
 19    editor: Entity<Editor>,
 20    multibuffer: Entity<MultiBuffer>,
 21    title: SharedString,
 22    buffer_entries: Vec<BufferEntry>,
 23    _recalculate_diffs_task: Task<Option<()>>,
 24    recalculate_diffs_tx: mpsc::UnboundedSender<RecalculateDiff>,
 25}
 26
 27pub struct ProposedChangeLocation<T> {
 28    pub buffer: Entity<Buffer>,
 29    pub ranges: Vec<Range<T>>,
 30}
 31
 32struct BufferEntry {
 33    base: Entity<Buffer>,
 34    branch: Entity<Buffer>,
 35    _subscription: Subscription,
 36}
 37
 38pub struct ProposedChangesEditorToolbar {
 39    current_editor: Option<Entity<ProposedChangesEditor>>,
 40}
 41
 42struct RecalculateDiff {
 43    buffer: Entity<Buffer>,
 44    debounce: bool,
 45}
 46
 47/// A provider of code semantics for branch buffers.
 48///
 49/// Requests in edited regions will return nothing, but requests in unchanged
 50/// regions will be translated into the base buffer's coordinates.
 51struct BranchBufferSemanticsProvider(Rc<dyn SemanticsProvider>);
 52
 53impl ProposedChangesEditor {
 54    pub fn new<T: Clone + ToOffset>(
 55        title: impl Into<SharedString>,
 56        locations: Vec<ProposedChangeLocation<T>>,
 57        project: Option<Entity<Project>>,
 58        window: &mut Window,
 59        cx: &mut Context<Self>,
 60    ) -> Self {
 61        let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 62        let (recalculate_diffs_tx, mut recalculate_diffs_rx) = mpsc::unbounded();
 63        let mut this = Self {
 64            editor: cx.new(|cx| {
 65                let mut editor = Editor::for_multibuffer(multibuffer.clone(), project, 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, async move |this, cx| {
 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(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 diff =
110                                        this.multibuffer.read(cx).diff_for(buffer.remote_id())?;
111                                    Some(diff.update(cx, |diff, cx| {
112                                        diff.set_base_text_buffer(base_buffer.clone(), buffer, cx)
113                                    }))
114                                })
115                                .collect::<Vec<_>>()
116                        })
117                        .ok()?;
118
119                    join_all(recalculate_diff_futures).await;
120                }
121                None
122            }),
123        };
124        this.reset_locations(locations, window, cx);
125        this
126    }
127
128    pub fn branch_buffer_for_base(&self, base_buffer: &Entity<Buffer>) -> Option<Entity<Buffer>> {
129        self.buffer_entries.iter().find_map(|entry| {
130            if &entry.base == base_buffer {
131                Some(entry.branch.clone())
132            } else {
133                None
134            }
135        })
136    }
137
138    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
139        self.title = title;
140        cx.notify();
141    }
142
143    pub fn reset_locations<T: Clone + ToOffset>(
144        &mut self,
145        locations: Vec<ProposedChangeLocation<T>>,
146        window: &mut Window,
147        cx: &mut Context<Self>,
148    ) {
149        // Undo all branch changes
150        for entry in &self.buffer_entries {
151            let base_version = entry.base.read(cx).version();
152            entry.branch.update(cx, |buffer, cx| {
153                let undo_counts = buffer
154                    .operations()
155                    .iter()
156                    .filter_map(|(timestamp, _)| {
157                        if !base_version.observed(*timestamp) {
158                            Some((*timestamp, u32::MAX))
159                        } else {
160                            None
161                        }
162                    })
163                    .collect();
164                buffer.undo_operations(undo_counts, cx);
165            });
166        }
167
168        self.multibuffer.update(cx, |multibuffer, cx| {
169            multibuffer.clear(cx);
170        });
171
172        let mut buffer_entries = Vec::new();
173        let mut new_diffs = Vec::new();
174        for location in locations {
175            let branch_buffer;
176            if let Some(ix) = self
177                .buffer_entries
178                .iter()
179                .position(|entry| entry.base == location.buffer)
180            {
181                let entry = self.buffer_entries.remove(ix);
182                branch_buffer = entry.branch.clone();
183                buffer_entries.push(entry);
184            } else {
185                branch_buffer = location.buffer.update(cx, |buffer, cx| buffer.branch(cx));
186                new_diffs.push(cx.new(|cx| {
187                    let mut diff = BufferDiff::new(&branch_buffer.read(cx).snapshot(), cx);
188                    let _ = diff.set_base_text_buffer(
189                        location.buffer.clone(),
190                        branch_buffer.read(cx).text_snapshot(),
191                        cx,
192                    );
193                    diff
194                }));
195                buffer_entries.push(BufferEntry {
196                    branch: branch_buffer.clone(),
197                    base: location.buffer.clone(),
198                    _subscription: cx.subscribe(&branch_buffer, Self::on_buffer_event),
199                });
200            }
201
202            self.multibuffer.update(cx, |multibuffer, cx| {
203                multibuffer.push_excerpts(
204                    branch_buffer,
205                    location
206                        .ranges
207                        .into_iter()
208                        .map(|range| ExcerptRange::new(range)),
209                    cx,
210                );
211            });
212        }
213
214        self.buffer_entries = buffer_entries;
215        self.editor.update(cx, |editor, cx| {
216            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
217                selections.refresh()
218            });
219            editor.buffer.update(cx, |buffer, cx| {
220                for diff in new_diffs {
221                    buffer.add_diff(diff, 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, _detail: usize, _cx: &App) -> SharedString {
291        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        options: SaveOptions,
357        project: Entity<Project>,
358        window: &mut Window,
359        cx: &mut Context<Self>,
360    ) -> Task<anyhow::Result<()>> {
361        self.editor.update(cx, |editor, cx| {
362            Item::save(editor, options, 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, cx)
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 inline_values(
461        &self,
462        _: Entity<Buffer>,
463        _: Range<text::Anchor>,
464        _: &mut App,
465    ) -> Option<Task<anyhow::Result<Vec<project::InlayHint>>>> {
466        None
467    }
468
469    fn resolve_inlay_hint(
470        &self,
471        hint: project::InlayHint,
472        buffer: Entity<Buffer>,
473        server_id: lsp::LanguageServerId,
474        cx: &mut App,
475    ) -> Option<Task<anyhow::Result<project::InlayHint>>> {
476        let buffer = self.to_base(&buffer, &[], cx)?;
477        self.0.resolve_inlay_hint(hint, buffer, server_id, cx)
478    }
479
480    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
481        if let Some(buffer) = self.to_base(buffer, &[], cx) {
482            self.0.supports_inlay_hints(&buffer, cx)
483        } else {
484            false
485        }
486    }
487
488    fn document_highlights(
489        &self,
490        buffer: &Entity<Buffer>,
491        position: text::Anchor,
492        cx: &mut App,
493    ) -> Option<Task<anyhow::Result<Vec<project::DocumentHighlight>>>> {
494        let buffer = self.to_base(buffer, &[position], cx)?;
495        self.0.document_highlights(&buffer, position, cx)
496    }
497
498    fn definitions(
499        &self,
500        buffer: &Entity<Buffer>,
501        position: text::Anchor,
502        kind: crate::GotoDefinitionKind,
503        cx: &mut App,
504    ) -> Option<Task<anyhow::Result<Vec<project::LocationLink>>>> {
505        let buffer = self.to_base(buffer, &[position], cx)?;
506        self.0.definitions(&buffer, position, kind, cx)
507    }
508
509    fn range_for_rename(
510        &self,
511        _: &Entity<Buffer>,
512        _: text::Anchor,
513        _: &mut App,
514    ) -> Option<Task<anyhow::Result<Option<Range<text::Anchor>>>>> {
515        None
516    }
517
518    fn perform_rename(
519        &self,
520        _: &Entity<Buffer>,
521        _: text::Anchor,
522        _: String,
523        _: &mut App,
524    ) -> Option<Task<anyhow::Result<project::ProjectTransaction>>> {
525        None
526    }
527}