proposed_changes_editor.rs

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