src/functions/center_rect.rs

2512b334b421431b5e8577ab9c3031350fcd71bd
youtube-tui/src/functions/center_rect.rs history · blame · raw

36 lines · 1047 bytes

 1use tui::layout::Rect;
 2
 3pub fn center_rect(rect: (u16, u16), frame_rect: Rect) -> Result<Rect, Rect> {
 4    let width_too_big = rect.0 > frame_rect.width;
 5    let height_too_big = rect.1 > frame_rect.height;
 6
 7    if width_too_big || height_too_big {
 8        return Err(Rect {
 9            width: if width_too_big {
10                frame_rect.width
11            } else {
12                rect.0
13            },
14            height: if height_too_big {
15                frame_rect.height
16            } else {
17                rect.1
18            },
19            x: if width_too_big {
20                frame_rect.x
21            } else {
22                (frame_rect.x + frame_rect.width - rect.0) / 2
23            },
24            y: if height_too_big {
25                frame_rect.y
26            } else {
27                (frame_rect.y + frame_rect.height - rect.1) / 2
28            },
29        });
30    }
31
32    let x = (frame_rect.x + frame_rect.width - rect.0) / 2;
33    let y = (frame_rect.y + frame_rect.height - rect.1) / 2;
34
35    Ok(Rect::new(x, y, rect.0, rect.1))
36}