Skip to content

Commit

Permalink
refactor: add back widget titles
Browse files Browse the repository at this point in the history
Also has a few clippy fixes and bug fixes for redundant rerendering on
scroll on time graphs, being off by one cell during rendering for
no-battery situations on the battery widget, and having empty columns for
rtl column width calculations (as otherwise it goes to the wrong column).

We also now ensure that the CPU legend has enough room to draw!
  • Loading branch information
ClementTsang committed Sep 7, 2021
1 parent 18af6b0 commit 81fd703
Show file tree
Hide file tree
Showing 14 changed files with 133 additions and 155 deletions.
12 changes: 5 additions & 7 deletions src/app/layout_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1315,11 +1315,9 @@ pub fn create_layout_tree(
child_ids
.into_iter()
.filter_map(|child_id| {
if let Some(w) = widget_lookup_map.get(&child_id) {
Some((child_id, w.get_pretty_name().into()))
} else {
None
}
widget_lookup_map
.get(&child_id)
.map(|w| (child_id, w.get_pretty_name().into()))
})
.collect(),
)
Expand Down Expand Up @@ -1773,7 +1771,7 @@ pub fn generate_layout(

// Handle flexible children now.
let denominator: u32 = flexible_indices.iter().map(|(_, _, ratio)| ratio).sum();
let original_constraints = constraints.clone();
let original_constraints = constraints;
let mut split_constraints = flexible_indices
.iter()
.map(|(_, _, numerator)| {
Expand Down Expand Up @@ -1876,7 +1874,7 @@ pub fn generate_layout(
}

let denominator: u32 = flexible_indices.iter().map(|(_, _, ratio)| ratio).sum();
let original_constraints = constraints.clone();
let original_constraints = constraints;
let mut split_constraints = flexible_indices
.iter()
.map(|(_, _, numerator)| {
Expand Down
32 changes: 31 additions & 1 deletion src/app/widgets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ use std::time::Instant;
use crossterm::event::{KeyEvent, MouseEvent};
use enum_dispatch::enum_dispatch;
use indextree::NodeId;
use tui::{backend::Backend, layout::Rect, widgets::TableState, Frame};
use tui::{
backend::Backend,
layout::Rect,
text::Span,
widgets::{Block, Borders, TableState},
Frame,
};

use crate::{
app::{
Expand Down Expand Up @@ -115,6 +121,30 @@ pub trait Widget {
/// Returns a [`Widget`]'s "pretty" display name.
fn get_pretty_name(&self) -> &'static str;

/// Returns a new [`Block`]. The default implementation returns
/// a basic [`Block`] with different border colours based on selected state.
fn block<'a>(&self, painter: &'a Painter, is_selected: bool, borders: Borders) -> Block<'a> {
let has_top_bottom_border =
borders.contains(Borders::TOP) || borders.contains(Borders::BOTTOM);

let block = Block::default()
.border_style(if is_selected {
painter.colours.highlighted_border_style
} else {
painter.colours.border_style
})
.borders(borders);

if has_top_bottom_border {
block.title(Span::styled(
format!(" {} ", self.get_pretty_name()),
painter.colours.widget_title_style,
))
} else {
block
}
}

/// Draws a [`Widget`]. The default implementation draws nothing.
fn draw<B: Backend>(
&mut self, painter: &Painter, f: &mut Frame<'_, B>, area: Rect, selected: bool,
Expand Down
2 changes: 2 additions & 0 deletions src/app/widgets/base/text_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ where
left_to_right: bool, mut desired_widths: Vec<DesiredColumnWidth>, total_width: u16,
) -> Vec<u16> {
let mut total_width_left = total_width;
let num_widths = desired_widths.len();
if !left_to_right {
desired_widths.reverse();
}
Expand Down Expand Up @@ -302,6 +303,7 @@ where
}

if !left_to_right {
column_widths.extend(vec![0; num_widths.saturating_sub(column_widths.len())]);
column_widths.reverse();
}
}
Expand Down
8 changes: 6 additions & 2 deletions src/app/widgets/base/time_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,9 @@ impl TimeGraph {
fn zoom_in(&mut self) -> WidgetEventResult {
let new_time = self.current_display_time.saturating_sub(self.time_interval);

if new_time >= self.min_duration {
if self.current_display_time == new_time {
WidgetEventResult::NoRedraw
} else if new_time >= self.min_duration {
self.current_display_time = new_time;
self.autohide_timer.start_display_timer();

Expand All @@ -187,7 +189,9 @@ impl TimeGraph {
fn zoom_out(&mut self) -> WidgetEventResult {
let new_time = self.current_display_time + self.time_interval;

if new_time <= self.max_duration {
if self.current_display_time == new_time {
WidgetEventResult::NoRedraw
} else if new_time <= self.max_duration {
self.current_display_time = new_time;
self.autohide_timer.start_display_timer();

Expand Down
3 changes: 1 addition & 2 deletions src/app/widgets/bottom_widgets/basic_cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,13 +175,12 @@ impl Widget for BasicCpu {
"{:3}",
data.cpu_count
.map(|c| c.to_string())
.unwrap_or(data.cpu_prefix.clone())
.unwrap_or_else(|| data.cpu_prefix.clone())
),
format!("{:3.0}%", data.cpu_usage.round()),
)
})
.collect::<Vec<_>>();

}

fn width(&self) -> LayoutRule {
Expand Down
56 changes: 26 additions & 30 deletions src/app/widgets/bottom_widgets/battery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use tui::{
backend::Backend,
layout::{Constraint, Direction, Layout, Rect},
text::{Span, Spans},
widgets::{Block, Borders, Paragraph, Tabs},
widgets::{Borders, Paragraph, Tabs},
Frame,
};

Expand Down Expand Up @@ -144,11 +144,11 @@ impl Component for BatteryTable {

fn handle_mouse_event(&mut self, event: MouseEvent) -> WidgetEventResult {
for (itx, bound) in self.tab_bounds.iter().enumerate() {
if does_bound_intersect_coordinate(event.column, event.row, *bound) {
if itx < self.battery_data.len() {
self.selected_index = itx;
return WidgetEventResult::Redraw;
}
if does_bound_intersect_coordinate(event.column, event.row, *bound)
&& itx < self.battery_data.len()
{
self.selected_index = itx;
return WidgetEventResult::Redraw;
}
}
WidgetEventResult::NoRedraw
Expand Down Expand Up @@ -178,43 +178,39 @@ impl Widget for BatteryTable {
fn draw<B: Backend>(
&mut self, painter: &Painter, f: &mut Frame<'_, B>, area: Rect, selected: bool,
) {
let block = Block::default()
.border_style(if selected {
painter.colours.highlighted_border_style
} else {
painter.colours.border_style
})
.borders(self.block_border.clone());
let block = self.block(painter, selected, self.block_border);

let inner_area = block.inner(area);
const CONSTRAINTS: [Constraint; 2] = [Constraint::Length(1), Constraint::Min(0)];
let split_area = Layout::default()
.direction(Direction::Vertical)
.constraints(CONSTRAINTS)
.split(inner_area);
let tab_area = Rect::new(
split_area[0].x.saturating_sub(1),
split_area[0].y,
split_area[0].width,
split_area[0].height,
);
let data_area = if inner_area.height >= TABLE_GAP_HEIGHT_LIMIT && split_area[1].height > 0 {
Rect::new(
split_area[1].x,
split_area[1].y + 1,
split_area[1].width,
split_area[1].height - 1,
)
} else {
split_area[1]
};

if self.battery_data.is_empty() {
f.render_widget(
Paragraph::new("No batteries found").style(painter.colours.text_style),
tab_area,
split_area[0],
);
} else {
let tab_area = Rect::new(
split_area[0].x.saturating_sub(1),
split_area[0].y,
split_area[0].width,
split_area[0].height,
);
let data_area =
if inner_area.height >= TABLE_GAP_HEIGHT_LIMIT && split_area[1].height > 0 {
Rect::new(
split_area[1].x,
split_area[1].y + 1,
split_area[1].width,
split_area[1].height - 1,
)
} else {
split_area[1]
};

let battery_tab_names = self
.battery_data
.iter()
Expand Down
2 changes: 1 addition & 1 deletion src/app/widgets/bottom_widgets/carousel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ impl Carousel {

/// Returns the currently selected [`NodeId`] if possible.
pub fn get_currently_selected(&self) -> Option<NodeId> {
self.children.get(self.index).map(|i| i.0.clone())
self.children.get(self.index).map(|i| i.0)
}

fn get_next(&self) -> Option<&(NodeId, Cow<'static, str>)> {
Expand Down
93 changes: 46 additions & 47 deletions src/app/widgets/bottom_widgets/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ impl CpuGraph {
let graph = TimeGraph::from_config(app_config_fields);
let legend = TextTable::new(vec![
SimpleColumn::new_flex("CPU".into(), 0.5),
SimpleColumn::new_hard("Use%".into(), None),
SimpleColumn::new_hard("Use".into(), None),
])
.default_ltr(false);
let legend_position = if app_config_fields.left_legend {
Expand Down Expand Up @@ -165,12 +165,17 @@ impl Widget for CpuGraph {
fn draw<B: Backend>(
&mut self, painter: &Painter, f: &mut Frame<'_, B>, area: Rect, selected: bool,
) {
let constraints = match self.legend_position {
CpuGraphLegendPosition::Left => {
[Constraint::Percentage(15), Constraint::Percentage(85)]
}
CpuGraphLegendPosition::Right => {
[Constraint::Percentage(85), Constraint::Percentage(15)]
let constraints = {
const CPU_LEGEND_MIN_WIDTH: u16 = 10;
let (legend_constraint, cpu_constraint) =
if area.width * 15 / 100 < CPU_LEGEND_MIN_WIDTH {
(Constraint::Length(CPU_LEGEND_MIN_WIDTH), Constraint::Min(0))
} else {
(Constraint::Percentage(15), Constraint::Percentage(85))
};
match self.legend_position {
CpuGraphLegendPosition::Left => [legend_constraint, cpu_constraint],
CpuGraphLegendPosition::Right => [cpu_constraint, legend_constraint],
}
};

Expand All @@ -180,6 +185,11 @@ impl Widget for CpuGraph {
.constraints(constraints)
.split(area);

let (graph_block_area, legend_block_area) = match self.legend_position {
CpuGraphLegendPosition::Left => (split_area[1], split_area[0]),
CpuGraphLegendPosition::Right => (split_area[0], split_area[1]),
};

const Y_BOUNDS: [f64; 2] = [0.0, 100.5];
let y_bound_labels: [Cow<'static, str>; 2] = ["0%".into(), "100%".into()];

Expand Down Expand Up @@ -217,6 +227,35 @@ impl Widget for CpuGraph {
})
.collect::<Vec<_>>();

let graph_block = self.block(
painter,
selected && matches!(&self.selected, CpuGraphSelection::Graph),
Borders::ALL,
);

self.graph.draw_tui_chart(
painter,
f,
&cpu_data,
&y_bound_labels,
Y_BOUNDS,
true,
graph_block,
graph_block_area,
);

let legend_block = Block::default()
.border_style(if selected {
if let CpuGraphSelection::Legend = &self.selected {
painter.colours.highlighted_border_style
} else {
painter.colours.border_style
}
} else {
painter.colours.border_style
})
.borders(Borders::ALL);

let legend_data = self
.display_data
.iter()
Expand Down Expand Up @@ -249,46 +288,6 @@ impl Widget for CpuGraph {
})
.collect::<Vec<_>>();

let graph_block = Block::default()
.border_style(if selected {
if let CpuGraphSelection::Graph = &self.selected {
painter.colours.highlighted_border_style
} else {
painter.colours.border_style
}
} else {
painter.colours.border_style
})
.borders(Borders::ALL);

let legend_block = Block::default()
.border_style(if selected {
if let CpuGraphSelection::Legend = &self.selected {
painter.colours.highlighted_border_style
} else {
painter.colours.border_style
}
} else {
painter.colours.border_style
})
.borders(Borders::ALL);

let (graph_block_area, legend_block_area) = match self.legend_position {
CpuGraphLegendPosition::Left => (split_area[1], split_area[0]),
CpuGraphLegendPosition::Right => (split_area[0], split_area[1]),
};

self.graph.draw_tui_chart(
painter,
f,
&cpu_data,
&y_bound_labels,
Y_BOUNDS,
true,
graph_block,
graph_block_area,
);

self.legend.draw_tui_table(
painter,
f,
Expand Down
15 changes: 2 additions & 13 deletions src/app/widgets/bottom_widgets/disk.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
use std::collections::HashMap;

use crossterm::event::{KeyEvent, MouseEvent};
use tui::{
backend::Backend,
layout::Rect,
widgets::{Block, Borders},
Frame,
};
use tui::{backend::Backend, layout::Rect, widgets::Borders, Frame};

use crate::{
app::{
Expand Down Expand Up @@ -127,13 +122,7 @@ impl Widget for DiskTable {
fn draw<B: Backend>(
&mut self, painter: &Painter, f: &mut Frame<'_, B>, area: Rect, selected: bool,
) {
let block = Block::default()
.border_style(if selected {
painter.colours.highlighted_border_style
} else {
painter.colours.border_style
})
.borders(self.block_border.clone());
let block = self.block(painter, selected, self.block_border);

self.table
.draw_tui_table(painter, f, &self.display_data, block, area, selected);
Expand Down
Loading

0 comments on commit 81fd703

Please sign in to comment.