1use std::{ops::Range, sync::Arc};
2
3use collections::{HashMap, HashSet};
4use editor::{
5 display_map::{BlockDisposition, BlockProperties, BlockStyle, CustomBlockId},
6 Editor,
7};
8use gpui::{AppContext, Model, View};
9use text::{Bias, ToOffset, ToPoint};
10use ui::{
11 div, h_flex, px, Color, Element as _, ParentElement as _, Styled, ViewContext, WindowContext,
12};
13
14use crate::{Context, ResolvedWorkflowStep, WorkflowSuggestion};
15
16type StepRange = Range<language::Anchor>;
17
18struct DebugInfo {
19 range: Range<editor::Anchor>,
20 block_id: CustomBlockId,
21}
22
23pub(crate) struct ContextInspector {
24 active_debug_views: HashMap<Range<language::Anchor>, DebugInfo>,
25 context: Model<Context>,
26 editor: View<Editor>,
27}
28
29impl ContextInspector {
30 pub(crate) fn new(editor: View<Editor>, context: Model<Context>) -> Self {
31 Self {
32 editor,
33 context,
34 active_debug_views: Default::default(),
35 }
36 }
37
38 pub(crate) fn is_active(&self, range: &StepRange) -> bool {
39 self.active_debug_views.contains_key(range)
40 }
41
42 pub(crate) fn refresh(&mut self, range: &StepRange, cx: &mut WindowContext<'_>) {
43 if self.deactivate_for(range, cx) {
44 self.activate_for_step(range.clone(), cx);
45 }
46 }
47
48 fn crease_content(
49 context: &Model<Context>,
50 range: StepRange,
51 cx: &mut AppContext,
52 ) -> Option<Arc<str>> {
53 use std::fmt::Write;
54 let step = context.read(cx).workflow_step_for_range(range)?;
55 let mut output = String::from("\n\n");
56 match &step.resolution.read(cx).result {
57 Some(Ok(ResolvedWorkflowStep { title, suggestions })) => {
58 writeln!(output, "Resolution:").ok()?;
59 writeln!(output, " {title:?}").ok()?;
60 if suggestions.is_empty() {
61 writeln!(output, " No suggestions").ok()?;
62 }
63
64 for (buffer, suggestion_groups) in suggestions {
65 let buffer = buffer.read(cx);
66 let buffer_path = buffer
67 .file()
68 .and_then(|file| file.path().to_str())
69 .unwrap_or("untitled");
70 let snapshot = buffer.text_snapshot();
71 writeln!(output, " {buffer_path}:").ok()?;
72 for group in suggestion_groups {
73 for suggestion in &group.suggestions {
74 pretty_print_workflow_suggestion(&mut output, suggestion, &snapshot);
75 }
76 }
77 }
78 }
79 Some(Err(error)) => {
80 writeln!(output, "Resolution: Error").ok()?;
81 writeln!(output, "{error:?}").ok()?;
82 }
83 None => {
84 writeln!(output, "Resolution: Pending").ok()?;
85 }
86 }
87
88 Some(output.into())
89 }
90
91 pub(crate) fn activate_for_step(&mut self, range: StepRange, cx: &mut WindowContext<'_>) {
92 let text = Self::crease_content(&self.context, range.clone(), cx)
93 .unwrap_or_else(|| Arc::from("Error fetching debug info"));
94 self.editor.update(cx, |editor, cx| {
95 let buffer = editor.buffer().read(cx).as_singleton()?;
96 let snapshot = buffer.read(cx).text_snapshot();
97 let start_offset = range.end.to_offset(&snapshot) + 1;
98 let start_offset = snapshot.clip_offset(start_offset, Bias::Right);
99 let text_len = text.len();
100 buffer.update(cx, |this, cx| {
101 this.edit([(start_offset..start_offset, text)], None, cx);
102 });
103
104 let end_offset = start_offset + text_len;
105 let multibuffer_snapshot = editor.buffer().read(cx).snapshot(cx);
106 let anchor_before = multibuffer_snapshot.anchor_after(start_offset);
107 let anchor_after = multibuffer_snapshot.anchor_before(end_offset);
108
109 let block_id = editor
110 .insert_blocks(
111 [BlockProperties {
112 position: anchor_after,
113 height: 0,
114 style: BlockStyle::Sticky,
115 render: Box::new(move |cx| {
116 div()
117 .w_full()
118 .px(cx.gutter_dimensions.full_width())
119 .child(h_flex().h(px(1.)).bg(Color::Warning.color(cx)))
120 .into_any()
121 }),
122 disposition: BlockDisposition::Below,
123 priority: 0,
124 }],
125 None,
126 cx,
127 )
128 .into_iter()
129 .next()?;
130 let info = DebugInfo {
131 range: anchor_before..anchor_after,
132 block_id,
133 };
134 self.active_debug_views.insert(range, info);
135 Some(())
136 });
137 }
138
139 fn deactivate_impl(editor: &mut Editor, debug_data: DebugInfo, cx: &mut ViewContext<Editor>) {
140 editor.remove_blocks(HashSet::from_iter([debug_data.block_id]), None, cx);
141 editor.edit([(debug_data.range, Arc::<str>::default())], cx)
142 }
143 pub(crate) fn deactivate_for(&mut self, range: &StepRange, cx: &mut WindowContext<'_>) -> bool {
144 if let Some(debug_data) = self.active_debug_views.remove(range) {
145 self.editor.update(cx, |this, cx| {
146 Self::deactivate_impl(this, debug_data, cx);
147 });
148 true
149 } else {
150 false
151 }
152 }
153
154 pub(crate) fn deactivate(&mut self, cx: &mut WindowContext<'_>) {
155 let steps_to_disable = std::mem::take(&mut self.active_debug_views);
156
157 self.editor.update(cx, move |editor, cx| {
158 for (_, debug_data) in steps_to_disable {
159 Self::deactivate_impl(editor, debug_data, cx);
160 }
161 });
162 }
163}
164fn pretty_print_anchor(
165 out: &mut String,
166 anchor: &language::Anchor,
167 snapshot: &text::BufferSnapshot,
168) {
169 use std::fmt::Write;
170 let point = anchor.to_point(snapshot);
171 write!(out, "{}:{}", point.row, point.column).ok();
172}
173fn pretty_print_range(
174 out: &mut String,
175 range: &Range<language::Anchor>,
176 snapshot: &text::BufferSnapshot,
177) {
178 use std::fmt::Write;
179 write!(out, " Range: ").ok();
180 pretty_print_anchor(out, &range.start, snapshot);
181 write!(out, "..").ok();
182 pretty_print_anchor(out, &range.end, snapshot);
183}
184
185fn pretty_print_workflow_suggestion(
186 out: &mut String,
187 suggestion: &WorkflowSuggestion,
188 snapshot: &text::BufferSnapshot,
189) {
190 use std::fmt::Write;
191 let (range, description, position) = match suggestion {
192 WorkflowSuggestion::Update { range, description } => (Some(range), Some(description), None),
193 WorkflowSuggestion::CreateFile { description } => (None, Some(description), None),
194 WorkflowSuggestion::AppendChild {
195 position,
196 description,
197 }
198 | WorkflowSuggestion::InsertSiblingBefore {
199 position,
200 description,
201 }
202 | WorkflowSuggestion::InsertSiblingAfter {
203 position,
204 description,
205 }
206 | WorkflowSuggestion::PrependChild {
207 position,
208 description,
209 } => (None, Some(description), Some(position)),
210
211 WorkflowSuggestion::Delete { range } => (Some(range), None, None),
212 };
213 if let Some(description) = description {
214 writeln!(out, " Description: {description}").ok();
215 }
216 if let Some(range) = range {
217 pretty_print_range(out, range, snapshot);
218 }
219 if let Some(position) = position {
220 write!(out, " Position: ").ok();
221 pretty_print_anchor(out, position, snapshot);
222 write!(out, "\n").ok();
223 }
224 write!(out, "\n").ok();
225}