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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//!
//! Calculate the layout for an edit-mask with lots of label/widget pairs.
//!

use ratatui::layout::Rect;
use std::cmp::{max, min};

/// Constraint data for [layout_edit]
#[allow(variant_size_differences)]
#[derive(Debug)]
pub enum EditConstraint<'a> {
    /// Label by sample
    Label(&'a str),
    /// Label by width. (cols)
    LabelWidth(u16),
    /// Label by height+width. ( cols, rows).
    LabelRows(u16, u16),
    /// Label occupying the full row.
    TitleLabel,
    /// Label occupying the full row, but rendering only part of it. (cols)
    TitleLabelWidth(u16),
    /// Label occupying multiple full rows. (rows)
    TitleLabelRows(u16),
    /// Widget aligned with the label. (cols)
    Widget(u16),
    /// Widget aligned with the label. (cols, rows)
    WidgetRows(u16, u16),
    /// Empty line. Only increase the line counter.
    Empty,
    /// Empty lines. (rows). Only increase the line counter.
    EmptyRows(u16),
    /// Widget aligned with the left margin. (cols)
    LineWidget(u16),
    /// Widget aligned with the left margin. (cols, rows)
    LineWidgetRows(u16, u16),
}

/// Layout generated by [layout_edit]
#[derive(Debug, Default)]
pub struct LayoutEdit {
    label: Vec<Option<Rect>>,
    widget: Vec<Option<Rect>>,
}

impl LayoutEdit {
    /// Returns label number n.
    /// Panics if out of bounds or if there is no label at this position.
    pub fn label(&self, n: usize) -> Rect {
        self.label[n].expect("layout-error")
    }

    /// Returns widget number n.
    /// Panics if out of bounds or if there is no widget at this position.
    pub fn widget(&self, n: usize) -> Rect {
        self.widget[n].expect("layout-error")
    }

    /// Returns the label nr at the given position.
    pub fn label_at(&self, pos: (u16, u16)) -> Option<usize> {
        let mut nr = 0;
        for i in 0..self.widget.len() {
            if let Some(label) = self.label[i] {
                if label.contains(pos.into()) {
                    return Some(nr);
                }
                nr += 1;
            }
        }
        None
    }

    /// Returns the widget nr at the given position.
    pub fn widget_at(&self, pos: (u16, u16)) -> Option<usize> {
        let mut nr = 0;
        for i in 0..self.widget.len() {
            if let Some(widget) = self.widget[i] {
                if widget.contains(pos.into()) {
                    return Some(nr);
                }
                nr += 1;
            }
        }
        None
    }

    /// Create an iterator look-alike that gives access to both
    /// label and widget areas.
    ///
    /// If you render your widgets in the order of the layout, you
    /// don't need widget indexes any longer.
    pub fn iter(&self) -> LayoutEditIterator<'_> {
        LayoutEditIterator {
            l: self,
            idx_label: 0,
            idx_widget: 0,
        }
    }
}

/// Iterates both the labels and the widgets.
///
/// You have to call both to keep the iterator in sync.
/// For `TitleLable` and `RowWidget` you need only `label()` or
/// `widget()` respectively.
///
#[derive(Debug)]
pub struct LayoutEditIterator<'a> {
    idx_label: usize,
    idx_widget: usize,
    l: &'a LayoutEdit,
}

impl<'a> LayoutEditIterator<'a> {
    /// Next widget.
    ///
    /// Panic
    /// Panics if there are no more widgets.
    #[track_caller]
    pub fn widget(&mut self) -> Rect {
        let widget = self.l.widget.get(self.idx_widget).expect("no_more_widget");

        // skip layout if there was no layout for it.
        if self.idx_label < self.l.label.len() {
            if self.l.label[self.idx_label].is_none() {
                self.idx_label += 1;
            }
        }

        self.idx_widget += 1;

        widget.expect("layout-error")
    }

