Skip to content

Commit a8bc7a4

Browse files
committed
[AI generated] fix: Clamp GPU graph widths to prevent crash on small terminals
When many GPUs are present and the terminal is small, the GPU graph width calculations in Cpu::draw init_graphs and draw_graphs can produce negative values. This causes std::out_of_range from the Draw::Graph constructor, surfacing as "Exception in runner thread -> Cpu:: -> deque". The root cause is the remainder-distribution formula for the last GPU graph: graph_width + graph_default_width%graph_width - gpus.size() + 1 which underflows when gpus.size() exceeds the available remainder plus graph_width. The per-GPU graph_width itself can also go below 1 when graph_default_width is small relative to gpu_draw_count. Clamp both graph_width and the last-GPU width to a minimum of 1, and clamp the cursor movement arguments in draw_graphs to prevent negative Mv::l and Mv::r values.
1 parent 6462ebc commit a8bc7a4

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/btop_draw.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,7 @@ namespace Cpu {
624624
gpu_mem_graphs.resize(gpus.size());
625625
gpu_meters.resize(gpus.size());
626626
const int gpu_draw_count = gpu_always ? Gpu::count : Gpu::count - Gpu::shown;
627-
graph_width = gpu_draw_count <= 0 ? graph_default_width : graph_default_width/gpu_draw_count - gpu_draw_count + 1 + graph_default_width%gpu_draw_count;
627+
graph_width = gpu_draw_count <= 0 ? graph_default_width : max(1, graph_default_width/gpu_draw_count - gpu_draw_count + 1 + graph_default_width%gpu_draw_count);
628628
for (size_t i = 0; i < gpus.size(); i++) {
629629
if (gpu_auto and v_contains(Gpu::shown_panels, i))
630630
continue;
@@ -637,7 +637,7 @@ namespace Cpu {
637637
}
638638
else {
639639
graph = Draw::Graph{
640-
graph_width + graph_default_width%graph_width - (int)gpus.size() + 1,
640+
max(1, graph_width + graph_default_width%graph_width - (int)gpus.size() + 1),
641641
graph_height, "cpu", safeVal(gpu.gpu_percent, graph_field), graph_symbol, invert, true
642642
};
643643
}
@@ -792,8 +792,8 @@ namespace Cpu {
792792
}
793793
if (Gpu::count - (gpu_auto ? Gpu::shown : 0) > 1) {
794794
auto i_str = to_string(i);
795-
out += Mv::l(graph_width-1) + Mv::u(graph_height/2) + (graph_width > 5 ? "GPU" : "") + i_str
796-
+ Mv::d(graph_height/2) + Mv::r(graph_width - 1 - (graph_width > 5)*3 - i_str.size());
795+
out += Mv::l(max(0, graph_width-1)) + Mv::u(graph_height/2) + (graph_width > 5 ? "GPU" : "") + i_str
796+
+ Mv::d(graph_height/2) + Mv::r(max(0, (int)(graph_width - 1 - (graph_width > 5)*3 - i_str.size())));
797797
}
798798

799799
if (++gpu_drawn < Gpu::count - (gpu_auto ? Gpu::shown : 0))

0 commit comments

Comments
 (0)