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    fn can_save(&self, cx: &AppContext) -> bool {
303        self.editor.read(cx).can_save(cx)
304    }
305
306    fn save(
307        &mut self,
308        format: bool,
309        project: Model<Project>,
310        cx: &mut ViewContext<Self>,
311    ) -> Task<gpui::Result<()>> {
312        self.editor
313            .update(cx, |editor, cx| Item::save(editor, format, project, cx))
314    }
315}
316
317impl ProposedChangesEditorToolbar {
318    pub fn new() -> Self {
319        Self {
320            current_editor: None,
321        }
322    }
323
324    fn get_toolbar_item_location(&self) -> ToolbarItemLocation {
325        if self.current_editor.is_some() {
326            ToolbarItemLocation::PrimaryRight
327        } else {
328            ToolbarItemLocation::Hidden
329        }
330    }
331}
332
333impl Render for ProposedChangesEditorToolbar {
334    fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
335        let editor = self.current_editor.clone();
336        Button::new("apply-changes", "Apply All").on_click(move |_, cx| {
337            if let Some(editor) = &editor {
338                editor.update(cx, |editor, cx| {
339                    editor.editor.update(cx, |editor, cx| {
340                        editor.apply_all_diff_hunks(cx);
341                    })
342                });
343            }
344        })
345    }
346}
347
348impl EventEmitter<ToolbarItemEvent> for ProposedChangesEditorToolbar {}
349
350impl ToolbarItemView for ProposedChangesEditorToolbar {
351    fn set_active_pane_item(
352        &mut self,
353        active_pane_item: Option<&dyn workspace::ItemHandle>,
354        _cx: &mut ViewContext<Self>,
355    ) -> workspace::ToolbarItemLocation {
356        self.current_editor =
357            active_pane_item.and_then(|item| item.downcast::<ProposedChangesEditor>());
358        self.get_toolbar_item_location()
359    }
360}
361
362impl BranchBufferSemanticsProvider {
363    fn to_base(
364        &self,
365        buffer: &Model<Buffer>,
366        positions: &[text::Anchor],
367        cx: &AppContext,
368    ) -> Option<Model<Buffer>> {
369        let base_buffer = buffer.read(cx).diff_base_buffer()?;
370        let version = base_buffer.read(cx).version();
371        if positions
372            .iter()
373            .any(|position| !version.observed(position.timestamp))
374        {
375            return None;
376        }
377        Some(base_buffer)
378    }
379}
380
381impl SemanticsProvider for BranchBufferSemanticsProvider {
382    fn hover(
383        &self,
384        buffer: &Model<Buffer>,
385        position: text::Anchor,
386        cx: &mut AppContext,
387    ) -> Option<Task<Vec<project::Hover>>> {
388        let buffer = self.to_base(buffer, &[position], cx)?;
389        self.0.hover(&buffer, position, cx)
390    }
391
392    fn inlay_hints(
393        &self,
394        buffer: Model<Buffer>,
395        range: Range<text::Anchor>,
396        cx: &mut AppContext,
397    ) -> Option<Task<anyhow::Result<Vec<project::InlayHint>>>> {
398        let buffer = self.to_base(&buffer, &[range.start, range.end], cx)?;
399        self.0.inlay_hints(buffer, range, cx)
400    }
401
402    fn resolve_inlay_hint(
403        &self,
404        hint: project::InlayHint,
405        buffer: Model<Buffer>,
406        server_id: lsp::LanguageServerId,
407        cx: &mut AppContext,
408    ) -> Option<Task<anyhow::Result<project::InlayHint>>> {
409        let buffer = self.to_base(&buffer, &[], cx)?;
410        self.0.resolve_inlay_hint(hint, buffer, server_id, cx)
411    }
412
413    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
414        if let Some(buffer) = self.to_base(&buffer, &[], cx) {
415            self.0.supports_inlay_hints(&buffer, cx)
416        } else {
417            false
418        }
419    }
420
421    fn document_highlights(
422        &self,
423        buffer: &Model<Buffer>,
424        position: text::Anchor,
425        cx: &mut AppContext,
426    ) -> Option<Task<gpui::Result<Vec<project::DocumentHighlight>>>> {
427        let buffer = self.to_base(&buffer, &[position], cx)?;
428        self.0.document_highlights(&buffer, position, cx)
429    }
430
431    fn definitions(
432        &self,
433        buffer: &Model<Buffer>,
434        position: text::Anchor,
435        kind: crate::GotoDefinitionKind,
436        cx: &mut AppContext,
437    ) -> Option<Task<gpui::Result<Vec<project::LocationLink>>>> {
438        let buffer = self.to_base(&buffer, &[position], cx)?;
439        self.0.definitions(&buffer, position, kind, cx)
440    }
441
442    fn range_for_rename(
443        &self,
444        _: &Model<Buffer>,
445        _: text::Anchor,
446        _: &mut AppContext,
447    ) -> Option<Task<gpui::Result<Option<Range<text::Anchor>>>>> {
448        None
449    }
450
451    fn perform_rename(
452        &self,
453        _: &Model<Buffer>,
454        _: text::Anchor,
455        _: String,
456        _: &mut AppContext,
457    ) -> Option<Task<gpui::Result<project::ProjectTransaction>>> {
458        None
459    }
460}