1use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
6
7use crate::core::geom::{Align, Rect, Size};
8use crate::core::style::Style;
9use crate::core::text::Line;
10
11pub fn label_cols(text: &str, pad: u16) -> u16 {
13 let w = UnicodeWidthStr::width(text) as u16;
14 w.saturating_add(pad.saturating_mul(2))
15}
16
17pub fn chip_cols(labels: &[&str], pad: u16) -> u16 {
24 let w = labels
25 .iter()
26 .map(|t| label_cols(t, pad))
27 .max()
28 .unwrap_or(pad.saturating_mul(2));
29
30 let (even, odd) = labels.iter().fold((0usize, 0usize), |(even, odd), text| {
31 if UnicodeWidthStr::width(*text) % 2 == 0 {
32 (even + 1, odd)
33 } else {
34 (even, odd + 1)
35 }
36 });
37 let preferred_parity = if odd > even { 1 } else { 0 };
38
39 if w % 2 == preferred_parity {
40 w
41 } else {
42 w.saturating_add(1)
43 }
44}
45
46pub fn center_pad(text: &str, width: u16) -> String {
50 pad_align(text, width, Align::Center)
51}
52
53fn clip_text(text: &str, width: u16) -> (String, u16) {
54 let mut out = String::new();
55 let mut tw = 0u16;
56 for ch in text.chars() {
57 let w = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
58 if w == 0 {
59 continue;
60 }
61 if tw + w > width {
62 break;
63 }
64 out.push(ch);
65 tw += w;
66 }
67 (out, tw)
68}
69
70fn pad_align(text: &str, width: u16, align: Align) -> String {
71 let (core, tw) = clip_text(text, width);
72 if tw >= width {
73 return core;
74 }
75 let gap = width - tw;
76 let (left, right) = match align {
77 Align::Start => (0, gap),
78 Align::End => (gap, 0),
79 Align::Center => {
80 let left = gap / 2;
81 (left, gap - left)
82 }
83 };
84 let mut s = String::with_capacity(width as usize);
85 for _ in 0..left {
86 s.push(' ');
87 }
88 s.push_str(&core);
89 for _ in 0..right {
90 s.push(' ');
91 }
92 s
93}
94
95pub const WIDE_CONT: char = '\u{FFFE}';
98
99#[derive(Clone, Copy, PartialEq, Eq, Debug)]
102pub struct Cell {
103 pub ch: char,
104 pub style: Style,
105}
106
107impl Cell {
108 pub const fn blank() -> Self {
109 Cell {
110 ch: ' ',
111 style: Style::new(),
112 }
113 }
114
115 pub const fn transparent() -> Self {
116 Cell {
117 ch: '\0',
118 style: Style::new(),
119 }
120 }
121
122 pub fn is_transparent(&self) -> bool {
123 self.ch == '\0'
124 }
125}
126
127impl Default for Cell {
128 fn default() -> Self {
129 Cell::blank()
130 }
131}
132
133#[derive(Clone)]
134pub struct Buffer {
135 pub width: u16,
136 pub height: u16,
137 cells: Vec<Cell>,
138}
139
140impl Buffer {
141 pub fn blank(size: Size) -> Self {
143 Buffer::filled(size, Cell::blank())
144 }
145
146 pub fn transparent(size: Size) -> Self {
148 Buffer::filled(size, Cell::transparent())
149 }
150
151 pub fn filled(size: Size, cell: Cell) -> Self {
152 Buffer {
153 width: size.width,
154 height: size.height,
155 cells: vec![cell; size.area() as usize],
156 }
157 }
158
159 pub fn size(&self) -> Size {
160 Size::new(self.width, self.height)
161 }
162
163 pub fn area(&self) -> Rect {
164 Rect::new(0, 0, self.width, self.height)
165 }
166
167 fn index(&self, x: u16, y: u16) -> Option<usize> {
168 if x < self.width && y < self.height {
169 Some(y as usize * self.width as usize + x as usize)
170 } else {
171 None
172 }
173 }
174
175 pub fn get(&self, x: u16, y: u16) -> Option<&Cell> {
176 self.index(x, y).map(|i| &self.cells[i])
177 }
178
179 pub fn cell_mut(&mut self, x: u16, y: u16) -> Option<&mut Cell> {
180 self.index(x, y).map(|i| &mut self.cells[i])
181 }
182
183 pub fn set(&mut self, x: u16, y: u16, ch: char, style: Style) {
184 if let Some(c) = self.cell_mut(x, y) {
185 c.ch = ch;
186 c.style = c.style.patch(style);
190 }
191 }
192
193 fn put_glyph(&mut self, x: u16, y: u16, ch: char, style: Style, limit: u16) -> u16 {
196 if x >= limit {
197 return 0;
198 }
199 let w = UnicodeWidthChar::width(ch).unwrap_or(0);
200 if w == 0 {
201 return 0;
203 }
204 if w >= 2 {
205 if x + 1 >= limit {
207 self.set(x, y, ' ', style);
208 return 1;
209 }
210 self.set(x, y, ch, style);
211 self.set(x + 1, y, WIDE_CONT, style);
212 return 2;
213 }
214 self.set(x, y, ch, style);
215 1
216 }
217
218 pub fn set_str(&mut self, x: u16, y: u16, s: &str, style: Style) -> u16 {
221 let mut cx = x;
222 for ch in s.chars() {
223 if cx >= self.width {
224 break;
225 }
226 let adv = self.put_glyph(cx, y, ch, style, self.width);
227 if adv == 0 && UnicodeWidthChar::width(ch).unwrap_or(0) == 0 {
228 continue;
229 }
230 if adv == 0 {
231 break;
232 }
233 cx = cx.saturating_add(adv);
234 }
235 cx
236 }
237
238 pub fn set_line(&mut self, x: u16, y: u16, line: &Line, max_width: u16) {
241 self.set_line_on(x, y, line, max_width, Style::new());
242 }
243
244 pub fn set_line_on(&mut self, x: u16, y: u16, line: &Line, max_width: u16, base: Style) {
249 let mut cx = x;
250 let limit = x.saturating_add(max_width).min(self.width);
251 for span in &line.spans {
252 let st = span.style.patch(base);
253 for ch in span.content.chars() {
254 if cx >= limit {
255 break;
257 }
258 let adv = self.put_glyph(cx, y, ch, st, limit);
259 if adv == 0 {
260 if UnicodeWidthChar::width(ch).unwrap_or(0) == 0 {
261 continue;
262 }
263 break;
264 }
265 cx = cx.saturating_add(adv);
266 }
267 if cx >= limit {
268 break;
269 }
270 }
271 while cx < limit {
273 self.set(cx, y, ' ', base);
274 cx += 1;
275 }
276 }
277
278 pub fn set_lines(&mut self, area: Rect, lines: &[Line], scroll: usize) {
281 self.set_lines_on(area, lines, scroll, Style::new());
282 }
283
284 pub fn set_lines_on(&mut self, area: Rect, lines: &[Line], scroll: usize, base: Style) {
287 for row in 0..area.height {
288 let idx = scroll + row as usize;
289 let y = area.y + row;
290 match lines.get(idx) {
291 Some(line) => self.set_line_on(area.x, y, line, area.width, base),
292 None => {
293 self.paint(Rect::new(area.x, y, area.width, 1), base);
294 }
295 }
296 }
297 }
298
299 pub fn fill(&mut self, rect: Rect, ch: char, style: Style) {
301 let r = rect.intersection(self.area());
302 for y in r.y..r.bottom() {
303 for x in r.x..r.right() {
304 self.set(x, y, ch, style);
305 }
306 }
307 }
308
309 pub fn paint(&mut self, rect: Rect, style: Style) {
311 self.fill(rect, ' ', style);
312 }
313
314 pub fn put_str_aligned(
319 &mut self,
320 x: u16,
321 y: u16,
322 width: u16,
323 text: &str,
324 style: Style,
325 align: Align,
326 ) {
327 if width == 0 || y >= self.height {
328 return;
329 }
330 let x = x.min(self.width);
331 let width = width.min(self.width.saturating_sub(x));
332 if width == 0 {
333 return;
334 }
335 self.paint(Rect::new(x, y, width, 1), style);
336 let padded = match align {
337 Align::Center => center_pad(text, width),
338 Align::Start => pad_align(text, width, Align::Start),
339 Align::End => pad_align(text, width, Align::End),
340 };
341 self.set_line_on(
342 x,
343 y,
344 &Line::from(crate::core::text::Span::styled(padded, style)),
345 width,
346 style,
347 );
348 }
349
350 pub fn put_label(&mut self, area: Rect, text: &str, style: Style) {
355 let area = area.intersection(self.area());
356 if area.is_empty() {
357 return;
358 }
359 self.paint(area, style);
360 let y = area.y + area.height / 2;
361 self.put_str_aligned(area.x, y, area.width, text, style, Align::Center);
362 }
363
364 pub fn blit(&mut self, ox: u16, oy: u16, src: &Buffer, skip_transparent: bool) {
367 for sy in 0..src.height {
368 for sx in 0..src.width {
369 let cell = src.cells[sy as usize * src.width as usize + sx as usize];
370 if skip_transparent && cell.is_transparent() {
371 continue;
372 }
373 self.set(ox + sx, oy + sy, cell.ch, cell.style);
374 }
375 }
376 }
377
378 pub fn diff<'a>(&'a self, prev: &Buffer) -> Vec<(u16, u16, &'a Cell)> {
381 let mut out = Vec::new();
382 if self.width != prev.width || self.height != prev.height {
383 for y in 0..self.height {
385 for x in 0..self.width {
386 out.push((x, y, &self.cells[self.index(x, y).unwrap()]));
387 }
388 }
389 return out;
390 }
391 for (i, (a, b)) in self.cells.iter().zip(prev.cells.iter()).enumerate() {
392 if a != b {
393 let x = (i % self.width as usize) as u16;
394 let y = (i / self.width as usize) as u16;
395 out.push((x, y, a));
396 }
397 }
398 out
399 }
400
401 pub fn text(&self) -> String {
404 let mut s = String::with_capacity((self.width as usize + 1) * self.height as usize);
405 for y in 0..self.height {
406 for x in 0..self.width {
407 let ch = self.cells[y as usize * self.width as usize + x as usize].ch;
408 s.push(if ch == '\0' || ch == WIDE_CONT {
409 ' '
410 } else {
411 ch
412 });
413 }
414 if y + 1 < self.height {
415 s.push('\n');
416 }
417 }
418 s
419 }
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425 use crate::core::style::{Color, Style};
426 use crate::core::text::Span;
427
428 #[test]
429 fn set_str_clips_at_edge() {
430 let mut b = Buffer::blank(Size::new(4, 1));
431 let next = b.set_str(2, 0, "hello", Style::new());
432 assert_eq!(next, 4); let row: String = (0..4).map(|x| b.get(x, 0).unwrap().ch).collect();
434 assert_eq!(row, " he");
435 }
436
437 #[test]
438 fn diff_reports_only_changes() {
439 let a = Buffer::blank(Size::new(3, 1));
440 let mut b = a.clone();
441 b.set(1, 0, 'x', Style::new().fg(Color::rgb(9, 9, 9)));
442 let d = b.diff(&a);
443 assert_eq!(d.len(), 1);
444 assert_eq!((d[0].0, d[0].1, d[0].2.ch), (1, 0, 'x'));
445 }
446
447 #[test]
448 fn set_line_clears_remainder_of_row() {
449 let mut b = Buffer::blank(Size::new(8, 1));
450 b.set_str(0, 0, "abcdefgh", Style::new());
451 b.set_line(0, 0, &Line::from("hi"), 8);
452 let row: String = (0..8).map(|x| b.get(x, 0).unwrap().ch).collect();
453 assert_eq!(row, "hi ");
454 }
455
456 #[test]
457 fn set_line_preserves_painted_panel_bg_on_tail() {
458 let panel = Color::rgb(0x22, 0x22, 0x22);
459 let mut b = Buffer::blank(Size::new(10, 1));
460 b.paint(Rect::new(0, 0, 10, 1), Style::new().bg(panel));
461 b.set_line(
463 0,
464 0,
465 &Line::from(Span::styled(
466 "Settings",
467 Style::new().fg(Color::rgb(0xe0, 0xe0, 0xe0)),
468 )),
469 10,
470 );
471 for x in 0..10 {
472 assert_eq!(
473 b.get(x, 0).unwrap().style.bg,
474 Some(panel),
475 "col {x} lost panel bg"
476 );
477 }
478 assert_eq!(b.get(0, 0).unwrap().ch, 'S');
479 assert_eq!(b.get(8, 0).unwrap().ch, ' ');
480 }
481
482 #[test]
483 fn set_lines_clears_empty_viewport_rows() {
484 let mut b = Buffer::blank(Size::new(4, 3));
485 b.set_str(0, 0, "aaaa", Style::new());
486 b.set_str(0, 1, "bbbb", Style::new());
487 b.set_str(0, 2, "cccc", Style::new());
488 let lines = vec![Line::from("x")];
489 b.set_lines(Rect::new(0, 0, 4, 3), &lines, 0);
490 assert_eq!(b.get(0, 0).unwrap().ch, 'x');
491 assert_eq!(b.get(1, 0).unwrap().ch, ' ');
492 assert_eq!(b.get(0, 1).unwrap().ch, ' ');
493 assert_eq!(b.get(0, 2).unwrap().ch, ' ');
494 }
495
496 #[test]
497 fn wide_glyph_reserves_two_cells() {
498 let mut b = Buffer::blank(Size::new(4, 1));
499 b.set_str(0, 0, "あ", Style::new());
500 assert_eq!(b.get(0, 0).unwrap().ch, 'あ');
501 assert_eq!(b.get(1, 0).unwrap().ch, WIDE_CONT);
502 assert_eq!(b.get(2, 0).unwrap().ch, ' ');
503 }
504
505 #[test]
506 fn chip_cols_prefers_the_majority_label_parity() {
507 assert_eq!(chip_cols(&["MAKE", "MARK", "SEND"], 1), 6);
508 assert_eq!(center_pad("MAKE", 6), " MAKE ");
509 assert_eq!(center_pad("MARK", 6), " MARK ");
510 assert_eq!(center_pad("SEND", 6), " SEND ");
511 }
512
513 #[test]
514 fn put_label_preserves_shared_action_width() {
515 let bg = Color::rgb(0x5a, 0x8f, 0xb0);
516 let style = Style::new().bg(bg).fg(Color::rgb(0x11, 0x11, 0x11));
517 let w = chip_cols(&["MAKE", "MARK", "SEND"], 1);
518 assert_eq!(w, 6);
519 for (word, expect) in [("MAKE", " MAKE "), ("MARK", " MARK "), ("SEND", " SEND ")] {
520 let mut b = Buffer::blank(Size::new(w, 3));
521 b.put_label(Rect::new(0, 0, w, 3), word, style);
522 let mid: String = (0..w).map(|x| b.get(x, 1).unwrap().ch).collect();
523 assert_eq!(mid, expect, "{word}");
524 let text_width = UnicodeWidthStr::width(word);
525 let pad = (w as usize - text_width) / 2;
526 assert_eq!(&mid[..pad], " ".repeat(pad));
527 assert_eq!(&mid[pad + text_width..], " ".repeat(pad));
528 }
529 }
530}