1use crate::canvas::{Canvas, Marker};
4use crate::text::put_str;
5use crate::theme::{self, Theme};
6use crate::util::{format_tick, nice_bounds, nice_ticks};
7use crate::PALETTE;
8use ratatui::{
9 buffer::Buffer,
10 layout::Rect,
11 style::{Color, Style},
12 widgets::Block,
13};
14
15#[derive(Debug, Clone, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct BubbleSeries {
19 pub name: String,
21 pub points: Vec<(f64, f64, f64)>,
23 pub color: Option<Color>,
25}
26
27impl BubbleSeries {
28 pub fn new(name: impl Into<String>, points: impl IntoIterator<Item = (f64, f64, f64)>) -> Self {
30 Self {
31 name: name.into(),
32 points: points.into_iter().collect(),
33 color: None,
34 }
35 }
36
37 pub fn color(mut self, c: Color) -> Self {
39 self.color = Some(c);
40 self
41 }
42}
43
44#[derive(Debug, Clone, Default)]
46pub struct BubbleChart {
47 series: Vec<BubbleSeries>,
48 max_radius: Option<u16>,
49 marker: Marker,
50 theme: Option<Theme>,
51 base: Option<Style>,
52 block: Option<Block<'static>>,
53}
54
55impl BubbleChart {
56 pub fn new(series: impl IntoIterator<Item = BubbleSeries>) -> Self {
58 Self {
59 series: series.into_iter().collect(),
60 ..Self::default()
61 }
62 }
63
64 opt_setter!(
65 max_radius: u16
67 );
68
69 setter!(
70 marker: Marker
72 );
73
74 theme_setter!(
75 theme
77 );
78
79 base_style_setter!(base);
80
81 block_setter!(block, 'static);
82
83 fn render_into(&self, area: Rect, buf: &mut Buffer) {
84 let area = area.intersection(buf.area);
85 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
86 if inner.width < 8 || inner.height < 4 {
87 return;
88 }
89 let pts = || {
90 self.series.iter().flat_map(|s| {
91 s.points
92 .iter()
93 .filter(|(x, y, z)| x.is_finite() && y.is_finite() && z.is_finite())
94 })
95 };
96 if pts().next().is_none() {
97 return;
98 }
99 let (mut x0, mut x1) = (f64::MAX, f64::MIN);
100 let (mut y0, mut y1) = (f64::MAX, f64::MIN);
101 let mut zmax = 0f64;
102 for &(x, y, z) in pts() {
103 x0 = x0.min(x);
104 x1 = x1.max(x);
105 y0 = y0.min(y);
106 y1 = y1.max(y);
107 zmax = zmax.max(z.abs());
108 }
109 let (x0, x1) = nice_bounds(x0, x1, 5);
110 let (y0, y1) = nice_bounds(y0, y1, 5);
111 let (xs, ys) = ((x1 - x0).max(f64::EPSILON), (y1 - y0).max(f64::EPSILON));
112 let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
113 let text = self
114 .theme
115 .as_ref()
116 .map_or(Style::default(), |t| t.label_style());
117
118 let yt = nice_ticks(y0, y1, (inner.height as usize / 3).max(2));
119 let ystep = if yt.len() >= 2 { yt[1] - yt[0] } else { 1.0 };
120 let ylabels: Vec<String> = yt.iter().map(|v| format_tick(*v, ystep)).collect();
121 let gutter = (ylabels.iter().map(|l| l.chars().count()).max().unwrap_or(1) as u16 + 1)
122 .min(inner.width / 2);
123 let plot = Rect::new(
124 inner.x + gutter,
125 inner.y,
126 inner.width - gutter,
127 inner.height - 1,
128 );
129 if plot.width < 2 || plot.height < 2 {
130 return;
131 }
132 let mut cv = Canvas::new(plot.width, plot.height, self.marker);
133 let (pw, ph) = (cv.px_w(), cv.px_h());
134 let rmax = self
135 .max_radius
136 .map_or(((ph.min(pw / 2)) / 5).max(2), |r| r as i32);
137 let (ix, iy) = (rmax.min(pw / 3), rmax.min(ph / 3));
139 let (aw, ah) = (
140 (pw - 1 - 2 * ix).max(1) as f64,
141 (ph - 1 - 2 * iy).max(1) as f64,
142 );
143 for (si, s) in self.series.iter().enumerate() {
144 let color = s.color.unwrap_or_else(|| {
145 self.theme
146 .as_ref()
147 .map_or(PALETTE[si % PALETTE.len()], |t| t.color(si))
148 });
149 for &(x, y, z) in &s.points {
150 if !(x.is_finite() && y.is_finite() && z.is_finite()) {
151 continue;
152 }
153 let cx = ix + ((x - x0) / xs * aw).round() as i32;
154 let cy = iy + ((1.0 - (y - y0) / ys) * ah).round() as i32;
155 let r = if zmax > 0.0 {
156 ((z.abs() / zmax).sqrt() * rmax as f64).round() as i32
157 } else {
158 0
159 }
160 .max(1);
161 for dy in -r..=r {
162 for dx in -r..=r {
163 let (rx, ry) = self.marker.resolution();
165 let ax = dx * ry as i32 / rx as i32;
166 if ax * ax + dy * dy <= r * r {
167 cv.set(cx + dx, cy + dy, color);
168 }
169 }
170 }
171 }
172 }
173 for (v, l) in yt.iter().zip(&ylabels) {
174 let f = ((v - y0) / ys).clamp(0.0, 1.0);
175 let y = plot.bottom() - 1 - (f * (plot.height - 1) as f64).round() as u16;
176 let w = l.chars().count() as u16;
177 put_str(
178 buf,
179 inner.x + gutter.saturating_sub(w + 1),
180 y,
181 plot.x,
182 l,
183 dim,
184 );
185 for x in plot.x..plot.right() {
186 if buf[(x, y)].symbol() == " " {
187 buf[(x, y)].set_char('┈').set_style(dim);
188 }
189 }
190 }
191 cv.render(buf, plot);
192 let xt = nice_ticks(x0, x1, (plot.width as usize / 10).max(2));
193 let xstep = if xt.len() >= 2 { xt[1] - xt[0] } else { 1.0 };
194 for v in xt {
195 let f = ((v - x0) / xs).clamp(0.0, 1.0);
196 let x = plot.x + (f * (plot.width - 1) as f64).round() as u16;
197 let l = format_tick(v, xstep);
198 let lx = x.saturating_sub(l.chars().count() as u16 / 2).max(plot.x);
199 put_str(buf, lx, inner.bottom() - 1, inner.right(), &l, text);
200 }
201 }
202}
203
204widget_impls!(BubbleChart);
205
206#[cfg(feature = "theme")]
207impl tui_nuances::Themed for BubbleChart {
208 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
209 self.theme(theme)
210 }
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216 use ratatui::widgets::Widget;
217
218 fn render(c: &BubbleChart, w: u16, h: u16) -> Buffer {
219 let a = Rect::new(0, 0, w, h);
220 let mut b = Buffer::empty(a);
221 c.render(a, &mut b);
222 b
223 }
224
225 #[test]
226 fn bigger_size_covers_more_cells() {
227 let count = |z: f64| {
228 let c =
229 BubbleChart::new([
230 BubbleSeries::new("a", [(0.0, 0.0, 100.0), (10.0, 10.0, z)]).color(Color::Red)
231 ]);
232 render(&c, 60, 20)
233 .content()
234 .iter()
235 .filter(|c| c.fg == Color::Red && c.symbol() != " ")
236 .count()
237 };
238 assert!(count(100.0) > count(1.0));
239 }
240
241 #[test]
242 fn degenerate_inputs_do_not_panic() {
243 let c = BubbleChart::new([BubbleSeries::new(
244 "a",
245 [(f64::NAN, 1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, -3.0)],
246 )]);
247 render(&c, 40, 12);
248 render(&c, 5, 3);
249 render(&c, 0, 0);
250 render(&BubbleChart::new([]), 40, 12);
251 render(
252 &BubbleChart::new([BubbleSeries::new("z", [(0.0, 0.0, 0.0)])]),
253 40,
254 12,
255 );
256 }
257
258 #[test]
259 fn max_radius_limits_size() {
260 let count = |r: u16| {
261 let c =
262 BubbleChart::new([
263 BubbleSeries::new("a", [(0.0, 0.0, 10.0), (5.0, 5.0, 100.0)]).color(Color::Red),
264 ])
265 .max_radius(r);
266 render(&c, 60, 20)
267 .content()
268 .iter()
269 .filter(|c| c.fg == Color::Red && c.symbol() != " ")
270 .count()
271 };
272 assert!(count(8) > count(2));
273 }
274
275 #[test]
276 fn multiple_series_and_markers() {
277 for m in [Marker::Braille, Marker::HalfBlock, Marker::Dot] {
278 let c = BubbleChart::new([
279 BubbleSeries::new("a", [(1.0, 1.0, 5.0)]).color(Color::Red),
280 BubbleSeries::new("b", [(2.0, 3.0, 9.0)]).color(Color::Blue),
281 ])
282 .marker(m);
283 let b = render(&c, 50, 16);
284 assert!(b.content().iter().any(|x| x.fg == Color::Blue));
285 }
286 }
287}