context_inspector.rs

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