1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This software may be used and distributed according to the terms of the
// GNU General Public License version 2.
use crate::columns::{
get_memory_detail_columns, get_memory_detail_metrics, get_memory_rates_columns,
get_memory_summary_columns, get_pagefault_summary_columns, get_slab_columns,
get_swap_summary_columns, Column,
};
use crate::util::format_bytes;
use crate::{Action, AppState, AppTheme, KeyMap, MemStatSnapshot};
use anyhow::Result;
use ratatui::layout::{Alignment, Constraint, Layout};
use ratatui::symbols::line::THICK;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Cell, LineGauge, Row, Table};
use ratatui::{layout::Rect, Frame};
/// Renderer for memory views
pub struct MemoryRenderer;
impl MemoryRenderer {
/// Renders the full memory view (AppState::Memory)
pub fn render_memory_view(
frame: &mut Frame,
mem_info: &MemStatSnapshot,
_sample_rate: u32,
tick_rate_ms: usize,
theme: &AppTheme,
) -> Result<()> {
let area = frame.area();
let [left, right] = Layout::horizontal([Constraint::Fill(1); 2]).areas(area);
// Get the columns and metrics for the detailed memory view
let memory_columns = get_memory_detail_columns();
let memory_metrics = get_memory_detail_metrics();
// Create header cells from column headers
let header_cells: Vec<Cell> = memory_columns
.iter()
.map(|col| Cell::from(col.header).style(theme.title_style()))
.collect();
// Create constraints from column constraints
let constraints: Vec<Constraint> =
memory_columns.iter().map(|col| col.constraint).collect();
// Create rows for memory metrics
let rows = memory_metrics
.iter()
.map(|metric| {
let cells = memory_columns
.iter()
.map(|col| {
Cell::from((col.value_fn)(metric, mem_info))
.style(theme.text_important_color())
})
.collect::<Vec<Cell>>();
Row::new(cells)
})
.collect::<Vec<Row>>();
let block = Block::bordered()
.title_top(
Line::from("Memory Statistics")
.style(theme.title_style())
.centered(),
)
.title_top(
Line::from(format!("{}ms", tick_rate_ms))
.style(theme.text_important_color())
.right_aligned(),
)
.border_type(BorderType::Rounded)
.style(theme.border_style());
let table = Table::new(rows, constraints)
.header(Row::new(header_cells).style(theme.title_style()))
.block(block);
frame.render_widget(table, left);
// Create memory usage gauges and additional stats for the right side
let [right_top, right_middle, right_bottom] = Layout::vertical([
Constraint::Min(3),
Constraint::Percentage(50),
Constraint::Percentage(50),
])
.areas(right);
// Split the top section into two columns for memory and swap gauges
let [gauge_left, gauge_right] =
Layout::horizontal([Constraint::Fill(1); 2]).areas(right_top);
// Memory usage gauge
let mem_used_percent =
100.0 - (mem_info.available_kb as f64 / mem_info.total_kb as f64) * 100.0;
let mem_used_kb = mem_info.total_kb - mem_info.available_kb;
// Calculate gradient color based on memory usage percentage
let mem_gradient_color = theme.gradient_5(
mem_used_percent,
20.0, // very low threshold (0-20%)
40.0, // low threshold (20-40%)
60.0, // high threshold (40-60%)
80.0, // very high threshold (60-80%)
false,
);
let mem_gauge = LineGauge::default()
.block(
Block::bordered()
.title_top(
Line::from("Memory Usage")
.style(theme.title_style())
.centered(),
)
.border_type(BorderType::Rounded)
.style(theme.border_style()),
)
.line_set(THICK)
.filled_style(mem_gradient_color)
.ratio(mem_used_percent / 100.0)
.label(format!(
"{}/{}",
format_bytes(mem_used_kb),
format_bytes(mem_info.total_kb),
));
frame.render_widget(mem_gauge, gauge_left);
// Swap usage gauge
let swap_used_percent = if mem_info.swap_total_kb > 0 {
100.0 - (mem_info.swap_free_kb as f64 / mem_info.swap_total_kb as f64) * 100.0
} else {
0.0
};
let swap_used_kb = mem_info.swap_total_kb - mem_info.swap_free_kb;
// Calculate gradient color based on swap usage percentage
let swap_gradient_color = theme.gradient_5(
swap_used_percent,
5.0, // very low threshold (0-5%) - any swap usage is concerning
15.0, // low threshold (5-15%)
35.0, // high threshold (15-35%)
60.0, // very high threshold (35-60%)
false,
);
let swap_gauge = LineGauge::default()
.block(
Block::bordered()
.title_top(
Line::from("Swap Usage")
.style(theme.title_style())
.centered(),
)
.border_type(BorderType::Rounded)
.style(theme.border_style()),
)
.line_set(THICK)
.filled_style(swap_gradient_color)
.ratio(swap_used_percent / 100.0)
.label(format!(
"{}/{}",
format_bytes(swap_used_kb),
format_bytes(mem_info.swap_total_kb),
));
frame.render_widget(swap_gauge, gauge_right);
// Memory rates (pagefaults, swap I/O)
let memory_rates_columns = get_memory_rates_columns();
Self::render_memory_table(
frame,
right_middle,
Some("Memory Activity Rates"),
&memory_rates_columns,
mem_info,
true,
theme,
)?;
// Slab information section
let slab_columns = get_slab_columns();
Self::render_memory_table(
frame,
right_bottom,
Some("Slab Information"),
&slab_columns,
mem_info,
true,
theme,
)?;
Ok(())
}
/// Renders memory summary for default view
pub fn render_memory_summary(
frame: &mut Frame,
area: Rect,
mem_info: &MemStatSnapshot,
keymap: &KeyMap,
theme: &AppTheme,
) -> Result<()> {
let memory_key = keymap.action_keys_string(Action::SetState(AppState::Memory));
// Check if the memory key is bound
if memory_key.is_empty() {
panic!("Memory key is not bound");
}
// Create a single block for all memory tables with keybinding in title
let title = if memory_key == "m" || memory_key == "M" {
Line::from(vec![
Span::styled(
&memory_key,
theme
.title_style()
.add_modifier(ratatui::style::Modifier::BOLD),
),
Span::styled("emory Statistics", theme.text_color()),
])
} else {
Line::from(vec![
Span::styled("Memory Statistics (", theme.text_color()),
Span::styled(&memory_key, theme.title_style()),
Span::styled(")", theme.text_color()),
])
};
let block = Block::bordered()
.title(title)
.title_alignment(Alignment::Center)
.border_type(BorderType::Rounded)
.style(theme.border_style());
// Get the inner area of the block
let inner_area = block.inner(area);
// Split the inner area into three sections for different memory tables
// Use proportional heights based on content - memory needs more space than swap and page faults
let [memory_area, swap_area, pagefault_area] = Layout::vertical([
Constraint::Length(3), // Memory table (header + 1 row + padding)
Constraint::Length(3), // Swap table (header + 1 row + padding)
Constraint::Length(3), // Page faults table (header + 1 row + padding)
])
.margin(0) // Remove margin between tables
.areas(inner_area);
// Get the columns for memory, swap, and pagefault stats
let memory_columns = get_memory_summary_columns();
let swap_columns = get_swap_summary_columns();
let pagefault_columns = get_pagefault_summary_columns();
// Render the block first
frame.render_widget(block, area);
// Render memory statistics table (without border)
Self::render_memory_table(
frame,
memory_area,
None,
&memory_columns,
mem_info,
false,
theme,
)?;
// Render swap statistics table (without border)
Self::render_memory_table(
frame,
swap_area,
None,
&swap_columns,
mem_info,
false,
theme,
)?;
// Render page fault statistics table (without border)
Self::render_memory_table(
frame,
pagefault_area,
None,
&pagefault_columns,
mem_info,
false,
theme,
)?;
Ok(())
}
/// Renders a memory table with the given columns
fn render_memory_table(
frame: &mut Frame,
area: Rect,
title: Option<&str>,
columns: &[Column<(), MemStatSnapshot>],
mem_stats: &MemStatSnapshot,
with_border: bool,
theme: &AppTheme,
) -> Result<()> {
// Create header cells from column headers
let header_cells: Vec<Cell> = columns
.iter()
.filter(|col| col.visible)
.map(|col| Cell::from(col.header).style(theme.title_style()))
.collect();
// Create row data
let row_cells: Vec<Cell> = columns
.iter()
.filter(|col| col.visible)
.map(|col| {
let value = (col.value_fn)((), mem_stats);
Cell::from(value).style(theme.text_color())
})
.collect();
// Get constraints for visible columns
let constraints: Vec<Constraint> = columns
.iter()
.filter(|col| col.visible)
.map(|col| col.constraint)
.collect();
// Create the table with rows and constraints
let mut table = Table::new(vec![Row::new(row_cells)], constraints)
.header(Row::new(header_cells))
.column_spacing(1);
// Add border and title if requested
if with_border {
if let Some(table_title) = title {
table = table.block(
Block::bordered()
.title(table_title)
.title_alignment(Alignment::Center)
.border_type(BorderType::Rounded)
.style(theme.border_style()),
);
} else {
table = table.block(
Block::bordered()
.border_type(BorderType::Rounded)
.style(theme.border_style()),
);
}
}
frame.render_widget(table, area);
Ok(())
}
}