use crate::widgets::view_cx::ViewCx;
use std::collections::HashSet;
use std::path::PathBuf;
use ratatui::{
buffer::Buffer,
layout::{Position, Rect},
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Paragraph, Widget},
};
use crate::lsp::manager::DiagnosticSeverity;
use crate::widgets::scrollbar;
const COLOR_HEADER: Color = Color::Rgb(0xE8, 0xEE, 0xF8);
const COLOR_DIM: Color = Color::Rgb(0x60, 0x68, 0x78);
const COLOR_MSG: Color = Color::Rgb(0xCC, 0xCC, 0xCC);
const COLOR_ERROR: Color = Color::Rgb(0xf1, 0x4c, 0x4c);
const COLOR_WARNING: Color = Color::Rgb(0xcc, 0xa7, 0x00);
const COLOR_INFO: Color = Color::Rgb(0x3b, 0x9e, 0xff);
const GLYPH_ERROR: char = '\u{ea87}';
const GLYPH_WARNING: char = '\u{ea6c}';
const GLYPH_INFO: char = '\u{ea74}';
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProblemItem {
pub line: u32,
pub col: u32,
pub col_utf16: bool,
pub severity: DiagnosticSeverity,
pub message: String,
pub source: String,
pub code: Option<crate::lsp::manager::DiagnosticCode>,
pub related: Vec<ProblemRelated>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProblemRelated {
pub path: PathBuf,
pub rel_path: String,
pub line: u32,
pub col: u32,
pub message: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProblemGroup {
pub path: PathBuf,
pub name: String,
pub rel_dir: String,
pub items: Vec<ProblemItem>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum RenderRow {
Header(usize),
Diag(usize, usize),
Related(usize, usize, usize),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ProblemScope {
OpenFiles,
#[default]
WholeProject,
}
impl ProblemScope {
pub fn label(self) -> &'static str {
match self {
Self::OpenFiles => "Open Files",
Self::WholeProject => "Whole Project",
}
}
pub fn next(self) -> Self {
match self {
Self::OpenFiles => Self::WholeProject,
Self::WholeProject => Self::OpenFiles,
}
}
pub fn to_config(self) -> &'static str {
match self {
Self::OpenFiles => "open_files",
Self::WholeProject => "whole_project",
}
}
pub fn from_config(s: &str) -> Self {
let norm = s.trim().to_ascii_lowercase().replace([' ', '-'], "_");
match norm.as_str() {
"open" | "open_files" | "openfiles" => Self::OpenFiles,
"whole_project" | "wholeproject" | "project" | "all" => Self::WholeProject,
_ => Self::WholeProject,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProblemFilter {
All,
Errors,
Warnings,
}
impl ProblemFilter {
fn next(self) -> Self {
match self {
Self::All => Self::Errors,
Self::Errors => Self::Warnings,
Self::Warnings => Self::All,
}
}
fn label(self) -> &'static str {
match self {
Self::All => "All",
Self::Errors => "Errors",
Self::Warnings => "Errors & Warnings",
}
}
fn keeps(self, sev: DiagnosticSeverity) -> bool {
match self {
Self::All => true,
Self::Errors => sev == DiagnosticSeverity::Error,
Self::Warnings => {
matches!(sev, DiagnosticSeverity::Error | DiagnosticSeverity::Warning)
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProblemHit {
Header(PathBuf),
Diagnostic {
path: PathBuf,
line: u32,
col: u32,
col_utf16: bool,
},
}
const RELATED_INDENT: &str = " ";
const FILTER_CHIP_CHARS: usize = 24;
pub struct ProblemsPanel {
groups: Vec<ProblemGroup>,
collapsed: HashSet<PathBuf>,
scroll: usize,
filter: ProblemFilter,
pub text_filter: String,
text_filter_caret: Option<usize>,
group_by_file: bool,
pub scope: ProblemScope,
pub last_area: Rect,
pub last_scrollbar: Rect,
pub fixing: Option<(PathBuf, u32)>,
pub fix_glyph: &'static str,
filter_rect: Rect,
group_rect: Rect,
rows: Vec<RenderRow>,
first_row_y: u16,
visible_rows: u16,
last_scroll: usize,
drawn_groups: Option<Vec<ProblemGroup>>,
viewport_rows: u16,
}
impl ProblemsPanel {
pub fn new() -> Self {
Self {
groups: Vec::new(),
collapsed: HashSet::new(),
scroll: 0,
filter: ProblemFilter::All,
text_filter: String::new(),
text_filter_caret: None,
group_by_file: true,
scope: ProblemScope::default(),
last_area: Rect::default(),
last_scrollbar: Rect::default(),
fixing: None,
fix_glyph: "",
filter_rect: Rect::default(),
group_rect: Rect::default(),
rows: Vec::new(),
first_row_y: 0,
visible_rows: 0,
last_scroll: 0,
drawn_groups: None,
viewport_rows: 0,
}
}
pub fn groups(&self) -> &[ProblemGroup] {
&self.groups
}
pub fn set_groups(&mut self, groups: Vec<ProblemGroup>) -> bool {
if self.groups == groups {
return false;
}
self.collapsed
.retain(|p| groups.iter().any(|g| &g.path == p));
let old = std::mem::replace(&mut self.groups, groups);
self.drawn_groups.get_or_insert(old);
self.scroll = self.scroll.min(self.max_scroll());
true
}
pub fn total_count(&self) -> usize {
self.groups.iter().map(|g| g.items.len()).sum()
}
pub fn top_diagnostic(&self) -> Option<(&ProblemGroup, &ProblemItem)> {
self.layout()
.into_iter()
.skip(self.scroll)
.find_map(|row| match row {
RenderRow::Diag(g, i) => Some((&self.groups[g], &self.groups[g].items[i])),
_ => None,
})
}
pub fn error_count(&self) -> usize {
self.severity_count(DiagnosticSeverity::Error)
}
pub fn warning_count(&self) -> usize {
self.severity_count(DiagnosticSeverity::Warning)
}
fn severity_count(&self, want: DiagnosticSeverity) -> usize {
self.groups
.iter()
.flat_map(|g| g.items.iter())
.filter(|i| i.severity == want)
.count()
}
pub fn toggle_collapse(&mut self, path: &PathBuf) {
if !self.collapsed.remove(path) {
self.collapsed.insert(path.clone());
}
self.scroll = self.scroll.min(self.max_scroll());
}
pub fn scroll_down(&mut self, n: usize) {
self.scroll = (self.scroll + n).min(self.max_scroll());
}
pub fn scroll_up(&mut self, n: usize) {
self.scroll = self.scroll.saturating_sub(n);
}
fn max_scroll(&self) -> usize {
self.total_rows()
.saturating_sub(self.viewport_rows as usize)
}
fn keeps_item(&self, group: &ProblemGroup, it: &ProblemItem) -> bool {
if !self.filter.keeps(it.severity) {
return false;
}
if self.text_filter.is_empty() {
return true;
}
let needle = self.text_filter.to_lowercase();
it.message.to_lowercase().contains(&needle)
|| it
.code
.as_ref()
.is_some_and(|c| c.label(&it.source).to_lowercase().contains(&needle))
|| group
.path
.to_string_lossy()
.to_lowercase()
.contains(&needle)
|| it.related.iter().any(|r| {
r.message.to_lowercase().contains(&needle)
|| r.rel_path.to_lowercase().contains(&needle)
})
}
pub fn text_filter_caret(&self) -> usize {
crate::widgets::line_edit::opt_caret(&self.text_filter, self.text_filter_caret)
}
pub fn move_filter_caret(&mut self, step: impl FnOnce(&str, usize) -> usize) {
crate::widgets::line_edit::walk_opt(&self.text_filter, &mut self.text_filter_caret, step);
}
pub fn push_filter_char(&mut self, c: char) {
let mut buf = [0u8; 4];
let s = c.encode_utf8(&mut buf);
if crate::widgets::line_edit::edit_opt(
&mut self.text_filter,
&mut self.text_filter_caret,
|t, at| crate::widgets::line_edit::insert_at(t, at, s),
) {
self.scroll = 0;
}
}
#[cfg(test)]
pub fn pop_filter_char(&mut self) {
self.backspace_filter(false);
}
pub fn backspace_filter(&mut self, word: bool) {
if crate::widgets::line_edit::edit_opt(
&mut self.text_filter,
&mut self.text_filter_caret,
|t, at| crate::widgets::line_edit::delete_before(t, at, word),
) {
self.scroll = 0;
}
}
pub fn delete_filter(&mut self, word: bool) {
if crate::widgets::line_edit::edit_opt(
&mut self.text_filter,
&mut self.text_filter_caret,
|t, at| crate::widgets::line_edit::delete_at(t, at, word),
) {
self.scroll = 0;
}
}
pub fn clear_text_filter(&mut self) -> bool {
if self.text_filter.is_empty() {
return false;
}
self.text_filter.clear();
self.text_filter_caret = None;
self.scroll = 0;
true
}
fn visible_groups(&self) -> Vec<(usize, Vec<usize>)> {
self.groups
.iter()
.enumerate()
.filter_map(|(g, group)| {
let items: Vec<usize> = group
.items
.iter()
.enumerate()
.filter(|(_, it)| self.keeps_item(group, it))
.map(|(i, _)| i)
.collect();
(!items.is_empty()).then_some((g, items))
})
.collect()
}
fn total_rows(&self) -> usize {
self.layout().len()
}
pub fn scroll_to_bar_y(&mut self, y: u16) -> bool {
let Some(metrics) = scrollbar::vertical_metrics(
self.last_scrollbar,
self.total_rows(),
self.viewport_rows as usize,
self.scroll,
) else {
return false;
};
let target = scrollbar::scroll_for_y(metrics, y);
let moved = target != self.scroll;
self.scroll = target;
moved
}
pub fn hit_at(&self, y: u16) -> Option<ProblemHit> {
let line = self.line_at_y(y)?;
let groups = self.drawn_groups();
match self.rows.get(self.last_scroll + line)? {
RenderRow::Header(g) => {
let group = groups.get(*g)?;
Some(ProblemHit::Header(group.path.clone()))
}
RenderRow::Diag(g, i) => {
let group = groups.get(*g)?;
let item = group.items.get(*i)?;
Some(ProblemHit::Diagnostic {
path: group.path.clone(),
line: item.line,
col: item.col,
col_utf16: item.col_utf16,
})
}
RenderRow::Related(g, i, r) => {
let related = groups.get(*g)?.items.get(*i)?.related.get(*r)?;
Some(ProblemHit::Diagnostic {
path: related.path.clone(),
line: related.line,
col: related.col,
col_utf16: true,
})
}
}
}
pub fn diagnostic_at(&self, y: u16) -> Option<(PathBuf, ProblemItem)> {
let line = self.line_at_y(y)?;
diagnostic_of(self.drawn_groups(), self.rows.get(self.last_scroll + line)?)
}
pub fn first_diagnostic_next_frame(&self) -> Option<(u16, (PathBuf, ProblemItem))> {
let shown = self.visible_rows as usize;
let rows = self.layout();
(self.first_row_y..)
.zip(rows.iter().skip(self.scroll).take(shown))
.find_map(|(y, row)| Some((y, diagnostic_of(&self.groups, row)?)))
}
fn line_at_y(&self, y: u16) -> Option<usize> {
let offset = (y.checked_sub(self.first_row_y)?) as usize;
(offset < self.visible_rows as usize).then_some(offset)
}
fn drawn_groups(&self) -> &[ProblemGroup] {
self.drawn_groups.as_deref().unwrap_or(&self.groups)
}
fn layout(&self) -> Vec<RenderRow> {
let mut rows = Vec::new();
for (g, items) in self.visible_groups() {
if self.group_by_file {
rows.push(RenderRow::Header(g));
if self.collapsed.contains(&self.groups[g].path) {
continue;
}
}
for i in items {
rows.push(RenderRow::Diag(g, i));
let related = self.groups[g].items[i].related.len();
rows.extend((0..related).map(|r| RenderRow::Related(g, i, r)));
}
}
rows
}
fn build_rows(&mut self) {
self.rows = self.layout();
self.drawn_groups = None;
}
fn cycle_filter(&mut self) {
self.filter = self.filter.next();
self.scroll = self.scroll.min(self.max_scroll());
}
fn toggle_group_by_file(&mut self) {
self.group_by_file = !self.group_by_file;
self.scroll = self.scroll.min(self.max_scroll());
}
pub fn click(&mut self, x: u16, y: u16) -> bool {
if self.filter_rect.contains(Position::new(x, y)) {
self.cycle_filter();
return true;
}
if self.group_rect.contains(Position::new(x, y)) {
self.toggle_group_by_file();
return true;
}
false
}
}
fn diagnostic_of(groups: &[ProblemGroup], row: &RenderRow) -> Option<(PathBuf, ProblemItem)> {
match row {
RenderRow::Header(_) => None,
RenderRow::Diag(g, i) | RenderRow::Related(g, i, _) => {
let group = groups.get(*g)?;
let item = group.items.get(*i)?;
Some((group.path.clone(), item.clone()))
}
}
}
impl Default for ProblemsPanel {
fn default() -> Self {
Self::new()
}
}
pub fn fix_prompt(item: &ProblemItem, rel_path: &str, hints: &[String]) -> String {
let kind = match item.severity {
DiagnosticSeverity::Error => "error",
DiagnosticSeverity::Warning => "warning",
DiagnosticSeverity::Information | DiagnosticSeverity::Hint => "diagnostic",
};
let source = if item.source.is_empty() {
String::from("a diagnostic tool")
} else {
item.source.clone()
};
let rule = item
.code
.as_ref()
.map(|c| format!(" (rule {})", c.value))
.unwrap_or_default();
let mut text = format!(
"Fix the {kind} reported by {source}{rule} at {rel_path}:{}:{}: {}",
item.line + 1,
item.col + 1,
item.message.trim().replace('\n', " ")
);
if !hints.is_empty() {
text.push_str("\nThe server offers these quick fixes; apply one if it is the right fix: ");
text.push_str(&hints.join("; "));
}
text.push_str(
"\nEdit the buffer with the smallest change that resolves the diagnostic and \
keeps the code's behaviour. If it cannot be fixed safely, say why in a note \
instead of editing.",
);
text
}
fn severity_glyph(severity: DiagnosticSeverity, theme: crate::theme::Theme) -> (char, Color) {
match severity {
DiagnosticSeverity::Error => (GLYPH_ERROR, theme.ui(COLOR_ERROR)),
DiagnosticSeverity::Warning => (GLYPH_WARNING, theme.ui(COLOR_WARNING)),
DiagnosticSeverity::Information | DiagnosticSeverity::Hint => {
(GLYPH_INFO, theme.ui(COLOR_INFO))
}
}
}
impl ProblemsPanel {
pub fn draw(&mut self, cx: &ViewCx, area: Rect, buf: &mut Buffer) {
self.last_area = area;
self.last_scrollbar = Rect::default();
self.filter_rect = Rect::default();
self.group_rect = Rect::default();
self.visible_rows = 0;
self.build_rows();
if area.width == 0 || area.height == 0 {
return;
}
buf.set_style(area, Style::default().bg(cx.theme.editor_bg()));
if self.groups.is_empty() {
let empty_msg = match self.scope {
ProblemScope::WholeProject => "No problems have been detected in the workspace.",
ProblemScope::OpenFiles => {
"No problems in the open files. Switch scope to Whole Project to see the rest."
}
};
Paragraph::new(Line::from(Span::styled(
empty_msg,
Style::default().fg(cx.theme.ui(COLOR_DIM)),
)))
.render(
Rect {
x: area.x + 1,
y: area.y,
width: area.width.saturating_sub(1),
height: 1,
},
buf,
);
return;
}
let toolbar = Rect {
x: area.x,
y: area.y,
width: area.width,
height: 1,
};
self.render_toolbar(cx, toolbar, buf);
let body = Rect {
x: area.x,
y: area.y + 1,
width: area.width,
height: area.height.saturating_sub(1),
};
if body.height == 0 {
return;
}
if self.rows.is_empty() {
Paragraph::new(Line::from(Span::styled(
"No problems match the current filter.",
Style::default().fg(cx.theme.ui(COLOR_DIM)),
)))
.render(
Rect {
x: body.x + 1,
y: body.y,
width: body.width.saturating_sub(1),
height: 1,
},
buf,
);
return;
}
self.first_row_y = body.y;
self.viewport_rows = body.height;
let total = self.total_rows();
self.scroll = self.scroll.min(total.saturating_sub(body.height as usize));
let bar = scrollbar::vertical_metrics(
Rect {
x: body.x + body.width.saturating_sub(1),
y: body.y,
width: 1,
height: body.height,
},
total,
body.height as usize,
self.scroll,
);
let content_w = body.width.saturating_sub(u16::from(bar.is_some()));
let visible = (body.height as usize).min(self.rows.len().saturating_sub(self.scroll));
self.visible_rows = visible as u16;
self.last_scroll = self.scroll;
let gutter = u16::from(cx.theme.surfaces().is_some());
for row in 0..visible {
let render_row = self.rows[self.scroll + row].clone();
let y = body.y + row as u16;
let row_rect = Rect {
x: body.x,
y,
width: content_w,
height: 1,
};
if let Some(bg) = crate::widgets::hover::row_hover_bg(row_rect, cx.pointer, cx.theme) {
buf.set_style(row_rect, Style::default().bg(bg));
}
let spans = match render_row {
RenderRow::Header(g) => self.header_spans(cx, g),
RenderRow::Diag(g, i) => self.diag_spans(cx, g, i),
RenderRow::Related(g, i, r) => self.related_spans(cx, g, i, r),
};
let text_rect = Rect {
x: row_rect.x + gutter.min(row_rect.width),
width: row_rect.width.saturating_sub(gutter),
..row_rect
};
Paragraph::new(Line::from(spans)).render(text_rect, buf);
}
if let Some(metrics) = bar {
self.last_scrollbar = metrics.area;
scrollbar::render_vertical(buf, metrics, cx.focused, cx.theme);
}
}
}
impl ProblemsPanel {
fn render_toolbar(&mut self, cx: &ViewCx, area: Rect, buf: &mut Buffer) {
let muted = cx.theme.ignored_fg();
let accent = cx.theme.accent();
let chip = cx.theme.accent_chip_bg();
let filter_prefix = format!(" {} \u{25be} \u{eb85} ", self.filter.label());
let (filter_label, caret_offset) = if self.text_filter.is_empty() {
(format!(" {} \u{25be} ", self.filter.label()), None)
} else {
let win = crate::widgets::line_edit::window(
&self.text_filter,
self.text_filter_caret(),
FILTER_CHIP_CHARS,
);
let shown_filter = crate::widgets::line_edit::visible_slice(&self.text_filter, win);
(
format!("{filter_prefix}{shown_filter} "),
Some(filter_prefix.chars().count() + win.caret_cell),
)
};
let group_label = format!(
" {} ",
if self.group_by_file {
"Grouped"
} else {
"Flat"
}
);
let fw = filter_label.chars().count() as u16;
let gw = group_label.chars().count() as u16;
let total = fw + 1 + gw + 1;
let mut x = area.x + area.width.saturating_sub(total.min(area.width));
let mut control = |label: String, active: bool, buf: &mut Buffer| -> Rect {
let w = (label.chars().count() as u16).min(area.right().saturating_sub(x));
let r = Rect {
x,
y: area.y,
width: w,
height: 1,
};
let style = if active {
Style::default().fg(accent).bg(chip)
} else {
Style::default().fg(muted)
};
Paragraph::new(Line::from(Span::styled(label, style))).render(r, buf);
x += w + 1;
r
};
self.filter_rect = control(
filter_label,
self.filter != ProblemFilter::All || !self.text_filter.is_empty(),
buf,
);
if cx.focused
&& let Some(offset) = caret_offset
{
let caret_x = self.filter_rect.x.saturating_add(offset as u16);
if caret_x < self.filter_rect.right() {
buf[(caret_x, self.filter_rect.y)].set_style(
Style::default()
.fg(accent)
.bg(chip)
.add_modifier(Modifier::REVERSED),
);
}
}
self.group_rect = control(group_label, !self.group_by_file, buf);
}
fn header_spans(&self, cx: &ViewCx, g: usize) -> Vec<Span<'static>> {
let group = &self.groups[g];
let chevron = if self.collapsed.contains(&group.path) {
crate::icons::CHEVRON_CLOSED
} else {
crate::icons::CHEVRON_OPEN
};
let suffix = group
.name
.rfind('.')
.map(|i| group.name[i..].to_string())
.unwrap_or_default();
let icon = crate::icons::for_path(&group.name, &suffix);
let mut spans = vec![
Span::styled(
format!("{chevron} "),
Style::default().fg(cx.theme.ui(COLOR_DIM)),
),
Span::styled(
format!("{} ", icon.glyph),
Style::default().fg(cx.theme.ui(icon.color)),
),
Span::styled(
group.name.clone(),
Style::default()
.fg(cx.theme.ui(COLOR_HEADER))
.add_modifier(Modifier::BOLD),
),
];
if !group.rel_dir.is_empty() {
spans.push(Span::styled(
format!(" {}", group.rel_dir),
Style::default().fg(cx.theme.ui(COLOR_DIM)),
));
}
let shown = group
.items
.iter()
.filter(|it| self.keeps_item(group, it))
.count();
spans.push(Span::styled(
format!(" {shown}"),
Style::default().fg(cx.theme.ui(COLOR_DIM)),
));
spans
}
fn diag_spans(&self, cx: &ViewCx, g: usize, i: usize) -> Vec<Span<'static>> {
let item = &self.groups[g].items[i];
let (glyph, color) = severity_glyph(item.severity, cx.theme);
let message = item.message.replace('\n', " ");
let fixing = self
.fixing
.as_ref()
.is_some_and(|(path, line)| *path == self.groups[g].path && *line == item.line);
let lead = if fixing && !self.fix_glyph.is_empty() {
Span::styled(
format!(" {} ", self.fix_glyph),
Style::default().fg(cx.theme.ui(COLOR_INFO)),
)
} else {
Span::styled(format!(" {glyph} "), Style::default().fg(color))
};
let mut spans = vec![
lead,
Span::styled(message, Style::default().fg(cx.theme.ui(COLOR_MSG))),
];
let source = match &item.code {
Some(code) => code.label(&item.source),
None => item.source.clone(),
};
if !source.is_empty() {
spans.push(Span::styled(
format!(" {source} "),
Style::default().fg(cx.theme.ui(COLOR_DIM)),
));
}
spans.push(Span::styled(
format!("[Ln {}, Col {}]", item.line + 1, item.col + 1),
Style::default().fg(cx.theme.ui(COLOR_DIM)),
));
if !self.group_by_file {
spans.push(Span::styled(
format!(" {}", self.groups[g].name),
Style::default().fg(cx.theme.ui(COLOR_DIM)),
));
}
spans
}
fn related_spans(&self, cx: &ViewCx, g: usize, i: usize, r: usize) -> Vec<Span<'static>> {
let related = &self.groups[g].items[i].related[r];
vec![
Span::styled(
format!(
"{RELATED_INDENT}{} [Ln {}, Col {}]: ",
related.rel_path,
related.line + 1,
related.col + 1
),
Style::default().fg(cx.theme.ui(COLOR_DIM)),
),
Span::styled(
crate::lsp::manager::one_line(&related.message),
Style::default().fg(cx.theme.ui(COLOR_MSG)),
),
]
}
}
#[cfg(test)]
mod tests {
use super::*;
fn diag(line: u32, severity: DiagnosticSeverity, msg: &str) -> ProblemItem {
ProblemItem {
line,
col: 0,
col_utf16: false,
severity,
message: msg.to_string(),
source: "rustc".to_string(),
code: None,
related: Vec::new(),
}
}
fn group(name: &str, items: Vec<ProblemItem>) -> ProblemGroup {
ProblemGroup {
path: PathBuf::from(format!("/repo/src/{name}")),
name: name.to_string(),
rel_dir: "src".to_string(),
items,
}
}
fn render(p: &mut ProblemsPanel, w: u16, h: u16) -> String {
render_in(p, &ViewCx::default(), w, h)
}
fn render_in(p: &mut ProblemsPanel, cx: &ViewCx, w: u16, h: u16) -> String {
let area = Rect {
x: 0,
y: 0,
width: w,
height: h,
};
let mut buf = Buffer::empty(area);
p.draw(cx, area, &mut buf);
let mut out = String::new();
for y in 0..h {
for x in 0..w {
out.push_str(buf[(x, y)].symbol());
}
out.push('\n');
}
out
}
#[test]
fn the_top_diagnostic_follows_the_scroll_filters_and_folds() {
use DiagnosticSeverity::{Error, Warning};
let mut p = ProblemsPanel::new();
assert!(p.top_diagnostic().is_none(), "no problems, no top row");
p.set_groups(vec![
group("a.rs", vec![diag(1, Warning, "w1"), diag(2, Error, "e1")]),
group("b.rs", vec![diag(5, Error, "e2")]),
]);
let top = |p: &ProblemsPanel| {
p.top_diagnostic()
.map(|(g, it)| (g.name.clone(), it.message.clone()))
};
assert_eq!(top(&p), Some(("a.rs".into(), "w1".into())));
p.scroll_down(2);
assert_eq!(top(&p), Some(("a.rs".into(), "e1".into())));
p.scroll_down(1);
assert_eq!(top(&p), Some(("b.rs".into(), "e2".into())));
p.scroll_up(10);
p.cycle_filter();
assert_eq!(top(&p), Some(("a.rs".into(), "e1".into())));
p.cycle_filter();
p.cycle_filter();
p.toggle_collapse(&PathBuf::from("/repo/src/a.rs"));
assert_eq!(top(&p), Some(("b.rs".into(), "e2".into())));
}
#[test]
fn a_long_or_wide_filter_keeps_the_toolbar_inside_the_panel() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(0, DiagnosticSeverity::Error, "boom")],
)]);
for c in "\u{5e83}\u{3044}\u{6587}\u{5b57}".repeat(20).chars() {
p.push_filter_char(c);
}
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 6,
};
let mut buf = Buffer::empty(area);
p.draw(&ViewCx::default(), area, &mut buf);
let row: String = (0..area.width)
.map(|x| buf[(x, 0)].symbol().to_string())
.collect();
assert!(
row.contains("All"),
"the severity control must survive a long filter, got {row:?}"
);
assert!(
p.text_filter.chars().count() > FILTER_CHIP_CHARS,
"the filter itself stays unbounded; only its display is capped"
);
}
#[test]
fn text_filter_narrows_by_message_and_path() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![
group(
"alpha.rs",
vec![
diag(0, DiagnosticSeverity::Error, "Mismatched types"),
diag(1, DiagnosticSeverity::Warning, "unused variable"),
],
),
group("beta.rs", vec![diag(0, DiagnosticSeverity::Error, "boom")]),
]);
assert_eq!(p.total_rows(), 5, "2 headers + 3 diagnostics");
for c in "MISMATCH".chars() {
p.push_filter_char(c.to_ascii_lowercase());
}
assert_eq!(p.total_rows(), 2, "one header + the one matching row");
while !p.text_filter.is_empty() {
p.pop_filter_char();
}
assert_eq!(p.total_rows(), 5);
for c in "beta".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 2);
while !p.text_filter.is_empty() {
p.pop_filter_char();
}
for c in "unused".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 2, "the warning matches on its own");
while p.filter != ProblemFilter::Errors {
p.cycle_filter();
}
assert_eq!(p.total_rows(), 0, "text and severity filters compose");
assert!(p.clear_text_filter(), "clearing reports it had text");
assert!(!p.clear_text_filter(), "second clear is a no-op");
}
#[test]
fn text_filter_matches_the_displayed_rule_code() {
let mut coded = diag(0, DiagnosticSeverity::Warning, "`os` imported but unused");
coded.code = Some(crate::lsp::manager::DiagnosticCode {
value: String::from("F401"),
source: Some(String::from("Ruff")),
href: None,
});
let plain = diag(1, DiagnosticSeverity::Warning, "unused variable");
let mut p = ProblemsPanel::new();
p.set_groups(vec![group("app.py", vec![coded, plain])]);
for c in "f401".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 2, "one header + the coded row");
p.clear_text_filter();
for c in "ruff(".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 2, "the source(code) label matches");
p.clear_text_filter();
for c in "rustc".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 0, "no row shows `rustc`");
}
#[test]
fn text_filter_matches_a_related_rows_message_and_file() {
let related = |rel_path: &str, message: &str| ProblemRelated {
path: PathBuf::from("/repo").join(rel_path),
rel_path: rel_path.to_string(),
line: 1,
col: 2,
message: message.to_string(),
};
let mut missing = diag(3, DiagnosticSeverity::Error, "Property 'foo' is missing");
missing.related = vec![
related("src/bar.ts", "'foo' is declared here."),
related("src/other.ts", "and used here."),
];
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.ts",
vec![missing, diag(9, DiagnosticSeverity::Warning, "meh")],
)]);
for c in "declared here".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 4, "header, diagnostic, both related rows");
p.clear_text_filter();
for c in "other.ts".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 4, "a related row's file matches too");
}
#[test]
fn the_header_count_follows_the_severity_filter() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![
diag(0, DiagnosticSeverity::Error, "boom"),
diag(1, DiagnosticSeverity::Warning, "meh1"),
diag(2, DiagnosticSeverity::Warning, "meh2"),
],
)]);
while p.filter != ProblemFilter::Errors {
p.cycle_filter();
}
let text: String = p
.header_spans(&ViewCx::default(), 0)
.iter()
.map(|s| s.content.clone())
.collect();
assert!(
text.ends_with(" 1"),
"the badge must count only diagnostics passing the filter, got {text:?}"
);
}
#[test]
fn counts_aggregate_across_files() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![
group(
"a.rs",
vec![
diag(0, DiagnosticSeverity::Error, "boom"),
diag(1, DiagnosticSeverity::Warning, "meh"),
],
),
group("b.rs", vec![diag(2, DiagnosticSeverity::Error, "kaboom")]),
]);
assert_eq!(p.total_count(), 3);
assert_eq!(p.error_count(), 2);
assert_eq!(p.warning_count(), 1);
}
#[test]
fn a_click_after_a_wheel_step_meets_the_drawn_rows() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
(1..=40)
.map(|line| diag(line, DiagnosticSeverity::Error, "boom"))
.collect(),
)]);
render(&mut p, 60, 10);
let drawn = p.hit_at(2);
assert!(drawn.is_some(), "a row is drawn there");
let before = p.scroll;
p.scroll_down(3);
assert!(p.scroll > before, "the wheel scrolled the rows");
assert_eq!(p.hit_at(2), drawn, "the row drawn there");
}
#[test]
fn a_click_after_the_groups_change_meets_the_drawn_diagnostic() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![
group("a.rs", vec![diag(1, DiagnosticSeverity::Error, "boom")]),
group("b.rs", vec![diag(2, DiagnosticSeverity::Error, "kaboom")]),
]);
render(&mut p, 60, 8);
let b = PathBuf::from("/repo/src/b.rs");
let y = (0..8)
.find(|&y| matches!(p.hit_at(y), Some(ProblemHit::Diagnostic { ref path, .. }) if *path == b))
.expect("b.rs's diagnostic is drawn");
p.set_groups(vec![
group("0.rs", vec![diag(7, DiagnosticSeverity::Error, "first")]),
group("a.rs", vec![diag(1, DiagnosticSeverity::Error, "boom")]),
group("b.rs", vec![diag(2, DiagnosticSeverity::Error, "kaboom")]),
]);
assert!(
matches!(p.hit_at(y), Some(ProblemHit::Diagnostic { ref path, line: 2, .. }) if *path == b),
"the diagnostic drawn there: {:?}",
p.hit_at(y)
);
let (path, item) = p.diagnostic_at(y).expect("a diagnostic is drawn there");
assert_eq!((path, item.message.as_str()), (b, "kaboom"));
let (_, (path, item)) = p
.first_diagnostic_next_frame()
.expect("the next frame has one");
assert_eq!(
(path, item.message.as_str()),
(PathBuf::from("/repo/src/0.rs"), "first"),
"the next frame draws the new groups"
);
}
#[test]
fn header_then_diag_rows_map_to_hits() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![
diag(4, DiagnosticSeverity::Error, "boom"),
diag(9, DiagnosticSeverity::Warning, "meh"),
],
)]);
render(&mut p, 60, 6);
assert_eq!(p.hit_at(0), None, "row 0 is the toolbar, not a list row");
assert_eq!(
p.hit_at(1),
Some(ProblemHit::Header(PathBuf::from("/repo/src/a.rs"))),
"row 1 is the file header",
);
assert_eq!(
p.hit_at(2),
Some(ProblemHit::Diagnostic {
path: PathBuf::from("/repo/src/a.rs"),
line: 4,
col: 0,
col_utf16: false,
}),
);
assert_eq!(
p.hit_at(3),
Some(ProblemHit::Diagnostic {
path: PathBuf::from("/repo/src/a.rs"),
line: 9,
col: 0,
col_utf16: false,
}),
);
assert_eq!(p.hit_at(4), None, "below the last row");
}
#[test]
fn hit_carries_the_column_unit_of_each_source() {
let mut lsp_item = diag(4, DiagnosticSeverity::Error, "from a server");
lsp_item.col = 7;
lsp_item.col_utf16 = true;
let mut build_item = diag(9, DiagnosticSeverity::Error, "from cargo");
build_item.col = 7;
let mut p = ProblemsPanel::new();
p.set_groups(vec![group("a.rs", vec![lsp_item, build_item])]);
render(&mut p, 60, 6);
let utf16_of = |hit| match hit {
Some(ProblemHit::Diagnostic { col_utf16, .. }) => Some(col_utf16),
_ => None,
};
assert_eq!(
utf16_of(p.hit_at(2)),
Some(true),
"the server's diagnostic keeps its UTF-16 column"
);
assert_eq!(
utf16_of(p.hit_at(3)),
Some(false),
"the build tool's identical column is NOT UTF-16"
);
}
#[test]
fn related_locations_are_rows_under_their_diagnostic_that_jump_there() {
let mut borrow = diag(3, DiagnosticSeverity::Error, "cannot borrow `v`");
borrow.related = vec![ProblemRelated {
path: PathBuf::from("/repo/src/lib.rs"),
rel_path: String::from("src/lib.rs"),
line: 2,
col: 17,
message: String::from("immutable borrow\r\noccurs here"),
}];
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![borrow, diag(9, DiagnosticSeverity::Warning, "meh")],
)]);
let row = |screen: &str, n| screen.lines().nth(n).unwrap_or_default().to_string();
let screen = render(&mut p, 80, 6);
assert!(row(&screen, 2).contains("cannot borrow `v`"), "{screen}");
assert!(
row(&screen, 3).starts_with(&format!(
" {RELATED_INDENT}src/lib.rs [Ln 3, Col 18]: immutable borrow occurs here"
)),
"{screen}"
);
assert!(
row(&screen, 4).contains("meh"),
"the next diagnostic follows"
);
assert_eq!(
p.hit_at(3),
Some(ProblemHit::Diagnostic {
path: PathBuf::from("/repo/src/lib.rs"),
line: 2,
col: 17,
col_utf16: true,
})
);
render(&mut p, 80, 4);
p.scroll_down(10);
assert!(row(&render(&mut p, 80, 4), 3).contains("meh"));
p.toggle_group_by_file();
assert!(row(&render(&mut p, 80, 6), 2).contains("src/lib.rs [Ln 3"));
}
#[test]
fn croft_loch_rows_keep_a_one_cell_gutter_and_black_stays_flush() {
let rows = |theme: crate::theme::Theme| {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(3, DiagnosticSeverity::Error, "boom")],
)]);
let cx = ViewCx {
theme,
..ViewCx::default()
};
render_in(&mut p, &cx, 60, 4)
.lines()
.map(String::from)
.collect::<Vec<_>>()
};
let loch = rows(crate::theme::Theme::LOCH);
let black = rows(crate::theme::Theme::BLACK);
assert!(loch[1].starts_with(' '), "{loch:?}");
assert_eq!(loch[1][1..].trim_end(), black[1].trim_end(), "header row");
assert_eq!(
loch[2][1..].trim_end(),
black[2].trim_end(),
"diagnostic row"
);
assert!(!black[1].starts_with(' '), "{black:?}");
}
#[test]
fn a_row_shows_the_rule_code_after_the_message() {
let code = |source: Option<&str>| crate::lsp::manager::DiagnosticCode {
value: String::from("F401"),
source: source.map(String::from),
href: Some(String::from(
"https://docs.astral.sh/ruff/rules/unused-import",
)),
};
let mut named = diag(0, DiagnosticSeverity::Warning, "`os` imported but unused");
named.source = String::from("ruff");
named.code = Some(code(Some("Ruff")));
let mut unnamed = diag(1, DiagnosticSeverity::Error, "bad argument");
unnamed.source = String::from("ty");
unnamed.code = Some(crate::lsp::manager::DiagnosticCode {
value: String::from("invalid-argument-type"),
source: None,
href: None,
});
let plain = diag(2, DiagnosticSeverity::Error, "no code here");
let mut p = ProblemsPanel::new();
p.set_groups(vec![group("app.py", vec![named, unnamed, plain])]);
let screen = render(&mut p, 120, 8);
assert!(
screen.contains("`os` imported but unused Ruff(F401) [Ln 1"),
"{screen}"
);
assert!(
screen.contains("bad argument ty(invalid-argument-type) [Ln 2"),
"{screen}"
);
assert!(screen.contains("no code here rustc [Ln 3"), "{screen}");
assert!(!screen.contains("rustc("), "{screen}");
}
#[test]
fn the_fix_prompt_names_the_rule() {
let mut item = diag(0, DiagnosticSeverity::Warning, "`os` imported but unused");
item.source = String::from("ruff");
assert!(!fix_prompt(&item, "app.py", &[]).contains("rule"));
item.code = Some(crate::lsp::manager::DiagnosticCode {
value: String::from("F401"),
source: Some(String::from("Ruff")),
href: None,
});
assert!(
fix_prompt(&item, "app.py", &[])
.starts_with("Fix the warning reported by ruff (rule F401) at app.py:1:1")
);
}
#[test]
fn collapse_hides_diagnostic_rows() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(0, DiagnosticSeverity::Error, "boom")],
)]);
let path = PathBuf::from("/repo/src/a.rs");
render(&mut p, 60, 6);
assert_eq!(p.total_rows(), 2, "header + one diagnostic");
p.toggle_collapse(&path);
render(&mut p, 60, 6);
assert_eq!(p.total_rows(), 1, "collapsed: header only");
assert_eq!(p.hit_at(2), None, "no diagnostic row when collapsed");
assert_eq!(p.hit_at(1), Some(ProblemHit::Header(path)));
}
#[test]
fn the_empty_state_names_the_scope_it_actually_searched() {
let mut p = ProblemsPanel::new();
p.scope = ProblemScope::OpenFiles;
let text = render(&mut p, 90, 6);
assert!(
text.contains("open files"),
"scoped empty state must say so: {text:?}"
);
assert!(
!text.contains("in the workspace"),
"and must not claim the workspace is clean: {text:?}"
);
p.scope = ProblemScope::WholeProject;
let text = render(&mut p, 90, 6);
assert!(text.contains("workspace"), "unscoped keeps its wording");
}
#[test]
fn empty_shows_no_problems_message() {
let mut p = ProblemsPanel::new();
let text = render(&mut p, 60, 3);
assert!(text.contains("No problems"), "empty state: {text:?}");
}
#[test]
fn severity_glyphs_are_the_verified_codicons() {
assert_eq!(
severity_glyph(DiagnosticSeverity::Error, crate::theme::Theme::default()).0,
'\u{ea87}'
);
assert_eq!(
severity_glyph(DiagnosticSeverity::Warning, crate::theme::Theme::default()).0,
'\u{ea6c}'
);
assert_eq!(
severity_glyph(
DiagnosticSeverity::Information,
crate::theme::Theme::default()
)
.0,
'\u{ea74}'
);
assert_eq!(
severity_glyph(DiagnosticSeverity::Hint, crate::theme::Theme::default()).0,
'\u{ea74}'
);
}
#[test]
fn severity_filter_hides_lower_severities_and_empty_groups() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![
group(
"a.rs",
vec![
diag(0, DiagnosticSeverity::Error, "boom"),
diag(1, DiagnosticSeverity::Warning, "meh"),
],
),
group(
"b.rs",
vec![diag(2, DiagnosticSeverity::Warning, "only warn")],
),
]);
assert_eq!(p.total_rows(), 5);
p.cycle_filter();
assert_eq!(p.filter, ProblemFilter::Errors);
assert_eq!(p.total_rows(), 2);
assert_eq!(p.total_count(), 3);
assert_eq!(p.error_count(), 1);
}
#[test]
fn group_by_file_toggle_flattens_to_diagnostics_only() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![
group("a.rs", vec![diag(0, DiagnosticSeverity::Error, "boom")]),
group("b.rs", vec![diag(2, DiagnosticSeverity::Error, "kaboom")]),
]);
assert_eq!(p.total_rows(), 4);
p.toggle_group_by_file();
assert!(!p.group_by_file);
assert_eq!(p.total_rows(), 2);
render(&mut p, 80, 6);
assert!(matches!(p.hit_at(1), Some(ProblemHit::Diagnostic { .. })));
}
#[test]
fn active_toolbar_control_gets_the_accent_chip_default_is_plain() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(0, DiagnosticSeverity::Error, "boom")],
)]);
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 6,
};
let mut buf = Buffer::empty(area);
p.draw(&ViewCx::default(), area, &mut buf);
let chip = ViewCx::default().theme.accent_chip_bg();
let cell_bg = |b: &Buffer, r: Rect| b[(r.x, r.y)].style().bg;
assert_ne!(
cell_bg(&buf, p.filter_rect),
Some(chip),
"All filter is plain, no chip",
);
p.cycle_filter();
let mut buf = Buffer::empty(area);
p.draw(&ViewCx::default(), area, &mut buf);
assert_eq!(
cell_bg(&buf, p.filter_rect),
Some(chip),
"a non-default filter is chipped with the theme accent",
);
assert_ne!(
cell_bg(&buf, p.group_rect),
Some(chip),
"grouping is still default, so its control stays plain",
);
}
#[test]
fn toolbar_click_cycles_filter_then_toggles_grouping() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(0, DiagnosticSeverity::Error, "boom")],
)]);
render(&mut p, 80, 6);
let fr = p.filter_rect;
assert!(fr.width > 0, "filter button rect recorded");
assert!(p.click(fr.x, fr.y), "filter button consumes the click");
assert_eq!(p.filter, ProblemFilter::Errors);
let gr = p.group_rect;
assert!(p.click(gr.x, gr.y), "group button consumes the click");
assert!(!p.group_by_file);
assert!(!p.click(0, 5));
}
#[test]
fn diag_row_shows_message_and_one_based_position() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(
4,
DiagnosticSeverity::Error,
"function `run` is never used",
)],
)]);
let text = render(&mut p, 80, 4);
assert!(text.contains("function `run` is never used"), "{text:?}");
assert!(text.contains("Ln 5"), "one-based line: {text:?}");
}
#[test]
fn fix_prompt_names_the_diagnostic_and_carries_the_servers_hints() {
let mut item = diag(
6,
DiagnosticSeverity::Error,
"unused import: `std::io`\nremove it",
);
item.col = 4;
let text = fix_prompt(&item, "src/lib.rs", &[]);
assert!(
text.starts_with("Fix the error reported by rustc at src/lib.rs:7:5: unused import")
);
assert!(
text.contains("unused import: `std::io` remove it"),
"a multi-line message collapses to one line: {text}"
);
assert!(!text.contains("quick fixes"), "no hints, no hint line");
assert!(text.contains("smallest change"));
let hinted = fix_prompt(
&item,
"src/lib.rs",
&[
String::from("Remove unused import"),
String::from("Fix all"),
],
);
assert!(hinted.contains("quick fixes"));
assert!(hinted.contains("Remove unused import; Fix all"));
item.source.clear();
item.severity = DiagnosticSeverity::Hint;
let anon = fix_prompt(&item, "a.py", &[]);
assert!(anon.starts_with("Fix the diagnostic reported by a diagnostic tool at a.py:7:5"));
}
#[test]
fn the_row_being_fixed_wears_the_spinner() {
let mut p = ProblemsPanel::new();
let path = PathBuf::from("/w/src/a.rs");
p.set_groups(vec![ProblemGroup {
path: path.clone(),
name: "a.rs".into(),
rel_dir: "src".into(),
items: vec![
diag(3, DiagnosticSeverity::Error, "first"),
diag(9, DiagnosticSeverity::Error, "second"),
],
}]);
let before = render(&mut p, 60, 6);
assert!(
!before.contains('\u{25DC}'),
"no spinner while nothing is being fixed"
);
p.fixing = Some((path.clone(), 9));
p.fix_glyph = "\u{25DC}";
let out = render(&mut p, 60, 6);
let rows: Vec<&str> = out.lines().collect();
let first = rows.iter().find(|r| r.contains("first")).unwrap();
let second = rows.iter().find(|r| r.contains("second")).unwrap();
assert!(
!first.contains('\u{25DC}'),
"the other row keeps its glyph: {first}"
);
assert!(
second.contains('\u{25DC}'),
"the fixing row shows the spinner: {second}"
);
assert!(
!second.contains(GLYPH_ERROR),
"in place of its severity glyph: {second}"
);
assert_eq!(
p.diagnostic_at(2).map(|(pth, item)| (pth, item.line)),
Some((path, 3)),
"the row under the pointer resolves to its whole diagnostic"
);
}
}