    /// Next label.
    ///
    /// Panic
    /// Panics if there are no more labels.
    #[track_caller]
    pub fn label(&mut self) -> Rect {
        let label = self.l.label.get(self.idx_label).expect("no_more_label");

        // skip widget if there was no layout for it.
        if self.idx_widget < self.l.widget.len() {
            if self.l.widget[self.idx_widget].is_none() {
                self.idx_widget += 1;
            }
        }

        self.idx_label += 1;

        label.expect("layout-error")
    }
}

/// Layout for an edit mask with lots of label+widget pairs.
///
/// This neatly aligns labels and widgets in one column.
///
#[allow(clippy::comparison_chain)]
pub fn layout_edit(area: Rect, constraints: &[EditConstraint<'_>]) -> LayoutEdit {
    let mut max_label = 0;
    let mut max_widget = 0;
    let mut space = 1;

    for l in constraints.iter() {
        match l {
            EditConstraint::Label(s) => {
                max_label = max(max_label, s.len() as u16);
            }
            EditConstraint::LabelWidth(w) => {
                max_label = max(max_label, *w);
            }
            EditConstraint::LabelRows(w, _) => {
                max_label = max(max_label, *w);
            }
            EditConstraint::TitleLabel => {
                // don't count
            }
            EditConstraint::TitleLabelWidth(_) => {
                // don't count
            }
            EditConstraint::TitleLabelRows(_) => {
                // don't count
            }
            EditConstraint::Widget(w) => {
                max_widget = max(max_widget, *w);
            }
            EditConstraint::WidgetRows(w, _) => {
                max_widget = max(max_widget, *w);
            }
            EditConstraint::LineWidget(_) => {
                // don't count
            }
            EditConstraint::LineWidgetRows(_, _) => {
                // don't count
            }
            EditConstraint::Empty => {}
            EditConstraint::EmptyRows(_) => {}
        }
    }

    let mut result = LayoutEdit::default();

    // area.width is a constraint too
    if max_label + space + max_widget < area.width {
        space = area.width - max_label - max_widget;
    } else if max_label + space + max_widget > area.width {
        let mut reduce = max_label + space + max_widget - area.width;

        if space > reduce {
            space -= reduce;
            reduce = 0;
        } else {
            reduce -= space;
            space = 0;
        }
        if max_label > 5 {
            if max_label - 5 > reduce {
                max_label -= reduce;
                reduce = 0;
            } else {
                reduce -= max_label - 5;
                max_label = 5;
            }
        }
        if max_widget > 5 {
            if max_widget - 5 > reduce {
                max_widget -= reduce;
                reduce = 0;
            } else {
                reduce -= max_widget - 5;
                max_widget = 5;
            }
        }
        if max_label > reduce {
            max_label -= reduce;
            reduce = 0;
        } else {
            reduce -= max_label;
            max_label = 0;
        }
        if max_widget > reduce {
            max_widget -= reduce;
            // reduce = 0;
        } else {
            // reduce -= max_widget;
            max_widget = 0;
        }
    }

    let mut x = area.x;
    let mut y = area.y;
    let total = max_label + space + max_widget;
    let mut rest_height = if area.height > 0 { area.height - 1 } else { 0 }; //todo: verify the '-1' somehow??
    let mut height = min(1, rest_height);

    for l in constraints.iter() {
        // break before
        match l {
            EditConstraint::LineWidget(_) | EditConstraint::LineWidgetRows(_, _) => {
                if x != area.x {
                    x = area.x;
                    y += height;
                    rest_height -= height;
                    height = min(1, rest_height);
                }
            }
            EditConstraint::TitleLabel
            | EditConstraint::TitleLabelWidth(_)
            | EditConstraint::TitleLabelRows(_) => {
                if x != area.x {
                    x = area.x;
                    y += height;
                    rest_height -= height;
                    height = min(1, rest_height);
                }
            }
            EditConstraint::Label(_)
            | EditConstraint::LabelWidth(_)
            | EditConstraint::LabelRows(_, _)
            | EditConstraint::Widget(_)
            | EditConstraint::WidgetRows(_, _)
            | EditConstraint::Empty
            | EditConstraint::EmptyRows(_) => {}
        }

        // self
        match l {
            EditConstraint::Label(s) => {
                result.label.push(Some(Rect::new(
                    x,
                    y,
                    min(s.len() as u16, max_label),
                    min(1, rest_height),
                )));
            }
            EditConstraint::LabelWidth(w) => {
                result.label.push(Some(Rect::new(
                    x,
                    y,
                    min(*w, max_label),
                    min(1, rest_height),
                )));
            }
            EditConstraint::LabelRows(w, h) => {
                result
                    .label
                    .push(Some(Rect::new(x, y, min(*w, max_label), min(1, *h))));
            }
            EditConstraint::TitleLabel => {
                result
                    .label
                    .push(Some(Rect::new(x, y, total, min(1, rest_height))));
                result.widget.push(None);
            }
            EditConstraint::TitleLabelWidth(w) => {
                result.label.push(Some(Rect::new(
                    x,
                    y,
                    min(*w, max_label),
                    min(1, rest_height),
                )));
                result.widget.push(None);
            }
            EditConstraint::TitleLabelRows(h) => {
                result
                    .label
                    .push(Some(Rect::new(x, y, total, min(*h, rest_height))));
                result.widget.push(None);
            }
            EditConstraint::Widget(w) => {
                result.widget.push(Some(Rect::new(
                    x,
                    y,
                    min(*w, max_widget),
                    min(1, rest_height),
                )));
            }
            EditConstraint::WidgetRows(w, h) => {
                result.widget.push(Some(Rect::new(
                    x,
                    y,
                    min(*w, max_widget),
                    min(*h, rest_height),
                )));
            }
            EditConstraint::LineWidget(w) => {
                result.label.push(None);
                result.widget.push(Some(Rect::new(
                    x,
                    y,
                    min(*w, max_widget),
                    min(1, rest_height),
                )));
            }
            EditConstraint::LineWidgetRows(w, h) => {
                result.label.push(None);
                result.widget.push(Some(Rect::new(
                    x,
                    y,
                    min(*w, max_widget),
                    min(*h, rest_height),
                )));
            }
            EditConstraint::Empty => {}
            EditConstraint::EmptyRows(_) => {}
        }

        // row-height
        match l {
            EditConstraint::Label(_)
            | EditConstraint::LabelWidth(_)
            | EditConstraint::TitleLabel
            | EditConstraint::TitleLabelWidth(_)
            | EditConstraint::Widget(_)
            | EditConstraint::Empty
            | EditConstraint::LineWidget(_) => {
                height = min(max(height, 1), rest_height);
            }
            EditConstraint::LabelRows(_, h)
            | EditConstraint::TitleLabelRows(h)
            | EditConstraint::WidgetRows(_, h)
            | EditConstraint::EmptyRows(h)
            | EditConstraint::LineWidgetRows(_, h) => {
                height = min(max(height, *h), rest_height);
            }
        }

        // break after
        match l {
            EditConstraint::Label(_)
            | EditConstraint::LabelWidth(_)
            | EditConstraint::LabelRows(_, _) => {
                x += max_label + space;
            }
            EditConstraint::TitleLabel
            | EditConstraint::TitleLabelWidth(_)
            | EditConstraint::TitleLabelRows(_) => {
                x = area.x;
                y += height;
                rest_height -= height;
                height = min(1, rest_height);
            }
            EditConstraint::Widget(_)
            | EditConstraint::WidgetRows(_, _)
            | EditConstraint::Empty
            | EditConstraint::EmptyRows(_)
            | EditConstraint::LineWidget(_)
            | EditConstraint::LineWidgetRows(_, _) => {
                x = area.x;
                y += height;
                rest_height -= height;
                height = min(1, rest_height);
            }
        };
    }

    result
}