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::{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
 91            let text_len = text.len();
 92            let snapshot = buffer.update(cx, |this, cx| {
 93                this.edit([(range.end..range.end, text)], None, cx);
 94                this.text_snapshot()
 95            });
 96            let start_offset = range.end.to_offset(&snapshot);
 97            let end_offset = start_offset + text_len;
 98            let multibuffer_snapshot = editor.buffer().read(cx).snapshot(cx);
 99            let anchor_before = multibuffer_snapshot.anchor_after(start_offset);
100            let anchor_after = multibuffer_snapshot.anchor_before(end_offset);
101
102            let block_id = editor
103                .insert_blocks(
104                    [BlockProperties {
105                        position: anchor_after,
106                        height: 0,
107                        style: BlockStyle::Sticky,
108                        render: Box::new(move |cx| {
109                            div()
110                                .w_full()
111                                .px(cx.gutter_dimensions.full_width())
112                                .child(h_flex().h(px(1.)).bg(Color::Warning.color(cx)))
113                                .into_any()
114                        }),
115                        disposition: BlockDisposition::Below,
116                        priority: 0,
117                    }],
118                    None,
119                    cx,
120                )
121                .into_iter()
122                .next()?;
123            let info = DebugInfo {
124                range: anchor_before..anchor_after,
125                block_id,
126            };
127            self.active_debug_views.insert(range, info);
128            Some(())
129        });
130    }
131
132    fn deactivate_impl(editor: &mut Editor, debug_data: DebugInfo, cx: &mut ViewContext<Editor>) {
133        editor.remove_blocks(HashSet::from_iter([debug_data.block_id]), None, cx);
134        editor.edit([(debug_data.range, Arc::<str>::default())], cx)
135    }
136    pub(crate) fn deactivate_for(&mut self, range: &StepRange, cx: &mut WindowContext<'_>) -> bool {
137        if let Some(debug_data) = self.active_debug_views.remove(range) {
138            self.editor.update(cx, |this, cx| {
139                Self::deactivate_impl(this, debug_data, cx);
140            });
141            true
142        } else {
143            false
144        }
145    }
146
147    pub(crate) fn deactivate(&mut self, cx: &mut WindowContext<'_>) {
148        let steps_to_disable = std::mem::take(&mut self.active_debug_views);
149
150        self.editor.update(cx, move |editor, cx| {
151            for (_, debug_data) in steps_to_disable {
152                Self::deactivate_impl(editor, debug_data, cx);
153            }
154        });
155    }
156}
157fn pretty_print_anchor(
158    out: &mut String,
159    anchor: &language::Anchor,
160    snapshot: &text::BufferSnapshot,
161) {
162    use std::fmt::Write;
163    let point = anchor.to_point(snapshot);
164    write!(out, "{}:{}", point.row, point.column).ok();
165}
166fn pretty_print_range(
167    out: &mut String,
168    range: &Range<language::Anchor>,
169    snapshot: &text::BufferSnapshot,
170) {
171    use std::fmt::Write;
172    write!(out, "    Range: ").ok();
173    pretty_print_anchor(out, &range.start, snapshot);
174    write!(out, "..").ok();
175    pretty_print_anchor(out, &range.end, snapshot);
176}
177
178fn pretty_print_workflow_suggestion(
179    out: &mut String,
180    suggestion: &WorkflowSuggestion,
181    snapshot: &text::BufferSnapshot,
182) {
183    use std::fmt::Write;
184    let (range, description, position) = match suggestion {
185        WorkflowSuggestion::Update { range, description } => (Some(range), Some(description), None),
186        WorkflowSuggestion::CreateFile { description } => (None, Some(description), None),
187        WorkflowSuggestion::AppendChild {
188            position,
189            description,
190        }
191        | WorkflowSuggestion::InsertSiblingBefore {
192            position,
193            description,
194        }
195        | WorkflowSuggestion::InsertSiblingAfter {
196            position,
197            description,
198        }
199        | WorkflowSuggestion::PrependChild {
200            position,
201            description,
202        } => (None, Some(description), Some(position)),
203
204        WorkflowSuggestion::Delete { range } => (Some(range), None, None),
205    };
206    if let Some(description) = description {
207        writeln!(out, "    Description: {description}").ok();
208    }
209    if let Some(range) = range {
210        pretty_print_range(out, range, snapshot);
211    }
212    if let Some(position) = position {
213        write!(out, "    Position: ").ok();
214        pretty_print_anchor(out, position, snapshot);
215        write!(out, "\n").ok();
216    }
217    write!(out, "\n").ok();
218}