Skip to main content

lune/
geometry.rs

1use std::num::NonZeroU32;
2use std::ops::Range;
3
4use lune_pty::PtySize;
5use lune_terminal::{CellPosition, MAX_CELLS, PixelPosition, PixelSize};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub struct PixelRect {
9    pub origin: PixelPosition,
10    pub size: PixelSize,
11}
12
13/// Physical pixel geometry measured from the terminal content origin.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub struct GridGeometry {
16    size: PtySize,
17    cell: Option<PixelSize>,
18}
19
20impl GridGeometry {
21    /// Fits whole cells inside the available content area, leaving unused
22    /// pixels at the right and bottom. The grid must fit terminal and PTY limits.
23    pub fn fit(available: PixelSize, cell: PixelSize) -> Option<Self> {
24        let columns = u16::try_from(available.width.get() / cell.width).ok()?;
25        let rows = u16::try_from(available.height.get() / cell.height).ok()?;
26        if columns == 0 || rows == 0 || u32::from(columns) * u32::from(rows) > MAX_CELLS as u32 {
27            return None;
28        }
29        let pixel_width = u16::try_from(u32::from(columns) * cell.width.get()).ok()?;
30        let pixel_height = u16::try_from(u32::from(rows) * cell.height.get()).ok()?;
31        Some(Self {
32            size: PtySize {
33                rows,
34                columns,
35                pixel_width,
36                pixel_height,
37            },
38            cell: Some(cell),
39        })
40    }
41
42    pub(crate) fn from_pty_size(size: PtySize) -> Self {
43        let cell = exact_cell_extent(size.pixel_width, size.columns)
44            .zip(exact_cell_extent(size.pixel_height, size.rows))
45            .map(|(width, height)| PixelSize { width, height });
46        Self { size, cell }
47    }
48
49    pub fn pty_size(self) -> PtySize {
50        self.size
51    }
52
53    pub fn text_area_pixels(self) -> Option<PixelSize> {
54        let width = NonZeroU32::new(u32::from(self.size.pixel_width))?;
55        let height = NonZeroU32::new(u32::from(self.size.pixel_height))?;
56        Some(PixelSize { width, height })
57    }
58
59    /// Uniform cell dimensions when both text area extents divide evenly into the grid.
60    pub fn cell_pixels(self) -> Option<PixelSize> {
61        self.cell
62    }
63
64    pub(crate) fn contains(self, pixel: PixelPosition) -> bool {
65        pixel.x < u32::from(self.size.pixel_width) && pixel.y < u32::from(self.size.pixel_height)
66    }
67
68    /// Maps a pixel inside the grid to its cell when uniform cell metrics are known.
69    pub fn cell_at(self, pixel: PixelPosition) -> Option<CellPosition> {
70        let cell = self.cell?;
71        self.contains(pixel).then(|| CellPosition {
72            row: (pixel.y / cell.height) as usize,
73            column: (pixel.x / cell.width) as usize,
74        })
75    }
76
77    /// Returns the center pixel of `cell` inside the committed grid.
78    pub fn cell_center_pixel(self, cell: CellPosition) -> Option<PixelPosition> {
79        let metrics = self.cell?;
80        if cell.row >= usize::from(self.size.rows) || cell.column >= usize::from(self.size.columns)
81        {
82            return None;
83        }
84        Some(PixelPosition {
85            x: cell.column as u32 * metrics.width.get() + metrics.width.get() / 2,
86            y: cell.row as u32 * metrics.height.get() + metrics.height.get() / 2,
87        })
88    }
89
90    /// Returns the pixel bounds of a nonempty column range clipped to the grid.
91    #[inline]
92    pub fn row_rect(self, row: usize, columns: Range<usize>) -> Option<PixelRect> {
93        let cell = self.cell?;
94        let end = columns.end.min(usize::from(self.size.columns));
95        if row >= usize::from(self.size.rows) || columns.start >= end {
96            return None;
97        }
98        let width = NonZeroU32::new((end - columns.start) as u32 * cell.width.get())?;
99        Some(PixelRect {
100            origin: PixelPosition {
101                x: columns.start as u32 * cell.width.get(),
102                y: row as u32 * cell.height.get(),
103            },
104            size: PixelSize {
105                width,
106                height: cell.height,
107            },
108        })
109    }
110}
111
112fn exact_cell_extent(pixels: u16, cells: u16) -> Option<NonZeroU32> {
113    if cells == 0 || !pixels.is_multiple_of(cells) {
114        return None;
115    }
116    NonZeroU32::new(u32::from(pixels / cells))
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn cell_center_pixel_round_trips_inside_grid_and_rejects_out_of_bounds() {
125        let cell = PixelSize {
126            width: NonZeroU32::new(10).unwrap(),
127            height: NonZeroU32::new(20).unwrap(),
128        };
129        let available = PixelSize {
130            width: NonZeroU32::new(80).unwrap(),
131            height: NonZeroU32::new(40).unwrap(),
132        };
133        let grid = GridGeometry::fit(available, cell).unwrap();
134        let target = CellPosition { row: 1, column: 3 };
135        let center = grid.cell_center_pixel(target).unwrap();
136        assert_eq!(center, PixelPosition { x: 35, y: 30 });
137        assert_eq!(grid.cell_at(center), Some(target));
138        assert!(
139            grid.cell_center_pixel(CellPosition { row: 2, column: 0 })
140                .is_none()
141        );
142        assert!(
143            grid.cell_center_pixel(CellPosition { row: 0, column: 8 })
144                .is_none()
145        );
146    }
147}