fix(tui): refine log selection and filters, label unlinked content

This commit is contained in:
objz committed 2026-10-04 12:12:11 +02:00
1 parent 8adadf75a8
commit b5c680ed55
13 files changed
+906 -365

No files matched your search

+4 -8
View File
@@ -48,12 +48,10 @@ pub struct App {
pub(super) instance_manager: InstanceManager,
pub(super) log_overlay_scroll: usize,
pub(super) log_overlay_max_scroll: usize,
pub(super) log_overlay_page: usize,
pub(super) log_filter_open: bool,
pub(super) log_filter_selected: usize,
pub(super) log_hidden_levels: Vec<crate::instance::launch::parser::LogLevel>,
pub(super) log_selection: Option<(usize, usize)>,
pub(super) log_selecting: bool,
pub(super) log_level_filters: widgets::logs_viewer::LevelFilters,
pub(super) log_selection: widgets::log_selection::LogSelection,
pub(super) log_overlay_inner: ratatui::layout::Rect,
pub(super) log_overlay_search: widgets::search::SearchState,
pub(super) log_overlay_scrollbar: ratatui::widgets::ScrollbarState,
@@ -244,12 +242,10 @@ impl App {
instance_manager: manager,
log_overlay_scroll: 0,
log_overlay_max_scroll: 0,
log_overlay_page: 0,
log_filter_open: false,
log_filter_selected: 0,
log_hidden_levels: Vec::new(),
log_selection: None,
log_selecting: false,
log_level_filters: [None; 5],
log_selection: widgets::log_selection::LogSelection::default(),
log_overlay_inner: ratatui::layout::Rect::default(),
log_overlay_search: widgets::search::SearchState::default(),
log_overlay_scrollbar: ratatui::widgets::ScrollbarState::default(),
+44 -160
View File
@@ -62,134 +62,43 @@ impl App {
}
fn handle_log_selection_mouse(&mut self, event: MouseEvent) -> bool {
use ratatui::layout::Position;
let at = Position::new(event.column, event.row);
if !matches!(
event.kind,
MouseEventKind::Down(MouseButton::Left)
| MouseEventKind::Drag(MouseButton::Left)
| MouseEventKind::Up(MouseButton::Left)
) {
return false;
}
if self
.content_update_popup
.as_ref()
.is_some_and(widgets::content::update::State::visible)
|| self.provider_conflict.is_some()
|| self.modpack_versions_state.is_some()
|| self.modpack_update_popup.is_some()
{
return false;
}
if self.focused == FocusedArea::OverviewExpanded && !self.log_filter_open {
let area = self.log_overlay_inner;
match event.kind {
MouseEventKind::Down(MouseButton::Left) => {
if area.is_empty() || !area.contains(at) {
return false;
}
let count = self.overlay_filtered_lines().len();
if count == 0 {
return false;
}
let index = (self.log_overlay_scroll
+ usize::from(event.row.saturating_sub(area.y)))
.min(count - 1);
self.log_selecting = true;
self.log_selection = Some((index, index));
true
}
MouseEventKind::Drag(MouseButton::Left) => {
if !self.log_selecting {
return false;
}
let count = self.overlay_filtered_lines().len();
if count == 0 {
return false;
}
let relative = usize::from(event.row.saturating_sub(area.y))
.min(usize::from(area.height.saturating_sub(1)));
let index = (self.log_overlay_scroll + relative).min(count - 1);
if let Some(selection) = self.log_selection.as_mut() {
selection.1 = index;
}
true
}
MouseEventKind::Up(MouseButton::Left) => {
if !self.log_selecting {
return false;
}
self.log_selecting = false;
true
}
_ => false,
}
let lines = self.overlay_filtered_lines();
self.log_selection.handle_mouse(
event,
self.log_overlay_inner,
self.log_overlay_scroll,
&lines,
)
} else if self.focused == FocusedArea::Content
&& self.content_tab == widgets::content::ContentTab::Logs
&& self.content_mode == widgets::content::ContentMode::Installed
&& !self.logs_state.filter_open
{
let area = self.logs_state.viewer_area;
match event.kind {
MouseEventKind::Down(MouseButton::Left) => {
if area.is_empty() || !area.contains(at) {
return false;
}
let count = widgets::logs_viewer::filtered_viewer_line_count(&self.logs_state);
if count == 0 {
return false;
}
let index = (self.logs_state.viewer_scroll
+ usize::from(event.row.saturating_sub(area.y)))
.min(count - 1);
self.logs_state.selecting = true;
self.logs_state.selection = Some((index, index));
true
}
MouseEventKind::Drag(MouseButton::Left) => {
if !self.logs_state.selecting {
return false;
}
let count = widgets::logs_viewer::filtered_viewer_line_count(&self.logs_state);
if count == 0 {
return false;
}
let relative = usize::from(event.row.saturating_sub(area.y))
.min(usize::from(area.height.saturating_sub(1)));
let index = (self.logs_state.viewer_scroll + relative).min(count - 1);
if let Some(selection) = self.logs_state.selection.as_mut() {
selection.1 = index;
}
true
}
MouseEventKind::Up(MouseButton::Left) => {
if !self.logs_state.selecting {
return false;
}
self.logs_state.selecting = false;
true
}
_ => false,
}
widgets::logs_viewer::handle_selection_mouse(event, &mut self.logs_state)
} else {
false
}
}
fn yank_overlay_selection(&mut self) {
let Some((from, to)) = self
.log_selection
.map(|(first, second)| (first.min(second), first.max(second)))
else {
error_buffer::push_message(
tracing::Level::INFO,
"Drag across log lines to select them, then press y to copy",
);
return;
};
let lines = self.overlay_filtered_lines();
if lines.is_empty() {
return;
}
let end = to.min(lines.len() - 1);
if from > end {
return;
}
match widgets::logs_viewer::copy_to_clipboard(&lines[from..=end].join("\n")) {
Some((count, false)) => error_buffer::push_message(
tracing::Level::INFO,
format!("Copied {count} line(s) to the clipboard"),
),
Some((count, true)) => error_buffer::push_message(
tracing::Level::WARN,
format!("Copied the first {count} lines; the selection was truncated"),
),
None => {}
}
}
pub(super) fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> {
if self.content_update_popup.as_ref().is_some_and(|update| {
update.phase != widgets::content::update::Phase::Applying
@@ -299,38 +208,22 @@ impl App {
// log overlay eats all input when open, including its own search sub-mode
if self.focused == FocusedArea::OverviewExpanded {
if self.log_filter_open {
match key_event.code {
KeyCode::Esc | KeyCode::Char('f') => {
self.log_filter_open = false;
}
KeyCode::Char('j') | KeyCode::Down => {
self.log_filter_selected = (self.log_filter_selected + 1).min(
crate::tui::widgets::logs_viewer::LOG_LEVEL_FILTER_ORDER.len() - 1,
);
}
KeyCode::Char('k') | KeyCode::Up => {
self.log_filter_selected = self.log_filter_selected.saturating_sub(1);
}
KeyCode::Enter | KeyCode::Char(' ') => {
crate::tui::widgets::logs_viewer::toggle_hidden_level(
&mut self.log_hidden_levels,
self.log_filter_selected,
);
self.log_selection = None;
self.log_overlay_scroll = 0;
}
KeyCode::Char('r') => {
self.log_hidden_levels.clear();
}
_ => {}
if widgets::logs_viewer::handle_level_filter_key(
&key_event,
&mut self.log_filter_open,
&mut self.log_filter_selected,
&mut self.log_level_filters,
) {
self.log_selection.clear();
self.log_overlay_scroll = 0;
}
return Ok(());
}
if self.log_overlay_search.active {
self.log_selection.clear();
match key_event.code {
KeyCode::Enter => {
self.log_overlay_search.confirm();
self.log_selection = None;
self.log_overlay_scroll = 0;
}
KeyCode::Esc => {
@@ -348,10 +241,7 @@ impl App {
}
match key_event.code {
KeyCode::Char('O') | KeyCode::Esc => {
if self.log_selection.take().is_some() {
self.log_selecting = false;
return Ok(());
}
self.log_selection.clear();
self.focused = self.pre_overlay_focused;
self.log_overlay_search.deactivate();
return Ok(());
@@ -374,18 +264,8 @@ impl App {
self.log_overlay_scroll = 0;
return Ok(());
}
KeyCode::PageDown => {
let page = self.log_overlay_page.max(1);
self.log_overlay_scroll =
(self.log_overlay_scroll + page).min(self.log_overlay_max_scroll);
return Ok(());
}
KeyCode::PageUp => {
let page = self.log_overlay_page.max(1);
self.log_overlay_scroll = self.log_overlay_scroll.saturating_sub(page);
return Ok(());
}
KeyCode::Char('/') => {
self.log_selection.clear();
self.log_overlay_search.activate();
return Ok(());
}
@@ -395,8 +275,11 @@ impl App {
return Ok(());
}
KeyCode::Char('y') => {
self.log_selecting = false;
self.yank_overlay_selection();
self.log_selection.finish();
widgets::logs_viewer::yank_selection(
&self.log_selection,
&self.overlay_filtered_lines(),
);
return Ok(());
}
_ => {
@@ -776,6 +659,7 @@ impl App {
} else if self.focused == FocusedArea::Content {
if self.content_tab == widgets::content::ContentTab::Logs {
if key_event.code == KeyCode::Char('d')
&& !self.logs_state.filter_open
&& !self.logs_state.search.active
&& !self.logs_state.viewer_search.active
{
+27 -22
View File
@@ -222,7 +222,10 @@ impl App {
.into_iter()
.filter(|line| self.log_overlay_search.matches(line))
.filter(|line| {
!super::widgets::logs_viewer::level_hidden(&self.log_hidden_levels, line)
widgets::logs_viewer::level_matches(
&self.log_level_filters,
widgets::logs_viewer::level_of_line(line),
)
})
.collect()
}
@@ -245,23 +248,34 @@ impl App {
let filtered = self.overlay_filtered_lines();
let visible_height = overlay.height.saturating_sub(2) as usize;
self.log_overlay_page = visible_height;
// Only follow new lines when pinned to the very bottom; being even
// one line up means the user is reading history.
let was_at_bottom = self.log_overlay_scroll >= self.log_overlay_max_scroll;
self.log_overlay_max_scroll = filtered.len().saturating_sub(visible_height);
if was_at_bottom || self.log_overlay_scroll > self.log_overlay_max_scroll {
if (was_at_bottom && self.log_selection.range.is_none())
|| self.log_overlay_scroll > self.log_overlay_max_scroll
{
self.log_overlay_scroll = self.log_overlay_max_scroll;
}
self.log_overlay_scrollbar =
ratatui::widgets::ScrollbarState::new(self.log_overlay_max_scroll)
.position(self.log_overlay_scroll);
let title = if self.log_hidden_levels.is_empty() {
let active_filters = self.log_level_filters.iter().flatten().count();
let title = if active_filters == 0 {
" Logs ".to_owned()
} else {
format!(" Logs · {} hidden ", self.log_hidden_levels.len())
format!(" Logs · {active_filters} filter(s) ")
};
let mut keybinds = vec![
("Esc", " close"),
("f", " filter"),
("g/G", " top/bottom"),
("/", " search"),
];
if self.log_selection.range.is_some() {
keybinds.insert(1, ("y", " yank"));
}
let mut block = Block::bordered()
.title_top(
Line::from(title).style(
@@ -271,14 +285,7 @@ impl App {
),
)
.title_bottom(
crate::tui::widgets::popups::keybind_line(&[
("O", " close"),
("f", " filter"),
("y", " copy"),
("PgUp/PgDn", " page"),
("/", " search"),
])
.alignment(Alignment::Right),
crate::tui::widgets::popups::keybind_line(&keybinds).alignment(Alignment::Right),
)
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(theme.accent()))
@@ -293,20 +300,18 @@ impl App {
self.log_overlay_inner = inner;
let search = &self.log_overlay_search;
let selected = self
.log_selection
.map(|(from, to)| (from.min(to), from.max(to)));
let styled: Vec<Line> = filtered
.iter()
.enumerate()
.skip(self.log_overlay_scroll)
.take(visible_height)
.map(|(index, line)| {
let mut style = super::widgets::logs_viewer::line_level_style(line);
if selected.is_some_and(|(from, to)| index >= from && index <= to) {
style = style.add_modifier(Modifier::REVERSED);
}
search.highlight_line(line, style)
self.log_selection.highlight_line(
index,
line,
search,
widgets::logs_viewer::line_level_style(line),
)
})
.collect();
@@ -328,7 +333,7 @@ impl App {
frame,
overlay,
self.log_filter_selected,
&self.log_hidden_levels,
&self.log_level_filters,
);
}
}
+142 -13
View File
@@ -795,7 +795,7 @@ fn checking_popup_locks_input_until_cancelled() {
}
#[test]
fn log_overlay_pages_and_stays_put_while_reading_history() {
fn log_overlay_ignores_page_keys_and_stays_put_while_reading_history() {
use crate::tui::logging::{clear_app_logs, push_app_log};
let mut ui = UiHarness::new();
clear_app_logs();
@@ -809,9 +809,13 @@ fn log_overlay_pages_and_stays_put_while_reading_history() {
assert_eq!(ui.app.log_overlay_scroll, 14);
ui.key(KeyCode::PageUp);
assert_eq!(ui.app.log_overlay_scroll, 0);
assert_eq!(ui.app.log_overlay_scroll, 14);
ui.key(KeyCode::PageDown);
assert_eq!(ui.app.log_overlay_scroll, 14);
assert!(ui.screen().contains("[g/G] top/bottom"));
assert!(ui.screen().contains("[Esc] close"));
assert!(!ui.screen().contains("PgUp"));
assert!(!ui.screen().contains("[y]"));
for _ in 0..5 {
ui.key(KeyCode::Char('k'));
}
@@ -833,26 +837,44 @@ fn log_overlay_pages_and_stays_put_while_reading_history() {
}
#[test]
fn log_overlay_level_filter_opens_toggles_and_closes() {
use crate::instance::launch::parser::LogLevel;
fn log_overlay_level_filter_opens_cycles_and_closes() {
use crate::tui::logging::{clear_app_logs, push_app_log};
use crate::tui::widgets::content::discovery::CategoryFilter;
let mut ui = UiHarness::new();
clear_app_logs();
push_app_log("12:00:00:ERROR:rmcl: failed".to_owned());
push_app_log("12:00:00:INFO:rmcl: done".to_owned());
ui.app.focused = FocusedArea::OverviewExpanded;
ui.key(KeyCode::Char('f'));
assert!(ui.app.log_filter_open);
ui.draw();
assert!(ui.screen().contains("Log levels"));
assert!(ui.screen().contains("· Error"));
ui.key(KeyCode::Enter);
assert_eq!(ui.app.log_hidden_levels, vec![LogLevel::Error]);
assert_eq!(ui.app.log_level_filters[0], Some(CategoryFilter::Include));
ui.draw();
assert!(ui.screen().contains("1 hidden"));
assert!(ui.screen().contains("+ Error"));
assert!(ui.screen().contains("1 filter(s)"));
ui.key(KeyCode::Esc);
ui.draw();
assert!(ui.screen().contains("failed"));
assert!(!ui.screen().contains("done"));
ui.key(KeyCode::Char('f'));
ui.key(KeyCode::Enter);
ui.draw();
assert!(ui.screen().contains("− Error"));
ui.key(KeyCode::Esc);
assert!(!ui.app.log_filter_open);
assert_eq!(ui.app.log_hidden_levels, vec![LogLevel::Error]);
assert_eq!(ui.app.log_level_filters[0], Some(CategoryFilter::Exclude));
ui.draw();
assert!(!ui.screen().contains("failed"));
assert!(ui.screen().contains("done"));
clear_app_logs();
}
#[test]
fn mouse_drag_selects_viewer_lines_for_yank() {
fn mouse_drag_selects_viewer_characters_and_click_clears_yank_hint() {
use crate::instance::logs::files::LogFileEntry;
use crossterm::event::KeyModifiers;
let mut ui = UiHarness::new();
@@ -871,6 +893,7 @@ fn mouse_drag_selects_viewer_lines_for_yank() {
ui.app.logs_state.viewer_lines =
vec!["alpha".to_owned(), "beta".to_owned(), "gamma".to_owned()];
ui.draw();
assert!(!ui.screen().contains("[y]"));
let area = ui.app.logs_state.viewer_area;
assert!(area.height >= 3);
let click = |kind, row| MouseEvent {
@@ -881,16 +904,36 @@ fn mouse_drag_selects_viewer_lines_for_yank() {
};
ui.app
.handle_mouse_event(click(MouseEventKind::Down(MouseButton::Left), area.y));
assert!(ui.app.logs_state.selection.range.is_none());
ui.app
.handle_mouse_event(click(MouseEventKind::Drag(MouseButton::Left), area.y + 1));
ui.app
.handle_mouse_event(click(MouseEventKind::Up(MouseButton::Left), area.y + 1));
assert_eq!(ui.app.logs_state.selection, Some((0, 1)));
assert!(!ui.app.logs_state.selecting);
assert_eq!(ui.app.logs_state.selection.range, Some(((0, 2), (1, 2))));
assert_eq!(
ui.app
.logs_state
.selection
.text(&["alpha", "beta", "gamma"])
.as_deref(),
Some("pha\nbe")
);
assert!(ui.app.logs_state.viewer_focused);
ui.draw();
assert!(ui.screen().contains("[y] yank"));
assert!(ui.screen().contains("[g/G] top/bottom"));
assert!(!ui.screen().contains("PgUp"));
ui.app
.handle_mouse_event(click(MouseEventKind::Down(MouseButton::Left), area.y));
ui.app
.handle_mouse_event(click(MouseEventKind::Up(MouseButton::Left), area.y));
ui.draw();
assert!(ui.app.logs_state.selection.range.is_none());
assert!(!ui.screen().contains("[y]"));
}
#[test]
fn mouse_drag_selects_overlay_lines_for_yank() {
fn mouse_drag_selects_overlay_characters_for_yank_and_escape_closes() {
use crate::tui::logging::{clear_app_logs, push_app_log};
use crossterm::event::KeyModifiers;
let mut ui = UiHarness::new();
@@ -914,16 +957,102 @@ fn mouse_drag_selects_overlay_lines_for_yank() {
.handle_mouse_event(click(MouseEventKind::Drag(MouseButton::Left), area.y + 2));
ui.app
.handle_mouse_event(click(MouseEventKind::Up(MouseButton::Left), area.y + 2));
assert_eq!(ui.app.log_selection, Some((0, 2)));
assert_eq!(ui.app.log_selection.range, Some(((0, 2), (2, 2))));
ui.draw();
assert!(ui.screen().contains("[y] yank"));
ui.key(KeyCode::Char('y'));
assert!(
crate::feedback::errors::peek_all_errors()
.iter()
.any(|event| event.message.contains("Copied 3 line(s)"))
.any(|event| event.message.contains("Yanked 3 line(s)"))
);
ui.app
.handle_mouse_event(click(MouseEventKind::Down(MouseButton::Left), area.y));
ui.app
.handle_mouse_event(click(MouseEventKind::Up(MouseButton::Left), area.y));
ui.draw();
assert!(!ui.screen().contains("[y]"));
ui.app
.handle_mouse_event(click(MouseEventKind::Down(MouseButton::Left), area.y));
ui.app
.handle_mouse_event(click(MouseEventKind::Drag(MouseButton::Left), area.y + 1));
ui.key(KeyCode::Esc);
assert_ne!(ui.app.focused, FocusedArea::OverviewExpanded);
assert!(ui.app.log_selection.range.is_none());
clear_app_logs();
}
#[test]
fn log_level_popup_does_not_delete_logs_or_leave_on_tab() {
use crate::instance::logs::files::LogFileEntry;
let mut ui = UiHarness::new();
ui.add_instance("A");
ui.app.focused = FocusedArea::Content;
ui.app.content_tab = ContentTab::Logs;
ui.app.logs_state.loaded_for = Some("A".to_owned());
ui.app.logs_state.entries.push(LogFileEntry {
name: "a.log".to_owned(),
path: ui.instance_path("A").join("a.log"),
});
ui.app.logs_state.list_state.selected = Some(0);
ui.key(KeyCode::Char('f'));
ui.key(KeyCode::Char('d'));
assert_eq!(ui.app.focused, FocusedArea::Content);
assert!(ui.app.logs_state.filter_open);
ui.key(KeyCode::Tab);
assert_eq!(ui.app.content_mode, ContentMode::Installed);
ui.draw();
assert!(ui.screen().contains("· Error"));
assert!(ui.screen().contains("[Esc] close"));
ui.key(KeyCode::Esc);
assert!(!ui.app.logs_state.filter_open);
}
#[test]
fn selected_unlinked_content_explains_why_versions_are_unavailable() {
let mut ui = UiHarness::new();
ui.add_instance("A");
let minecraft = ui
.instance_path("A")
.join(crate::storage::MINECRAFT_DIR_NAME);
let path = minecraft.join("mods/local.jar");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "local mod").unwrap();
let mut record = managed_mod_record(&minecraft, "mods/local.jar", "local", false, Vec::new());
record.resolution = Resolution::Unmatched {
checked_at: 1,
providers: vec!["modrinth".to_owned()],
};
let mut manifest = ContentManifest::default();
manifest.upsert(record);
ui.app
.mods_state
.entries
.push(content_entry("scoreboardinternal", path));
ui.app.mods_state.loaded_for = Some("A".to_owned());
ui.app.mods_state.list_state.selected = Some(0);
ui.app
.mods_state
.apply_manifest(&manifest, &minecraft, ContentKind::Mod);
ui.app.focused = FocusedArea::Content;
ui.draw();
assert!(ui.screen().contains("Unlinked"));
assert!(
ui.screen()
.contains("No online source linked; version switching unavailable.")
);
ui.key(KeyCode::Char('v'));
assert!(ui.app.mods_discovery_state.version_popup.is_none());
manifest.files[0].resolution = Resolution::Pending;
ui.app
.mods_state
.apply_manifest(&manifest, &minecraft, ContentKind::Mod);
ui.draw();
assert!(!ui.screen().contains("Unlinked"));
assert!(!ui.screen().contains("No online source linked"));
}
#[test]
fn settings_panel_routes_legacy_edit_keys_to_tui_popups() {
let mut ui = UiHarness::new();
+2 -4
View File
@@ -106,12 +106,10 @@ impl UiHarness {
instance_manager,
log_overlay_scroll: 0,
log_overlay_max_scroll: 0,
log_overlay_page: 0,
log_filter_open: false,
log_filter_selected: 0,
log_hidden_levels: Vec::new(),
log_selection: None,
log_selecting: false,
log_level_filters: [None; 5],
log_selection: widgets::log_selection::LogSelection::default(),
log_overlay_inner: ratatui::layout::Rect::default(),
log_overlay_search: widgets::search::SearchState::default(),
log_overlay_scrollbar: ratatui::widgets::ScrollbarState::default(),
+86
View File
@@ -1391,6 +1391,92 @@ fn manifest_metadata_keeps_an_embedded_icon_renderer() {
assert!(state.image_protocols.contains_key("installed"));
}
#[test]
fn unlinked_badge_is_subdued_and_requires_a_completed_unmatched_lookup() {
use crate::instance::{
ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, Resolution,
};
let minecraft = PathBuf::from("instance/minecraft");
let mut installed = entry("scoreboardinternal");
installed.path = minecraft.join("mods/local.jar");
installed.footer_label = Some("1.0.0".to_owned());
let mut state = ContentListState::default();
state.set_entries(vec![installed]);
let mut manifest = ContentManifest::default();
manifest.upsert(ContentFileRecord {
relative_path: PathBuf::from("mods/local.jar"),
kind: ContentKind::Mod,
enabled: true,
fingerprint: FileFingerprint {
size: 0,
modified_ns: 0,
hashes: Default::default(),
},
resolution: Resolution::Unmatched {
checked_at: 1,
providers: vec!["modrinth".to_owned()],
},
provider_aliases: Vec::new(),
provider_checks: vec!["modrinth".to_owned()],
required_dependencies: Vec::new(),
automatic_dependency: false,
cleanup_eligible: false,
});
state.apply_manifest(&manifest, &minecraft, ContentKind::Mod);
state.apply_update_snapshot(None);
assert!(state.selected_is_unlinked());
let picker = ratatui_image::picker::Picker::halfblocks();
let theme = crate::config::theme::THEME.as_ref();
let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(50, 4)).unwrap();
for focused in [false, true] {
terminal
.draw(|frame| {
super::render(
frame,
frame.area(),
&mut state,
focused,
"Loading...",
"Empty",
&picker,
false,
false,
)
})
.unwrap();
let buffer = terminal.backend().buffer();
let row = (0..50).map(|x| buffer[(x, 0)].symbol()).collect::<String>();
let x = row.find("Unlinked").expect("unlinked badge") as u16;
assert_eq!(buffer[(x, 0)].fg, theme.text_dim());
assert_eq!(buffer[(x, 0)].bg, theme.surface());
assert!(!buffer[(x, 0)].modifier.contains(Modifier::BOLD));
assert!(terminal.backend().to_string().contains("1.0.0"));
}
for resolution in [
Resolution::Pending,
Resolution::Unmatched {
checked_at: 1,
providers: Vec::new(),
},
Resolution::Ambiguous {
candidates: Vec::new(),
},
Resolution::Resolved {
project: crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "project".to_owned(),
version_id: "version".to_owned(),
},
},
] {
manifest.files[0].resolution = resolution;
state.apply_manifest(&manifest, &minecraft, ContentKind::Mod);
assert!(!state.selected_is_unlinked());
}
state.apply_manifest(&ContentManifest::default(), &minecraft, ContentKind::Mod);
assert!(state.unlinked_paths.is_empty());
}
#[test]
fn provider_metadata_fills_a_missing_installed_description() {
let mut state = ContentListState::default();
+157
View File
@@ -0,0 +1,157 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use crossterm::event::KeyModifiers;
use super::*;
fn mouse(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent {
MouseEvent {
kind,
column,
row,
modifiers: KeyModifiers::NONE,
}
}
#[test]
fn clicks_clear_selection_and_only_dragging_selects_characters() {
let mut selection = LogSelection::default();
let area = Rect::new(0, 0, 20, 4);
let lines = ["alpha", "beta"];
assert!(!selection.handle_mouse(
mouse(MouseEventKind::Drag(MouseButton::Left), 4, 0),
area,
0,
&lines
));
assert!(selection.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 1, 0),
area,
0,
&lines
));
assert!(selection.range.is_none());
assert!(selection.handle_mouse(
mouse(MouseEventKind::Drag(MouseButton::Left), 4, 0),
area,
0,
&lines
));
assert_eq!(selection.text(&lines).as_deref(), Some("lph"));
assert!(selection.handle_mouse(
mouse(MouseEventKind::Up(MouseButton::Left), 4, 0),
area,
0,
&lines
));
assert!(!selection.handle_mouse(
mouse(MouseEventKind::Drag(MouseButton::Left), 5, 0),
area,
0,
&lines
));
let search = SearchState {
query: "alpha".to_owned(),
..Default::default()
};
let highlighted = selection.highlight_line(0, "alpha", &search, Style::default());
assert_eq!(
highlighted
.spans
.iter()
.filter(|span| span.style.add_modifier.contains(Modifier::REVERSED))
.map(|span| span.content.as_ref())
.collect::<String>(),
"lph"
);
assert!(
highlighted
.spans
.iter()
.all(|span| span.style.add_modifier.contains(Modifier::UNDERLINED))
);
selection.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 2, 0),
area,
0,
&lines,
);
selection.handle_mouse(
mouse(MouseEventKind::Up(MouseButton::Left), 2, 0),
area,
0,
&lines,
);
assert!(selection.range.is_none());
assert!(selection.text(&lines).is_none());
selection.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 2, 0),
area,
0,
&lines,
);
selection.handle_mouse(
mouse(MouseEventKind::Drag(MouseButton::Left), 0, 1),
area,
0,
&lines,
);
assert_eq!(selection.text(&lines).as_deref(), Some("pha\n"));
selection.handle_mouse(
mouse(MouseEventKind::Drag(MouseButton::Left), 0, 3),
area,
0,
&lines,
);
assert_eq!(selection.text(&lines).as_deref(), Some("pha\nbeta"));
}
#[test]
fn selection_handles_reverse_multiline_drags_scroll_and_unicode_cells() {
let mut selection = LogSelection::default();
let area = Rect::new(10, 5, 20, 4);
let lines = ["hidden", "alpha", "beta"];
selection.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 12, 6),
area,
1,
&lines,
);
selection.handle_mouse(
mouse(MouseEventKind::Drag(MouseButton::Left), 11, 5),
area,
1,
&lines,
);
assert_eq!(selection.text(&lines).as_deref(), Some("lpha\nbe"));
let lines = ["a界e\u{0301}🙂z"];
selection.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 12, 5),
area,
0,
&lines,
);
selection.handle_mouse(
mouse(MouseEventKind::Drag(MouseButton::Left), 16, 5),
area,
0,
&lines,
);
assert_eq!(selection.text(&lines).as_deref(), Some("界e\u{0301}🙂"));
let highlighted =
selection.highlight_line(0, lines[0], &SearchState::default(), Style::default());
assert_eq!(
highlighted
.spans
.iter()
.filter(|span| span.style.add_modifier.contains(Modifier::REVERSED))
.map(|span| span.content.as_ref())
.collect::<String>(),
"界e\u{0301}🙂"
);
}
+54 -21
View File
@@ -58,20 +58,16 @@ fn shift_enter_without_a_selected_log_is_swallowed_without_opening() {
}
#[test]
fn viewer_pages_by_visible_height() {
fn viewer_ignores_page_keys_and_keeps_top_bottom_navigation() {
let mut state = LogsState {
viewer_focused: true,
viewer_max_scroll: 30,
viewer_page: 10,
..Default::default()
};
let page = |code| KeyEvent::new(code, KeyModifiers::NONE);
assert!(handle_key(&page(KeyCode::PageDown), &mut state));
assert_eq!(state.viewer_scroll, 10);
assert!(handle_key(&page(KeyCode::PageDown), &mut state));
assert_eq!(state.viewer_scroll, 20);
assert!(handle_key(&page(KeyCode::PageUp), &mut state));
assert_eq!(state.viewer_scroll, 10);
assert!(!handle_key(&page(KeyCode::PageDown), &mut state));
assert!(!handle_key(&page(KeyCode::PageUp), &mut state));
assert_eq!(state.viewer_scroll, 0);
assert!(handle_key(&page(KeyCode::Home), &mut state));
assert_eq!(state.viewer_scroll, 0);
assert!(handle_key(&page(KeyCode::End), &mut state));
@@ -79,10 +75,14 @@ fn viewer_pages_by_visible_height() {
}
#[test]
fn yank_copies_the_selected_viewer_lines() {
fn yank_copies_only_the_selected_viewer_characters() {
let mut state = LogsState {
viewer_lines: vec!["first".to_owned(), "second".to_owned(), "third".to_owned()],
selection: Some((2, 0)),
selection: {
let mut selection = LogSelection::default();
selection.range = Some(((2, 3), (0, 2)));
selection
},
..Default::default()
};
let yank = KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE);
@@ -90,7 +90,7 @@ fn yank_copies_the_selected_viewer_lines() {
assert!(
crate::feedback::errors::peek_all_errors()
.iter()
.any(|event| event.message.contains("Copied 3 line(s)"))
.any(|event| event.message.contains("Yanked 3 line(s)"))
);
}
@@ -113,8 +113,16 @@ fn log_levels_share_one_color_mapping_in_viewer_and_overlay() {
}
assert_eq!(
line_level_style("12:17:28:DEBUG:rmcl::net: fetching").fg,
Some(theme.info())
);
assert_eq!(
line_level_style("12:17:28:TRACE:rmcl::net: fetching").fg,
Some(theme.text_dim())
);
assert_ne!(
log_level_style(LogLevel::Debug).fg,
log_level_style(LogLevel::Trace).fg
);
assert_eq!(
line_level_style("[20:10:46] [Render thread/INFO]: done").fg,
Some(theme.text())
@@ -177,7 +185,7 @@ fn rescans_and_runtime_changes_keep_the_selected_log_and_viewer_in_sync() {
}
#[test]
fn unclassified_lines_have_no_level_and_are_never_filtered() {
fn unclassified_lines_have_no_level_and_follow_category_filter_rules() {
use crate::instance::launch::parser::LogLevel;
assert_eq!(level_of_line("just some output"), None);
assert_eq!(
@@ -188,32 +196,40 @@ fn unclassified_lines_have_no_level_and_are_never_filtered() {
level_of_line("tracing trace message"),
Some(LogLevel::Trace)
);
assert!(!level_hidden(&[LogLevel::Debug], "just some output"));
let mut filters = [None; 5];
filters[3] = Some(CategoryFilter::Exclude);
assert!(level_matches(&filters, None));
filters[0] = Some(CategoryFilter::Include);
assert!(!level_matches(&filters, None));
assert!(level_matches(&filters, Some(LogLevel::Error)));
assert!(!level_matches(&filters, Some(LogLevel::Debug)));
}
#[test]
fn level_filter_panel_toggles_resets_and_closes() {
use crate::instance::launch::parser::LogLevel;
fn level_filter_panel_cycles_neutral_include_exclude_resets_and_closes() {
let mut state = LogsState::default();
let press = |code| KeyEvent::new(code, KeyModifiers::NONE);
assert!(handle_key(&press(KeyCode::Char('f')), &mut state));
assert!(state.filter_open);
assert!(handle_key(&press(KeyCode::Enter), &mut state));
assert_eq!(state.hidden_levels, vec![LogLevel::Error]);
assert_eq!(state.level_filters[0], Some(CategoryFilter::Include));
assert!(handle_key(&press(KeyCode::Enter), &mut state));
assert_eq!(state.level_filters[0], Some(CategoryFilter::Exclude));
assert!(handle_key(&press(KeyCode::Enter), &mut state));
assert_eq!(state.level_filters[0], None);
assert!(handle_key(&press(KeyCode::Char('j')), &mut state));
assert!(handle_key(&press(KeyCode::Enter), &mut state));
assert_eq!(state.hidden_levels, vec![LogLevel::Error, LogLevel::Warn]);
assert_eq!(state.level_filters[1], Some(CategoryFilter::Include));
assert!(handle_key(&press(KeyCode::Enter), &mut state));
assert_eq!(state.hidden_levels, vec![LogLevel::Error]);
assert_eq!(state.level_filters[1], Some(CategoryFilter::Exclude));
assert!(handle_key(&press(KeyCode::Char('r')), &mut state));
assert!(state.hidden_levels.is_empty());
assert_eq!(state.level_filters, [None; 5]);
assert!(handle_key(&press(KeyCode::Esc), &mut state));
assert!(!state.filter_open);
}
#[test]
fn level_filter_hides_matching_lines_but_keeps_unclassified_ones() {
use crate::instance::launch::parser::LogLevel;
fn rendered(state: &mut LogsState) -> String {
let mut terminal =
ratatui::Terminal::new(ratatui::backend::TestBackend::new(70, 6)).unwrap();
@@ -237,9 +253,26 @@ fn level_filter_hides_matching_lines_but_keeps_unclassified_ones() {
..Default::default()
};
assert!(rendered(&mut state).contains("fetching versions"));
state.hidden_levels.push(LogLevel::Debug);
state.level_filters[3] = Some(CategoryFilter::Exclude);
let shown = rendered(&mut state);
assert!(!shown.contains("fetching versions"));
assert!(shown.contains("done"));
assert!(shown.contains("plain line"));
state.level_filters[2] = Some(CategoryFilter::Include);
let shown = rendered(&mut state);
assert!(shown.contains("done"));
assert!(!shown.contains("plain line"));
}
#[test]
fn included_levels_form_a_union_and_excluded_levels_stay_hidden() {
let mut filters = [None; 5];
filters[0] = Some(CategoryFilter::Include);
filters[1] = Some(CategoryFilter::Include);
filters[3] = Some(CategoryFilter::Exclude);
assert!(level_matches(&filters, Some(LogLevel::Error)));
assert!(level_matches(&filters, Some(LogLevel::Warn)));
assert!(!level_matches(&filters, Some(LogLevel::Info)));
assert!(!level_matches(&filters, Some(LogLevel::Debug)));
assert!(!level_matches(&filters, None));
}
+42 -2
View File
@@ -265,6 +265,7 @@ pub struct ContentListState {
pending_provider_icons: Arc<Mutex<Vec<PendingProviderIcon>>>,
project_metadata: HashMap<(String, String), crate::net::modrinth::ProjectInfo>,
version_metadata: HashMap<(String, String), crate::net::modrinth::VersionInfo>,
unlinked_paths: HashSet<std::path::PathBuf>,
requested_provider_icons: HashSet<(String, String, String)>,
pub local_panel_open: bool,
pub local_sort_index: usize,
@@ -316,6 +317,7 @@ impl Default for ContentListState {
pending_provider_icons: Arc::new(Mutex::new(Vec::new())),
project_metadata: HashMap::new(),
version_metadata: HashMap::new(),
unlinked_paths: HashSet::new(),
requested_provider_icons: HashSet::new(),
local_panel_open: false,
local_sort_index: 0,
@@ -405,6 +407,21 @@ impl ContentListState {
kind: crate::instance::ContentKind,
) {
let mut changed = false;
// Unmatched can also mean identification was skipped, so require
// at least one completed provider lookup before showing the notice.
let unlinked_paths = manifest
.files
.iter()
.filter(|record| {
record.kind == kind
&& matches!(&record.resolution, crate::instance::Resolution::Unmatched { providers, .. } if !providers.is_empty())
})
.map(|record| minecraft_dir.join(&record.relative_path))
.collect::<HashSet<_>>();
if self.unlinked_paths != unlinked_paths {
self.unlinked_paths = unlinked_paths;
changed = true;
}
let mut invalidated_icons = Vec::new();
for entry in &mut self.entries {
let Ok(relative_path) = entry.path.strip_prefix(minecraft_dir) else {
@@ -742,6 +759,7 @@ impl ContentListState {
self.pending_removals.clear();
self.requested_provider_icons.clear();
self.entries.clear();
self.unlinked_paths.clear();
self.invalidate_filtered();
self.sort_metadata.get_mut().clear();
self.display_metadata.clear();
@@ -1178,6 +1196,9 @@ impl ContentListState {
};
self.sort_metadata.get_mut().remove(&old_path);
self.sort_metadata.get_mut().remove(path);
if self.unlinked_paths.remove(&old_path) {
self.unlinked_paths.insert(path.clone());
}
update.toggles.push(ContentToggle {
old_path,
new_path: path.clone(),
@@ -1201,11 +1222,13 @@ impl ContentListState {
for mut entry in diff.added {
self.sort_metadata.get_mut().remove(&entry.path);
self.unlinked_paths.remove(&entry.path);
let replacement = self.entries.iter().position(|existing| {
self.pending_removals.contains_key(&existing.file_stem)
&& existing.name.eq_ignore_ascii_case(&entry.name)
});
if let Some(index) = replacement {
self.unlinked_paths.remove(&self.entries[index].path);
let old_stem = self.entries[index].file_stem.clone();
self.sort_metadata
.get_mut()
@@ -1278,6 +1301,7 @@ impl ContentListState {
let before = self.entries.len();
if let Some(entry) = self.entries.iter().find(|entry| entry.file_stem == stem) {
self.sort_metadata.get_mut().remove(&entry.path);
self.unlinked_paths.remove(&entry.path);
}
self.entries.retain(|entry| entry.file_stem != stem);
removed |= self.entries.len() != before;
@@ -1626,6 +1650,12 @@ impl ContentListState {
.is_some_and(|entry| entry.provider_project.is_some())
}
pub(crate) fn selected_is_unlinked(&self) -> bool {
self.selected_entry().is_some_and(|entry| {
entry.provider_project.is_none() && self.unlinked_paths.contains(&entry.path)
})
}
pub(crate) fn clamp_selected_index(&mut self) {
let count = self.filtered_indices().len();
self.list_state.selected =
@@ -1828,6 +1858,7 @@ impl ContentListState {
}
pub fn remove_path(&mut self, path: &Path) {
self.unlinked_paths.remove(path);
self.invalidate_filtered();
self.sort_metadata.get_mut().remove(path);
let file_stem = self
@@ -2093,6 +2124,7 @@ pub fn render(
let display_metadata = &state.display_metadata;
let version_metadata = &state.version_metadata;
let local_game_version = state.local_game_version.clone();
let unlinked_paths = &state.unlinked_paths;
let filtered_rows = &filtered;
let search = &state.search;
let warning_descriptions = state.warning_descriptions;
@@ -2109,7 +2141,11 @@ pub fn render(
let title_suffix = world_details
.and_then(|details| details.game_mode)
.map(WorldGameMode::label)
.or(entry.title_suffix.as_deref());
.or(entry.title_suffix.as_deref())
.or_else(|| {
(entry.provider_project.is_none() && unlinked_paths.contains(&entry.path))
.then_some("Unlinked")
});
let world_footer = world_details.map(|details| format_relative_time(details.last_played));
let footer_label = world_footer.as_deref().or(entry.footer_label.as_deref());
// Keep rendering the terminal fallback until the asynchronous image
@@ -2169,7 +2205,11 @@ pub fn render(
theme.success()
}
});
let title_suffix_style = crate::tui::widgets::status_badge_style(title_suffix_color);
let title_suffix_style = if title_suffix == Some("Unlinked") {
Style::default().fg(theme.text_dim()).bg(theme.surface())
} else {
crate::tui::widgets::status_badge_style(title_suffix_color)
};
let incompatible_version = !local_game_version.is_empty()
&& entry.provider_project.as_ref().is_some_and(|installed| {
!installed.version_id.is_empty()
+30 -3
View File
@@ -352,6 +352,16 @@ pub fn render(
}
_ => false,
};
let selected_unlinked = mode == ContentMode::Installed
&& match tab {
ContentTab::Mods => mods_state.selected_is_unlinked(),
ContentTab::ResourcePacks => resource_packs_state.selected_is_unlinked(),
ContentTab::Shaders => shaders_state.selected_is_unlinked(),
ContentTab::Worlds if open_world_datapacks.is_some() => {
world_datapacks_state.selected_is_unlinked()
}
_ => false,
};
let kb: Option<&[(&str, &str)]> = if is_focused {
Some(match (mode, tab) {
@@ -453,9 +463,7 @@ pub fn render(
if logs_state.viewer_focused {
&[
("j/k", " scroll"),
("PgUp/PgDn", " page"),
("f", " filter"),
("y", " copy"),
("g/G", " top/bottom"),
("d", " delete"),
("Esc", " back"),
@@ -495,6 +503,13 @@ pub fn render(
};
let mut keybinds = kb.map_or_else(Vec::new, <[_]>::to_vec);
if is_focused
&& mode == ContentMode::Installed
&& tab == ContentTab::Logs
&& logs_state.selection.range.is_some()
{
keybinds.insert(0, ("y", " yank"));
}
if is_focused
&& (mode == ContentMode::Installed || (!discovery_page_open && !discovery_unavailable))
&& (matches!(
@@ -536,8 +551,20 @@ pub fn render(
area.width.saturating_sub(2),
));
let content_area = block.inner(area);
let mut content_area = block.inner(area);
frame.render_widget(block, area);
if is_focused && selected_unlinked && content_area.height > 1 {
content_area.height -= 1;
frame.render_widget(
Paragraph::new(" No online source linked; version switching unavailable.")
.style(Style::default().fg(theme.text_dim())),
Rect {
y: content_area.bottom(),
height: 1,
..content_area
},
);
}
let downloadable_state = match tab {
ContentTab::Mods => Some((mods_state, mods_discovery_state)),
+158
View File
@@ -0,0 +1,158 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
use ratatui::{
layout::{Position, Rect},
style::{Modifier, Style},
text::{Line, Span},
};
use unicode_segmentation::UnicodeSegmentation;
use super::search::SearchState;
// Positions are (filtered line index, UTF-8 byte boundary). Mouse columns
// are converted using grapheme widths, including wide and combining glyphs.
#[derive(Debug, Default)]
pub(crate) struct LogSelection {
anchor: Option<(usize, usize)>,
pub range: Option<((usize, usize), (usize, usize))>,
}
impl LogSelection {
pub fn clear(&mut self) {
*self = Self::default();
}
pub fn finish(&mut self) {
self.anchor = None;
}
pub fn handle_mouse(
&mut self,
event: MouseEvent,
area: Rect,
scroll: usize,
lines: &[impl AsRef<str>],
) -> bool {
match event.kind {
MouseEventKind::Down(MouseButton::Left) => {
self.clear();
if area.is_empty()
|| !area.contains(Position::new(event.column, event.row))
|| lines.is_empty()
{
return false;
}
self.anchor = Some(mouse_position(event, area, scroll, lines));
true
}
MouseEventKind::Drag(MouseButton::Left) => {
let Some(anchor) = self.anchor else {
return false;
};
if lines.is_empty() {
self.clear();
return true;
}
let end = mouse_position(event, area, scroll, lines);
self.range = (anchor != end).then_some((anchor, end));
true
}
MouseEventKind::Up(MouseButton::Left) => self.anchor.take().is_some(),
_ => false,
}
}
pub fn text(&self, lines: &[impl AsRef<str>]) -> Option<String> {
let (start, end) = self.ordered()?;
let selected = lines.get(start.0..=end.0)?;
let mut text = Vec::with_capacity(selected.len());
for (offset, line) in selected.iter().enumerate() {
let line = line.as_ref();
let from = if offset == 0 { start.1 } else { 0 };
let to = if offset == selected.len() - 1 {
end.1
} else {
line.len()
};
text.push(line.get(from..to)?);
}
Some(text.join("\n"))
}
pub fn highlight_line(
&self,
index: usize,
text: &str,
search: &SearchState,
style: Style,
) -> Line<'static> {
let Some((start, end)) = self.ordered() else {
return search.highlight_line(text, style);
};
if index < start.0 || index > end.0 {
return search.highlight_line(text, style);
}
let from = if index == start.0 { start.1 } else { 0 };
let to = if index == end.0 { end.1 } else { text.len() };
if !text.is_char_boundary(from) || !text.is_char_boundary(to) {
return search.highlight_line(text, style);
}
let mut offset = 0;
let mut spans = Vec::new();
for span in search.highlight_spans(text, style) {
let len = span.content.len();
let left = from.saturating_sub(offset).min(len);
let right = to.saturating_sub(offset).min(len);
for (range, selected) in [(0..left, false), (left..right, true), (right..len, false)] {
if !range.is_empty() {
spans.push(Span::styled(
span.content[range].to_owned(),
if selected {
span.style.add_modifier(Modifier::REVERSED)
} else {
span.style
},
));
}
}
offset += len;
}
Line::from(spans)
}
fn ordered(&self) -> Option<((usize, usize), (usize, usize))> {
self.range.map(|(a, b)| (a.min(b), a.max(b)))
}
}
fn mouse_position(
event: MouseEvent,
area: Rect,
scroll: usize,
lines: &[impl AsRef<str>],
) -> (usize, usize) {
let row = event
.row
.saturating_sub(area.y)
.min(area.height.saturating_sub(1));
let index = scroll + usize::from(row);
if index >= lines.len() {
return (lines.len() - 1, lines.last().unwrap().as_ref().len());
}
let column = usize::from(event.column.saturating_sub(area.x).min(area.width));
let text = lines[index].as_ref();
let mut width = 0;
for (byte, grapheme) in text.grapheme_indices(true) {
width += Span::raw(grapheme).width();
if column < width {
return (index, byte);
}
}
(index, text.len())
}
#[cfg(test)]
#[path = "../tests/widgets/log_selection.rs"]
mod tests;
+159 -132
View File
@@ -14,10 +14,14 @@ use ratatui::{
};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use super::content::discovery::CategoryFilter;
use super::log_selection::LogSelection;
use crate::config::theme::{BORDER_STYLE, THEME};
use crate::instance::launch::parser::LogLevel;
use crate::instance::logs::files::{LogFileEntry, read_log_file, scan_log_files};
pub(crate) type LevelFilters = [Option<CategoryFilter>; 5];
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
pub struct LogsState {
@@ -29,12 +33,10 @@ pub struct LogsState {
pub viewer_lines: Vec<String>,
pub viewer_scroll: usize,
pub viewer_max_scroll: usize,
pub viewer_page: usize,
pub filter_open: bool,
pub filter_selected: usize,
pub hidden_levels: Vec<LogLevel>,
pub selection: Option<(usize, usize)>,
pub selecting: bool,
pub(crate) level_filters: LevelFilters,
pub(crate) selection: LogSelection,
pub viewer_area: Rect,
pub scrollbar_state: ScrollbarState,
pub viewer_scrollbar_state: ScrollbarState,
@@ -58,12 +60,10 @@ impl Default for LogsState {
viewer_lines: Vec::new(),
viewer_scroll: 0,
viewer_max_scroll: 0,
viewer_page: 0,
filter_open: false,
filter_selected: 0,
hidden_levels: Vec::new(),
selection: None,
selecting: false,
level_filters: [None; 5],
selection: LogSelection::default(),
viewer_area: Rect::default(),
scrollbar_state: ScrollbarState::default(),
viewer_scrollbar_state: ScrollbarState::default(),
@@ -87,6 +87,7 @@ impl LogsState {
self.entries.clear();
self.list_state = TuiListState::default();
self.viewer_lines.clear();
self.selection.clear();
self.viewer_scroll = 0;
self.viewer_focused = false;
self.selected_path = None;
@@ -240,6 +241,9 @@ impl LogsState {
fn load_selected_content(&mut self) {
if self.is_live_selected() {
if self.selected_path.is_some() {
self.selection.clear();
}
self.selected_path = None;
self.viewer_lines.clear();
self.viewer_scroll = 0;
@@ -255,6 +259,7 @@ impl LogsState {
return;
}
self.selected_path = path.clone();
self.selection.clear();
self.viewer_scroll = 0;
if let Some(path) = path {
@@ -309,6 +314,7 @@ impl LogsState {
self.selected_path = None;
self.viewer_lines.clear();
self.viewer_scroll = 0;
self.selection.clear();
} else if let Some(sel) = self.list_state.selected {
self.list_state.selected = Some(sel.min(display_count.saturating_sub(1)));
self.load_selected_content();
@@ -321,36 +327,24 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
let shift = key_event.modifiers.contains(KeyModifiers::SHIFT);
if state.filter_open {
match key_event.code {
KeyCode::Esc | KeyCode::Char('f') => {
state.filter_open = false;
}
KeyCode::Char('j') | KeyCode::Down => {
state.filter_selected =
(state.filter_selected + 1).min(LOG_LEVEL_FILTER_ORDER.len() - 1);
}
KeyCode::Char('k') | KeyCode::Up => {
state.filter_selected = state.filter_selected.saturating_sub(1);
}
KeyCode::Enter | KeyCode::Char(' ') => {
toggle_hidden_level(&mut state.hidden_levels, state.filter_selected);
state.selection = None;
state.viewer_scroll = 0;
}
KeyCode::Char('r') => {
state.hidden_levels.clear();
}
_ => {}
if handle_level_filter_key(
key_event,
&mut state.filter_open,
&mut state.filter_selected,
&mut state.level_filters,
) {
state.selection.clear();
state.viewer_scroll = 0;
}
return true;
}
if state.viewer_focused {
if state.viewer_search.active {
state.selection.clear();
match key_event.code {
KeyCode::Enter => {
state.viewer_search.confirm();
state.selection = None;
state.viewer_scroll = 0;
}
KeyCode::Esc => {
@@ -371,6 +365,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
}
if key_event.code == KeyCode::Char('/') {
state.selection.clear();
state.viewer_search.activate();
state.viewer_scroll = 0;
return true;
@@ -409,28 +404,13 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll);
true
}
KeyCode::PageDown => {
state.viewer_scroll =
(state.viewer_scroll + state.viewer_page.max(1)).min(state.viewer_max_scroll);
state.viewer_scrollbar_state =
ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll);
true
}
KeyCode::PageUp => {
state.viewer_scroll = state.viewer_scroll.saturating_sub(state.viewer_page.max(1));
state.viewer_scrollbar_state =
ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll);
true
}
KeyCode::Esc => {
if state.selection.take().is_some() {
return true;
}
state.selection.clear();
state.viewer_focused = false;
true
}
KeyCode::Char('y') => {
state.selecting = false;
state.selection.finish();
yank_viewer_selection(state);
true
}
@@ -442,10 +422,10 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
}
} else {
if state.search.active {
state.selection.clear();
match key_event.code {
KeyCode::Enter => {
state.search.confirm();
state.selection = None;
state.list_state.selected = Some(0);
state.load_selected_content();
state.update_scrollbar();
@@ -474,6 +454,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
}
if key_event.code == KeyCode::Char('/') {
state.selection.clear();
state.search.activate();
state.list_state.selected = Some(0);
state.update_scrollbar();
@@ -528,12 +509,12 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
state.viewer_focused = true;
true
}
KeyCode::Esc if state.selection.is_some() => {
state.selection = None;
KeyCode::Esc if state.selection.range.is_some() => {
state.selection.clear();
true
}
KeyCode::Char('y') => {
state.selecting = false;
state.selection.finish();
yank_viewer_selection(state);
true
}
@@ -545,20 +526,28 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: bool) {
let theme = THEME.as_ref();
if state.loading {
state.viewer_area = Rect::default();
frame.render_widget(
Paragraph::new("Loading logs...").style(Style::default().fg(theme.text_dim())),
area,
);
if state.filter_open {
render_level_filter(frame, area, state.filter_selected, &state.level_filters);
}
return;
}
let display_count = state.display_count();
if display_count == 0 {
state.viewer_area = Rect::default();
frame.render_widget(
Paragraph::new("No logs yet.").style(Style::default().fg(theme.text_dim())),
area,
);
if state.filter_open {
render_level_filter(frame, area, state.filter_selected, &state.level_filters);
}
return;
}
@@ -669,13 +658,12 @@ fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) {
let lines = filtered_viewer_lines(state);
let visible_height = area.height as usize;
state.viewer_page = visible_height;
// auto-scroll: if the user was already at the bottom, keep following
// new lines as they come in (like `tail -f` behavior)
let was_at_bottom = state.viewer_scroll >= state.viewer_max_scroll;
state.update_viewer_scrollbar(visible_height, lines.len());
if is_live && was_at_bottom && !state.viewer_search.active {
if is_live && was_at_bottom && !state.viewer_search.active && state.selection.range.is_none() {
state.viewer_scroll = state.viewer_max_scroll;
state.viewer_scrollbar_state =
ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll);
@@ -683,34 +671,32 @@ fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) {
if lines.is_empty() {
if state.filter_open {
render_level_filter(frame, area, state.filter_selected, &state.hidden_levels);
render_level_filter(frame, area, state.filter_selected, &state.level_filters);
}
return;
}
let search = &state.viewer_search;
let selected = state.selection.map(ordered_selection);
let styled_lines: Vec<Line> = lines
.iter()
.enumerate()
.skip(state.viewer_scroll)
.take(visible_height)
.map(|(index, line)| {
let mut style = line
let style = line
.level
.map(log_level_style)
.unwrap_or_else(|| line_level_style(&line.text));
if selected.is_some_and(|(from, to)| index >= from && index <= to) {
style = style.add_modifier(Modifier::REVERSED);
}
search.highlight_line(&line.text, style)
state
.selection
.highlight_line(index, &line.text, search, style)
})
.collect();
frame.render_widget(Paragraph::new(styled_lines), area);
if state.filter_open {
render_level_filter(frame, area, state.filter_selected, &state.hidden_levels);
render_level_filter(frame, area, state.filter_selected, &state.level_filters);
}
let scrollbar_area = Rect {
@@ -761,24 +747,41 @@ pub(crate) fn level_of_line(line: &str) -> Option<LogLevel> {
}
}
/// Whether a line is hidden by the level filter. Lines without a
/// recognizable level are always shown.
pub(crate) fn level_hidden(hidden: &[LogLevel], text: &str) -> bool {
level_of_line(text).is_some_and(|level| hidden.contains(&level))
pub(crate) fn level_matches(filters: &LevelFilters, level: Option<LogLevel>) -> bool {
let mode = LOG_LEVEL_FILTER_ORDER
.iter()
.position(|value| Some(*value) == level)
.and_then(|index| filters[index]);
mode != Some(CategoryFilter::Exclude)
&& (!filters.contains(&Some(CategoryFilter::Include))
|| mode == Some(CategoryFilter::Include))
}
pub(crate) fn toggle_hidden_level(hidden: &mut Vec<LogLevel>, selected: usize) {
if let Some(level) = LOG_LEVEL_FILTER_ORDER.get(selected) {
if hidden.contains(level) {
hidden.retain(|kept| kept != level);
} else {
hidden.push(*level);
pub(crate) fn handle_level_filter_key(
key: &KeyEvent,
open: &mut bool,
selected: &mut usize,
filters: &mut LevelFilters,
) -> bool {
match key.code {
KeyCode::Esc | KeyCode::Char('f') => *open = false,
KeyCode::Char('j') | KeyCode::Down => *selected = (*selected + 1).min(filters.len() - 1),
KeyCode::Char('k') | KeyCode::Up => *selected = selected.saturating_sub(1),
KeyCode::Enter | KeyCode::Char(' ') => {
filters[*selected] = match filters[*selected] {
None => Some(CategoryFilter::Include),
Some(CategoryFilter::Include) => Some(CategoryFilter::Exclude),
Some(CategoryFilter::Exclude) => None,
};
return true;
}
KeyCode::Char('r') => {
*filters = [None; 5];
return true;
}
_ => {}
}
}
fn ordered_selection(selection: (usize, usize)) -> (usize, usize) {
(selection.0.min(selection.1), selection.0.max(selection.1))
false
}
fn filtered_viewer_lines(state: &LogsState) -> Vec<ViewerLine> {
@@ -802,46 +805,47 @@ fn filtered_viewer_lines(state: &LogsState) -> Vec<ViewerLine> {
all_lines
.into_iter()
.filter(|line| state.viewer_search.matches(&line.text))
.filter(|line| match line.level {
Some(level) => !state.hidden_levels.contains(&level),
None => !level_hidden(&state.hidden_levels, &line.text),
.filter(|line| {
level_matches(
&state.level_filters,
line.level.or_else(|| level_of_line(&line.text)),
)
})
.collect()
}
pub(crate) fn filtered_viewer_line_count(state: &LogsState) -> usize {
filtered_viewer_lines(state).len()
pub(crate) fn handle_selection_mouse(
event: crossterm::event::MouseEvent,
state: &mut LogsState,
) -> bool {
let lines = filtered_viewer_lines(state);
let handled =
state
.selection
.handle_mouse(event, state.viewer_area, state.viewer_scroll, &lines);
if handled {
state.viewer_focused = true;
}
handled
}
pub(crate) fn yank_viewer_selection(state: &mut LogsState) {
let Some(selection) = state.selection.map(ordered_selection) else {
crate::feedback::errors::push_message(
tracing::Level::INFO,
"Drag across log lines to select them, then press y to copy",
);
let lines = filtered_viewer_lines(state);
yank_selection(&state.selection, &lines);
}
pub(crate) fn yank_selection(selection: &LogSelection, lines: &[impl AsRef<str>]) {
let Some(text) = selection.text(lines) else {
return;
};
let lines = filtered_viewer_lines(state);
if lines.is_empty() {
return;
}
let end = selection.1.min(lines.len() - 1);
if selection.0 > end {
return;
}
let text = lines[selection.0..=end]
.iter()
.map(|line| line.text.as_str())
.collect::<Vec<_>>()
.join("\n");
match copy_to_clipboard(&text) {
Some((count, false)) => crate::feedback::errors::push_message(
tracing::Level::INFO,
format!("Copied {count} line(s) to the clipboard"),
format!("Yanked {count} line(s) to the clipboard"),
),
Some((count, true)) => crate::feedback::errors::push_message(
tracing::Level::WARN,
format!("Copied the first {count} lines; the selection was truncated"),
format!("Yanked the first {count} lines; the selection was truncated"),
),
None => {}
}
@@ -852,19 +856,25 @@ pub(crate) fn yank_viewer_selection(state: &mut LogsState) {
pub(crate) fn copy_to_clipboard(text: &str) -> Option<(usize, bool)> {
use base64::Engine;
const MAX_LINES: usize = 2000;
let lines: Vec<&str> = text.lines().take(MAX_LINES + 1).collect();
let lines: Vec<&str> = text.split_inclusive('\n').take(MAX_LINES + 1).collect();
if lines.is_empty() {
return None;
}
let truncated = lines.len() > MAX_LINES;
let count = lines.len().min(MAX_LINES);
let encoded = base64::engine::general_purpose::STANDARD.encode(lines[..count].join("\n"));
let encoded = base64::engine::general_purpose::STANDARD.encode(lines[..count].concat());
let sequence = format!("\x1b]52;c;{encoded}\x07");
use std::io::Write;
std::io::stdout()
if let Err(error) = std::io::stdout()
.write_all(sequence.as_bytes())
.and_then(|_| std::io::stdout().flush())
.ok()?;
{
crate::feedback::errors::push_message(
tracing::Level::ERROR,
format!("Could not yank to the terminal clipboard: {error}"),
);
return None;
}
Some((count, truncated))
}
@@ -872,32 +882,54 @@ pub(crate) fn render_level_filter(
frame: &mut Frame,
area: Rect,
selected: usize,
hidden: &[LogLevel],
filters: &LevelFilters,
) {
use ratatui::layout::Constraint;
use ratatui::widgets::Widget;
let theme = THEME.as_ref();
let popup = area.centered(Constraint::Length(26), Constraint::Length(9));
let keybinds = super::popups::keybind_line(&[
("j/k", " navigate"),
("Enter", " toggle"),
("r", " reset"),
("Esc", " close"),
]);
let popup = area.centered(
Constraint::Length((keybinds.width() as u16 + 2).max(26)),
Constraint::Length(7),
);
let rows = LOG_LEVEL_FILTER_ORDER
.iter()
.enumerate()
.map(|(index, level)| {
let marker = if hidden.contains(level) { "[ ]" } else { "[x]" };
let prefix = if index == selected { "▶ " } else { " " };
let mode = filters[index];
let (marker, color) = match mode {
Some(CategoryFilter::Include) => ("+ ", theme.success()),
Some(CategoryFilter::Exclude) => ("− ", theme.error()),
None => ("· ", theme.text_dim()),
};
Line::from(vec![
Span::styled(
prefix,
Style::default().fg(if index == selected {
theme.accent()
} else {
theme.text()
}),
if index == selected { "▌ " } else { " " },
Style::default().fg(theme.accent()),
),
Span::styled(
format!("{marker} {}", level_label(*level)),
Style::default().fg(theme.text()),
marker,
Style::default().fg(color).add_modifier(Modifier::BOLD),
),
Span::styled(
level_label(*level),
Style::default().fg(if mode.is_some() {
theme.text()
} else {
theme.text_dim()
}),
),
])
.style(Style::default().bg(if index == selected {
theme.stripe()
} else {
theme.surface()
}))
})
.collect::<Vec<_>>();
let frame_widget = super::popups::base::PopupFrame {
@@ -908,11 +940,7 @@ pub(crate) fn render_level_filter(
),
border_color: theme.accent(),
bg: Some(theme.surface()),
keybinds: Some(super::popups::keybind_line(&[
("Enter", " toggle"),
("r", " reset"),
("Esc", " close"),
])),
keybinds: Some(keybinds),
search_line: None,
content: Box::new(move |area, buffer| {
Paragraph::new(rows.clone()).render(area, buffer);
@@ -926,28 +954,27 @@ struct ViewerLine {
level: Option<LogLevel>,
}
impl AsRef<str> for ViewerLine {
fn as_ref(&self) -> &str {
&self.text
}
}
fn log_level_style(level: LogLevel) -> Style {
let theme = THEME.as_ref();
match level {
LogLevel::Error => Style::default().fg(theme.error()),
LogLevel::Warn => Style::default().fg(theme.warning()),
LogLevel::Debug | LogLevel::Trace => Style::default().fg(theme.text_dim()),
LogLevel::Debug => Style::default().fg(theme.info()),
LogLevel::Trace => Style::default().fg(theme.text_dim()),
LogLevel::Info => Style::default().fg(theme.text()),
}
}
pub(crate) fn line_level_style(line: &str) -> Style {
let theme = THEME.as_ref();
let upper = line.to_uppercase();
if upper.contains("ERROR") || upper.contains("FATAL") || upper.contains("[STDERR]") {
Style::default().fg(theme.error())
} else if upper.contains("WARN") {
Style::default().fg(theme.warning())
} else if upper.contains("DEBUG") || upper.contains("TRACE") {
Style::default().fg(theme.text_dim())
} else {
Style::default().fg(theme.text())
}
level_of_line(line)
.map(log_level_style)
.unwrap_or_else(|| Style::default().fg(THEME.as_ref().text()))
}
#[cfg(test)]
+1
View File
@@ -12,6 +12,7 @@ use ratatui::{
pub mod account;
pub mod content;
pub mod instances;
pub(crate) mod log_selection;
pub mod logs_viewer;
pub mod markdown;
pub mod popups;