From 9205e1594b960dbdd3ad4189c996aa1be09e76a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=8C=E6=89=8B=E6=8E=89=E5=8C=85=E5=B7=A5=E7=A8=8B?= =?UTF-8?q?=E5=B8=88?= Date: Wed, 24 Jul 2024 15:52:42 +0800 Subject: [PATCH] fix(console): avoid crash when accessing selected item (#570) We should check the length before using the index to access it. Closes #565 Test locally: https://github.com/tokio-rs/console/assets/29879298/5c4fd5da-e1c7-490b-bd67-1257972076d3 But it is difficult to view it, you can try it by following the steps from the issue. --- tokio-console/src/view/mod.rs | 6 +++--- tokio-console/src/view/table.rs | 22 +++++++++++++--------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/tokio-console/src/view/mod.rs b/tokio-console/src/view/mod.rs index 6dda97c96..e8fff249e 100644 --- a/tokio-console/src/view/mod.rs +++ b/tokio-console/src/view/mod.rs @@ -132,7 +132,7 @@ impl View { // mutate the currently selected view. match event { key!(Enter) => { - if let Some(task) = self.tasks_list.selected_item().upgrade() { + if let Some(task) = self.tasks_list.selected_item() { update_kind = UpdateKind::SelectTask(task.borrow().span_id()); self.state = TaskInstance(self::task::TaskView::new( task, @@ -149,7 +149,7 @@ impl View { ResourcesList => { match event { key!(Enter) => { - if let Some(res) = self.resources_list.selected_item().upgrade() { + if let Some(res) = self.resources_list.selected_item() { update_kind = UpdateKind::SelectResource(res.borrow().span_id()); self.state = ResourceInstance(self::resource::ResourceView::new(res)); } @@ -169,7 +169,7 @@ impl View { update_kind = UpdateKind::Other; } key!(Enter) => { - if let Some(op) = view.async_ops_table.selected_item().upgrade() { + if let Some(op) = view.async_ops_table.selected_item() { if let Some(task_id) = op.borrow().task_id() { let task = self .tasks_list diff --git a/tokio-console/src/view/table.rs b/tokio-console/src/view/table.rs index 40ffc8757..c3d03959b 100644 --- a/tokio-console/src/view/table.rs +++ b/tokio-console/src/view/table.rs @@ -13,7 +13,7 @@ use ratatui::{ use std::convert::TryFrom; use std::cell::RefCell; -use std::rc::Weak; +use std::rc::{Rc, Weak}; pub(crate) trait TableList { type Row; @@ -154,18 +154,22 @@ impl, const N: usize> TableListState { self.scroll_with(|_, _| 0) } - pub(in crate::view) fn selected_item(&self) -> Weak> { + pub(in crate::view) fn selected_item(&self) -> Option>> { self.table_state .selected() - .map(|i| { - let selected = if self.sort_descending { - i + .and_then(|i| { + if self.sort_descending { + if i < self.sorted_items.len() { + Some(self.sorted_items[i].clone()) + } else { + None + } } else { - self.sorted_items.len() - i - 1 - }; - self.sorted_items[selected].clone() + let adjusted_index = self.sorted_items.len().checked_sub(i + 1)?; + self.sorted_items.get(adjusted_index).cloned() + } }) - .unwrap_or_default() + .and_then(|weak| weak.upgrade()) } pub(in crate::view) fn render(