rat_widget/pager/
pager_layout.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use crate::layout::StructuredLayout;
use crate::pager::AreaHandle;
use ratatui::layout::Rect;
use std::cell::RefCell;
use std::rc::Rc;

/// PagerLayout holds all areas for the widgets that want to be
/// displayed.
///
/// It uses its own layout coordinates.
///
/// The layout step breaks this list into pages that can fit the
/// widgets. If your widget is too big to fit in the page area it
/// will be placed at a new page and will be clipped into shape.
///
#[derive(Debug, Default, Clone)]
pub struct PagerLayout {
    core: Rc<RefCell<PagerLayoutCore>>,
}

#[derive(Debug, Default, Clone)]
struct PagerLayoutCore {
    layout: StructuredLayout,
    // calculated breaks
    breaks: Vec<u16>,
}

impl PagerLayout {
    /// New layout.
    pub fn new(stride: usize) -> Self {
        Self {
            core: Rc::new(RefCell::new(PagerLayoutCore {
                layout: StructuredLayout::new(stride),
                ..Default::default()
            })),
        }
    }

    /// New layout from StructuredLayout
    pub fn with_layout(layout: StructuredLayout) -> Self {
        Self {
            core: Rc::new(RefCell::new(PagerLayoutCore {
                layout,
                ..Default::default()
            })),
        }
    }

    /// Has the target width of the layout changed.
    pub fn width_changed(&self, width: u16) -> bool {
        self.core.borrow().layout.width_change(width)
    }

    /// Add a rect.
    pub fn add(&mut self, area: &[Rect]) -> AreaHandle {
        // reset page to re-layout
        self.core.borrow_mut().layout.set_area(Default::default());
        self.core.borrow_mut().layout.add(area)
    }

    /// Get the layout area for the given handle
    pub fn layout_handle(&self, handle: AreaHandle) -> Box<[Rect]> {
        self.core.borrow().layout[handle]
            .to_vec()
            .into_boxed_slice()
    }

    /// Add a manual break after the given position.
    pub fn break_after(&mut self, y: u16) {
        // reset page to re-layout
        self.core.borrow_mut().layout.set_area(Default::default());
        self.core.borrow_mut().layout.break_after_row(y);
    }

    /// Add a manual break before the given position.
    pub fn break_before(&mut self, y: u16) {
        // reset page to re-layout
        self.core.borrow_mut().layout.set_area(Default::default());
        self.core.borrow_mut().layout.break_before_row(y);
    }

    /// Number of areas.
    pub fn len(&self) -> usize {
        self.core.borrow().layout.len()
    }

    /// Contains areas?
    pub fn is_empty(&self) -> bool {
        self.core.borrow().layout.is_empty()
    }

    /// Run the layout algorithm.
    pub fn layout(&mut self, page: Rect) {
        self.core.borrow_mut().layout(page);
    }

    /// Page area in layout coordinates
    pub fn page_area(&self) -> Rect {
        self.core.borrow().layout.area()
    }

    /// Number of pages after calculating the layout.
    pub fn num_pages(&self) -> usize {
        self.core.borrow().breaks.len()
    }

    /// First area on the given page.
    pub fn first_layout_area(&self, page: usize) -> Option<Box<[Rect]>> {
        let core = self.core.borrow();

        let brk = core.breaks[page];

        let r = core
            .layout
            .chunked()
            .find(|v| v.iter().find(|w| w.y >= brk).is_some())
            .map(|v| v.to_vec().into_boxed_slice());

        r
    }

    /// First area-handle on the given page.
    pub fn first_layout_handle(&self, page: usize) -> Option<AreaHandle> {
        let core = self.core.borrow();

        let brk = core.breaks[page];

        let r = core
            .layout
            .chunked() //
            .enumerate()
            .find_map(|(i, v)| {
                if v.iter().find(|w| w.y >= brk).is_some() {
                    Some(AreaHandle(i))
                } else {
                    None
                }
            });

        r
    }

