proposed_changes_editor.rs

  1use crate::{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::Project;
  8use smol::stream::StreamExt;
  9use std::{any::TypeId, ops::Range, rc::Rc, time::Duration};
 10use text::ToOffset;
 11use ui::prelude::*;
 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();
 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(|_, 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                    join_all(buffers_to_diff.drain().filter_map(|buffer| {
100                        buffer
101                            .update(&mut cx, |buffer, cx| buffer.recalculate_diff(cx))
102                            .ok()?
103                    }))
104                    .await;
105                }
106                None
107            }),
108        };
109        this.reset_locations(locations, cx);
110        this
111    }
112
113    pub fn branch_buffer_for_base(&self, base_buffer: &Model<Buffer>) -> Option<Model<Buffer>> {
114        self.buffer_entries.iter().find_map(|entry| {
115            if &entry.base == base_buffer {
116                Some(entry.branch.clone())
117            } else {
118                None
119            }
120        })
121    }
122
123    pub fn set_title(&mut self, title: SharedString, cx: &mut ViewContext<Self>) {
124        self.title = title;
125        cx.notify();
126    }
127
128    pub fn reset_locations<T: ToOffset>(
129        &mut self,
130        locations: Vec<ProposedChangeLocation<T>>,
131        cx: &mut ViewContext<Self>,
132    ) {
133        // Undo all branch changes
134        for entry in &self.buffer_entries {
135            let base_version = entry.base.read(cx).version();
136            entry.branch.update(cx, |buffer, cx| {
137                let undo_counts = buffer
138                    .operations()
139                    .iter()
140                    .filter_map(|(timestamp, _)| {
141                        if !base_version.observed(*timestamp) {
142                            Some((*timestamp, u32::MAX))
143                        } else {
144                            None
145                        }
146                    })
147                    .collect();
148                buffer.undo_operations(undo_counts, cx);
149            });
150        }
151
152        self.multibuffer.update(cx, |multibuffer, cx| {
153            multibuffer.clear(cx);
154        });
155
156        let mut buffer_entries = Vec::new();
157        for location in locations {
158            let branch_buffer;
159            if let Some(ix) = self
160                .buffer_entries
161                .iter()
162                .position(|entry| entry.base == location.buffer)
163            {
164                let entry = self.buffer_entries.remove(ix);
165                branch_buffer = entry.branch.clone();
166                buffer_entries.push(entry);
167            } else {
168                branch_buffer = location.buffer.update(cx, |buffer, cx| buffer.branch(cx));
169                buffer_entries.push(BufferEntry {
170                    branch: branch_buffer.clone(),
171                    base: location.buffer.clone(),
172                    _subscription: cx.subscribe(&branch_buffer, Self::on_buffer_event),
173                });
174            }
175
176            self.multibuffer.update(cx, |multibuffer, cx| {
177                multibuffer.push_excerpts(
178                    branch_buffer,
179                    location.ranges.into_iter().map(|range| ExcerptRange {
180                        context: range,
181                        primary: None,
182                    }),
183                    cx,
184                );
185            });
186        }
187
188        self.buffer_entries = buffer_entries;
189        self.editor.update(cx, |editor, cx| {
190            editor.change_selections(None, cx, |selections| selections.refresh())
191        });
192    }
193
194    pub fn recalculate_all_buffer_diffs(&self) {
195        for (ix, entry) in self.buffer_entries.iter().enumerate().rev() {
196            self.recalculate_diffs_tx
197                .unbounded_send(RecalculateDiff {
198                    buffer: entry.branch.clone(),
199                    debounce: ix > 0,
200                })
201                .ok();
202        }
203    }
204
205    fn on_buffer_event(
206        &mut self,
207        buffer: Model<Buffer>,
208        event: &BufferEvent,
209        _cx: &mut ViewContext<Self>,
210    ) {
211        match event {
212            BufferEvent::Operation { .. } => {
213                self.recalculate_diffs_tx
214                    .unbounded_send(RecalculateDiff {
215                        buffer,
216                        debounce: true,
217                    })
218                    .ok();
219            }
220            BufferEvent::DiffBaseChanged => {
221                self.recalculate_diffs_tx
222                    .unbounded_send(RecalculateDiff {
223                        buffer,
224                        debounce: false,
225                    })
226                    .ok();
227            }
228            _ => (),
229        }
230    }
231}
232
233impl Render for ProposedChangesEditor {
234    fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
235        self.editor.clone()
236    }
237}
238
239impl FocusableView for ProposedChangesEditor {
240    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
241        self.editor.focus_handle(cx)
242    }
243}
244
245impl EventEmitter<EditorEvent> for ProposedChangesEditor {}
246
247impl Item for ProposedChangesEditor {
248    type Event = EditorEvent;
249
250    fn tab_icon(&self, _cx: &ui::WindowContext) -> Option<Icon> {
251        Some(Icon::new(IconName::Diff))
252    }
253
254    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
255        Some(self.title.clone())
256    }
257
258    fn as_searchable(&self, _: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
259        Some(Box::new(self.editor.clone()))
260    }
261
262    fn act_as_type<'a>(
263        &'a self,
264        type_id: TypeId,
265        self_handle: &'a View<Self>,
266        _: &'a AppContext,
267    ) -> Option<gpui::AnyView> {
268        if type_id == TypeId::of::<Self>() {
269            Some(self_handle.to_any())
270        } else if type_id == TypeId::of::<Editor>() {
271            Some(self.editor.to_any())
272        } else {
273            None
274        }
275    }
276
277    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
278        self.editor.update(cx, |editor, cx| {
279            Item::added_to_workspace(editor, workspace, cx)
280        });
281    }
282
283    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
284        self.editor.update(cx, Item::deactivated);
285    }
286
287    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
288        self.editor
289            .update(cx, |editor, cx| Item::navigate(editor, data, cx))
290    }
291
292    fn set_nav_history(
293        &mut self,
294        nav_history: workspace::ItemNavHistory,
295        cx: &mut ViewContext<Self>,
296    ) {
297        self.editor.update(cx, |editor, cx| {
298            Item::set_nav_history(editor, nav_history, cx)
299        });
300    }
301}
302
303impl ProposedChangesEditorToolbar {
304    pub fn new() -> Self {
305        Self {
306            current_editor: None,
307        }
308    }
309
310    fn get_toolbar_item_location(&self) -> ToolbarItemLocation {
311        if self.current_editor.is_some() {
312            ToolbarItemLocation::PrimaryRight
313        } else {
314            ToolbarItemLocation::Hidden
315        }
316    }
317}
318
319impl Render for ProposedChangesEditorToolbar {
320    fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
321        let editor = self.current_editor.clone();
322        Button::new("apply-changes", "Apply All").on_click(move |_, cx| {
323            if let Some(editor) = &editor {
324                editor.update(cx, |editor, cx| {
325                    editor.editor.update(cx, |editor, cx| {
326                        editor.apply_all_changes(cx);
327                    })
328                });
329            }
330        })
331    }
332}
333
334impl EventEmitter<ToolbarItemEvent> for ProposedChangesEditorToolbar {}
335
336impl ToolbarItemView for ProposedChangesEditorToolbar {
337    fn set_active_pane_item(
338        &mut self,
339        active_pane_item: Option<&dyn workspace::ItemHandle>,
340        _cx: &mut ViewContext<Self>,
341    ) -> workspace::ToolbarItemLocation {
342        self.current_editor =
343            active_pane_item.and_then(|item| item.downcast::<ProposedChangesEditor>());
344        self.get_toolbar_item_location()
345    }
346}
347
348impl BranchBufferSemanticsProvider {
349    fn to_base(
350        &self,
351        buffer: &Model<Buffer>,
352        positions: &[text::Anchor],
353        cx: &AppContext,
354    ) -> Option<Model<Buffer>> {
355        let base_buffer = buffer.read(cx).diff_base_buffer()?;
356        let version = base_buffer.read(cx).version();
357        if positions
358            .iter()
359            .any(|position| !version.observed(position.timestamp))
360        {
361            return None;
362        }
363        Some(base_buffer)
364    }
365}
366
367impl SemanticsProvider for BranchBufferSemanticsProvider {
368    fn hover(
369        &self,
370        buffer: &Model<Buffer>,
371        position: text::Anchor,
372        cx: &mut AppContext,
373    ) -> Option<Task<Vec<project::Hover>>> {
374        let buffer = self.to_base(buffer, &[position], cx)?;
375        self.0.hover(&buffer, position, cx)
376    }
377
378    fn inlay_hints(
379        &self,
380        buffer: Model<Buffer>,
381        range: Range<text::Anchor>,
382        cx: &mut AppContext,
383    ) -> Option<Task<anyhow::Result<Vec<project::InlayHint>>>> {
384        let buffer = self.to_base(&buffer, &[range.start, range.end], cx)?;
385        self.0.inlay_hints(buffer, range, cx)
386    }
387
388    fn resolve_inlay_hint(
389        &self,
390        hint: project::InlayHint,
391        buffer: Model<Buffer>,
392        server_id: lsp::LanguageServerId,
393        cx: &mut AppContext,
394    ) -> Option<Task<anyhow::Result<project::InlayHint>>> {
395        let buffer = self.to_base(&buffer, &[], cx)?;
396        self.0.resolve_inlay_hint(hint, buffer, server_id, cx)
397    }
398
399    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
400        if let Some(buffer) = self.to_base(&buffer, &[], cx) {
401            self.0.supports_inlay_hints(&buffer, cx)
402        } else {
403            false
404        }
405    }
406
407    fn document_highlights(
408        &self,
409        buffer: &Model<Buffer>,
410        position: text::Anchor,
411        cx: &mut AppContext,
412    ) -> Option<Task<gpui::Result<Vec<project::DocumentHighlight>>>> {
413        let buffer = self.to_base(&buffer, &[position], cx)?;
414        self.0.document_highlights(&buffer, position, cx)
415    }
416
417    fn definitions(
418        &self,
419        buffer: &Model<Buffer>,
420        position: text::Anchor,
421        kind: crate::GotoDefinitionKind,
422        cx: &mut AppContext,
423    ) -> Option<Task<gpui::Result<Vec<project::LocationLink>>>> {
424        let buffer = self.to_base(&buffer, &[position], cx)?;
425        self.0.definitions(&buffer, position, kind, cx)
426    }
427
428    fn range_for_rename(
429        &self,
430        _: &Model<Buffer>,
431        _: text::Anchor,
432        _: &mut AppContext,
433    ) -> Option<Task<gpui::Result<Option<Range<text::Anchor>>>>> {
434        None
435    }
436
437    fn perform_rename(
438        &self,
439        _: &Model<Buffer>,
440        _: text::Anchor,
441        _: String,
442        _: &mut AppContext,
443    ) -> Option<Task<gpui::Result<project::ProjectTransaction>>> {
444        None
445    }
446}