1use crate::{ApplyAllDiffHunks, Editor, EditorEvent, 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 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(None, window, cx, |selections| selections.refresh());
217 editor.buffer.update(cx, |buffer, cx| {
218 for diff in new_diffs {
219 buffer.add_diff(diff, cx)
220 }
221 })
222 });
223 }
224
225 pub fn recalculate_all_buffer_diffs(&self) {
226 for (ix, entry) in self.buffer_entries.iter().enumerate().rev() {
227 self.recalculate_diffs_tx
228 .unbounded_send(RecalculateDiff {
229 buffer: entry.branch.clone(),
230 debounce: ix > 0,
231 })
232 .ok();
233 }
234 }
235
236 fn on_buffer_event(
237 &mut self,
238 buffer: Entity<Buffer>,
239 event: &BufferEvent,
240 _cx: &mut Context<Self>,
241 ) {
242 match event {
243 BufferEvent::Operation { .. } => {
244 self.recalculate_diffs_tx
245 .unbounded_send(RecalculateDiff {
246 buffer,
247 debounce: true,
248 })
249 .ok();
250 }
251 // BufferEvent::DiffBaseChanged => {
252 // self.recalculate_diffs_tx
253 // .unbounded_send(RecalculateDiff {
254 // buffer,
255 // debounce: false,
256 // })
257 // .ok();
258 // }
259 _ => (),
260 }
261 }
262}
263
264impl Render for ProposedChangesEditor {
265 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
266 div()
267 .size_full()
268 .key_context("ProposedChangesEditor")
269 .child(self.editor.clone())
270 }
271}
272
273impl Focusable for ProposedChangesEditor {
274 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
275 self.editor.focus_handle(cx)
276 }
277}
278
279impl EventEmitter<EditorEvent> for ProposedChangesEditor {}
280
281impl Item for ProposedChangesEditor {
282 type Event = EditorEvent;
283
284 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
285 Some(Icon::new(IconName::Diff))
286 }
287
288 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
289 self.title.clone()
290 }
291
292 fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
293 Some(Box::new(self.editor.clone()))
294 }
295
296 fn act_as_type<'a>(
297 &'a self,
298 type_id: TypeId,
299 self_handle: &'a Entity<Self>,
300 _: &'a App,
301 ) -> Option<gpui::AnyView> {
302 if type_id == TypeId::of::<Self>() {
303 Some(self_handle.to_any())
304 } else if type_id == TypeId::of::<Editor>() {
305 Some(self.editor.to_any())
306 } else {
307 None
308 }
309 }
310
311 fn added_to_workspace(
312 &mut self,
313 workspace: &mut Workspace,
314 window: &mut Window,
315 cx: &mut Context<Self>,
316 ) {
317 self.editor.update(cx, |editor, cx| {
318 Item::added_to_workspace(editor, workspace, window, cx)
319 });
320 }
321
322 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
323 self.editor
324 .update(cx, |editor, cx| editor.deactivated(window, cx));
325 }
326
327 fn navigate(
328 &mut self,
329 data: Box<dyn std::any::Any>,
330 window: &mut Window,
331 cx: &mut Context<Self>,
332 ) -> bool {
333 self.editor
334 .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
335 }
336
337 fn set_nav_history(
338 &mut self,
339 nav_history: workspace::ItemNavHistory,
340 window: &mut Window,
341 cx: &mut Context<Self>,
342 ) {
343 self.editor.update(cx, |editor, cx| {
344 Item::set_nav_history(editor, nav_history, window, cx)
345 });
346 }
347
348 fn can_save(&self, cx: &App) -> bool {
349 self.editor.read(cx).can_save(cx)
350 }
351
352 fn save(
353 &mut self,
354 format: bool,
355 project: Entity<Project>,
356 window: &mut Window,
357 cx: &mut Context<Self>,
358 ) -> Task<anyhow::Result<()>> {
359 self.editor.update(cx, |editor, cx| {
360 Item::save(editor, format, project, window, cx)
361 })
362 }
363}
364
365impl ProposedChangesEditorToolbar {
366 pub fn new() -> Self {
367 Self {
368 current_editor: None,
369 }
370 }
371
372 fn get_toolbar_item_location(&self) -> ToolbarItemLocation {
373 if self.current_editor.is_some() {
374 ToolbarItemLocation::PrimaryRight
375 } else {
376 ToolbarItemLocation::Hidden
377 }
378 }
379}
380
381impl Render for ProposedChangesEditorToolbar {
382 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
383 let button_like = ButtonLike::new("apply-changes").child(Label::new("Apply All"));
384
385 match &self.current_editor {
386 Some(editor) => {
387 let focus_handle = editor.focus_handle(cx);
388 let keybinding =
389 KeyBinding::for_action_in(&ApplyAllDiffHunks, &focus_handle, window, cx)
390 .map(|binding| binding.into_any_element());
391
392 button_like.children(keybinding).on_click({
393 move |_event, window, cx| {
394 focus_handle.dispatch_action(&ApplyAllDiffHunks, window, cx)
395 }
396 })
397 }
398 None => button_like.disabled(true),
399 }
400 }
401}
402
403impl EventEmitter<ToolbarItemEvent> for ProposedChangesEditorToolbar {}
404
405impl ToolbarItemView for ProposedChangesEditorToolbar {
406 fn set_active_pane_item(
407 &mut self,
408 active_pane_item: Option<&dyn workspace::ItemHandle>,
409 _window: &mut Window,
410 _cx: &mut Context<Self>,
411 ) -> workspace::ToolbarItemLocation {
412 self.current_editor =
413 active_pane_item.and_then(|item| item.downcast::<ProposedChangesEditor>());
414 self.get_toolbar_item_location()
415 }
416}
417
418impl BranchBufferSemanticsProvider {
419 fn to_base(
420 &self,
421 buffer: &Entity<Buffer>,
422 positions: &[text::Anchor],
423 cx: &App,
424 ) -> Option<Entity<Buffer>> {
425 let base_buffer = buffer.read(cx).base_buffer()?;
426 let version = base_buffer.read(cx).version();
427 if positions
428 .iter()
429 .any(|position| !version.observed(position.timestamp))
430 {
431 return None;
432 }
433 Some(base_buffer)
434 }
435}
436
437impl SemanticsProvider for BranchBufferSemanticsProvider {
438 fn hover(
439 &self,
440 buffer: &Entity<Buffer>,
441 position: text::Anchor,
442 cx: &mut App,
443 ) -> Option<Task<Vec<project::Hover>>> {
444 let buffer = self.to_base(buffer, &[position], cx)?;
445 self.0.hover(&buffer, position, cx)
446 }
447
448 fn inlay_hints(
449 &self,
450 buffer: Entity<Buffer>,
451 range: Range<text::Anchor>,
452 cx: &mut App,
453 ) -> Option<Task<anyhow::Result<Vec<project::InlayHint>>>> {
454 let buffer = self.to_base(&buffer, &[range.start, range.end], cx)?;
455 self.0.inlay_hints(buffer, range, cx)
456 }
457
458 fn inline_values(
459 &self,
460 _: Entity<Buffer>,
461 _: Range<text::Anchor>,
462 _: &mut App,
463 ) -> Option<Task<anyhow::Result<Vec<project::InlayHint>>>> {
464 None
465 }
466
467 fn resolve_inlay_hint(
468 &self,
469 hint: project::InlayHint,
470 buffer: Entity<Buffer>,
471 server_id: lsp::LanguageServerId,
472 cx: &mut App,
473 ) -> Option<Task<anyhow::Result<project::InlayHint>>> {
474 let buffer = self.to_base(&buffer, &[], cx)?;
475 self.0.resolve_inlay_hint(hint, buffer, server_id, cx)
476 }
477
478 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
479 if let Some(buffer) = self.to_base(&buffer, &[], cx) {
480 self.0.supports_inlay_hints(&buffer, cx)
481 } else {
482 false
483 }
484 }
485
486 fn document_highlights(
487 &self,
488 buffer: &Entity<Buffer>,
489 position: text::Anchor,
490 cx: &mut App,
491 ) -> Option<Task<anyhow::Result<Vec<project::DocumentHighlight>>>> {
492 let buffer = self.to_base(&buffer, &[position], cx)?;
493 self.0.document_highlights(&buffer, position, cx)
494 }
495
496 fn definitions(
497 &self,
498 buffer: &Entity<Buffer>,
499 position: text::Anchor,
500 kind: crate::GotoDefinitionKind,
501 cx: &mut App,
502 ) -> Option<Task<anyhow::Result<Vec<project::LocationLink>>>> {
503 let buffer = self.to_base(&buffer, &[position], cx)?;
504 self.0.definitions(&buffer, position, kind, cx)
505 }
506
507 fn range_for_rename(
508 &self,
509 _: &Entity<Buffer>,
510 _: text::Anchor,
511 _: &mut App,
512 ) -> Option<Task<anyhow::Result<Option<Range<text::Anchor>>>>> {
513 None
514 }
515
516 fn perform_rename(
517 &self,
518 _: &Entity<Buffer>,
519 _: text::Anchor,
520 _: String,
521 _: &mut App,
522 ) -> Option<Task<anyhow::Result<project::ProjectTransaction>>> {
523 None
524 }
525}