    /// Locate an area by handle.
    ///
    /// This will return a Rect with a y-value relative to the
    /// page it is in. But still in layout-coords.
    ///
    /// And it returns the page the Rect is on.
    pub fn buf_handle(&self, handle: AreaHandle) -> (usize, Box<[Rect]>) {
        let area = &self.core.borrow().layout[handle];
        self.buf_areas(area)
    }

    /// Locate an area.
    ///
    /// This will return a Rect with a y-value relative to the
    /// page it is in. But still in layout-coords.
    ///
    /// This will clip the bounds to the page area if not
    /// displayable otherwise.
    ///
    /// And it returns the page the Rect is on.
    pub fn buf_area(&self, area: Rect) -> (usize, Rect) {
        let tmp = self.buf_areas(&[area]);
        (tmp.0, tmp.1[0])
    }

    /// Locate the given areas on one page.
    ///
    /// The correct page for top-most area is used for all areas.
    ///
    /// This will return a Rect with a y-value relative to the
    /// page it is in. But still in layout-coords.
    ///
    /// This will clip the bounds to the page area.
    ///
    /// And it returns the page the Rect is on.
    fn buf_areas(&self, area: &[Rect]) -> (usize, Box<[Rect]>) {
        let core = self.core.borrow();

        let min_y = area.iter().map(|v| v.y).min().expect("array of rect");

        // find page
        let (page_nr, brk) = core
            .breaks
            .iter()
            .enumerate()
            .rev()
            .find(|(_i, v)| **v <= min_y)
            .expect("valid breaks");

        // clip to fit
        let clip_area = Rect::new(
            0, //
            0,
            core.layout.area().width,
            core.layout.area().height,
        );

        let mut res = Vec::new();
        for a in area.iter() {
            let r = Rect::new(
                a.x, //
                a.y - *brk,
                a.width,
                a.height,
            )
            .intersection(clip_area);
            res.push(r);
        }

        (page_nr, res.into_boxed_slice())
    }
}

impl PagerLayoutCore {
    /// Run the layout algorithm.
    fn layout(&mut self, page: Rect) {
        if self.layout.area() == page {
            return;
        }
        self.layout.set_area(page);

        // must not change the order of the areas.
        // gave away handles ...
        let mut areas = self.layout.as_slice().to_vec();
        areas.sort_by(|a, b| a.y.cmp(&b.y));

        self.layout.sort_row_breaks_desc();
        self.breaks.clear();

        self.breaks.push(0);

        let mut last_break = 0;
        let mut man_breaks = self.layout.row_breaks().to_vec();

        for v in areas.iter() {
            if let Some(brk_y) = man_breaks.last() {
                if v.y >= *brk_y {
                    // don't break at the breaks.
                    // start the new page with a fresh widget :)
                    self.breaks.push(v.y);
                    last_break = v.y;
                    man_breaks.pop();
                }
            }

            if v.y > last_break {
                let ry = v.y - last_break;
                if ry + v.height > page.height {
                    self.breaks.push(v.y);
                    last_break = v.y;
                }
            }
        }
    }
}

#[cfg(test)]
mod test {
    use crate::pager::PagerLayout;
    use ratatui::layout::Rect;
    use std::ops::Deref;

    fn hr(y: u16, height: u16) -> [Rect; 1] {
        [Rect::new(0, y, 0, height)]
    }

    #[test]
    fn test_layout() {
        let mut p0 = PagerLayout::new(1);

        p0.add(&hr(5, 1));
        p0.add(&hr(5, 2));
        p0.add(&hr(9, 1));
        p0.add(&hr(9, 2));
        p0.add(&hr(9, 1));
        p0.add(&hr(9, 0));
        p0.add(&hr(12, 1));
        p0.add(&hr(14, 1));
        p0.add(&hr(16, 1));
        p0.add(&hr(18, 1));
        p0.add(&hr(19, 1));
        p0.add(&hr(20, 1));

        p0.layout(Rect::new(0, 0, 0, 10));

        assert_eq!(p0.core.borrow().breaks.deref(), &vec![0, 9, 19]);
    }
}