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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

//! A grid widget

use crate::adapt::AdaptEventCx;
use kas::layout::{DynGridStorage, GridChildInfo, GridDimensions};
use kas::layout::{GridSetter, GridSolver, RulesSetter, RulesSolver};
use kas::{layout, prelude::*};
use std::fmt::Debug;
use std::ops::{Index, IndexMut};

/// A grid of boxed widgets
///
/// This is a parameterisation of [`Grid`]
/// This is parameterised over the handler message type.
///
/// See documentation of [`Grid`] type.
pub type BoxGrid<Data> = Grid<Box<dyn Widget<Data = Data>>>;

impl_scope! {
    /// A generic grid widget
    ///
    /// Child widgets are displayed in a grid, according to each child's
    /// [`GridChildInfo`]. This allows spans and overlapping widgets. The numbers
    /// of rows and columns is determined automatically while the sizes of rows and
    /// columns are determined based on their contents (including special handling
    /// for spans, *mostly* with good results).
    ///
    /// Note that all child widgets are stored in a list internally. The order of
    /// widgets in that list does not affect display position, but does have a few
    /// effects: (a) widgets may be accessed in this order via indexing, (b) widgets
    /// are configured and drawn in this order, (c) navigating
    /// through widgets with the Tab key currently uses the list order (though it
    /// may be changed in the future to use display order).
    ///
    /// There is no protection against multiple widgets occupying the same cell.
    /// If this does happen, the last widget in that cell will appear on top, but
    /// overlapping widget drawing may not be pretty.
    ///
    /// ## Alternatives
    ///
    /// Where the entries are fixed, also consider custom [`Widget`] implementations.
    ///
    /// ## Performance
    ///
    /// Most operations are `O(n)` in the number of children.
    ///
    /// # Messages
    ///
    /// If a handler is specified via [`Self::on_messages`] then this handler is
    /// called when a child pushes a message.
    #[autoimpl(Default)]
    #[widget]
    pub struct Grid<W: Widget> {
        core: widget_core!(),
        widgets: Vec<(GridChildInfo, W)>,
        data: DynGridStorage,
        dim: GridDimensions,
        message_handlers: Vec<Box<dyn Fn(&mut AdaptEventCx, &W::Data, usize) -> bool>>,
    }

    impl Widget for Self {
        type Data = W::Data;

        fn for_child_node(
            &mut self,
            data: &W::Data,
            index: usize,
            closure: Box<dyn FnOnce(Node<'_>) + '_>,
        ) {
            if let Some(w) = self.widgets.get_mut(index) {
                closure(w.1.as_node(data));
            }
        }
    }

    impl Layout for Self {
        #[inline]
        fn num_children(&self) -> usize {
            self.widgets.len()
        }
        fn get_child(&self, index: usize) -> Option<&dyn Layout> {
            self.widgets.get(index).map(|w| w.1.as_layout())
        }
        fn size_rules(&mut self, sizer: SizeCx, axis: AxisInfo) -> SizeRules {
            let mut solver = GridSolver::<Vec<_>, Vec<_>, _>::new(axis, self.dim, &mut self.data);
            for (info, child) in &mut self.widgets {
                solver.for_child(&mut self.data, *info, |axis| {
                    child.size_rules(sizer.re(), axis)
                });
            }
            solver.finish(&mut self.data)
        }

        fn set_rect(&mut self, cx: &mut ConfigCx, rect: Rect) {
            self.core.rect = rect;
            let mut setter = GridSetter::<Vec<_>, Vec<_>, _>::new(rect, self.dim, &mut self.data);
            for (info, child) in &mut self.widgets {
                child.set_rect(cx, setter.child_rect(&mut self.data, *info));
            }
        }

        fn find_id(&mut self, coord: Coord) -> Option<Id> {
            if !self.rect().contains(coord) {
                return None;
            }
            self.widgets
                .iter_mut()
                .find_map(|(_, child)| child.find_id(coord))
                .or_else(|| Some(self.id()))
        }

        fn draw(&mut self, mut draw: DrawCx) {
            for (_, child) in &mut self.widgets {
                draw.recurse(child);
            }
        }
    }

    impl Events for Self {
        fn handle_messages(&mut self, cx: &mut EventCx, data: &Self::Data) {
            if self.message_handlers.is_empty() {
                return;
            }
            let mut update = false;
            let mut cx = AdaptEventCx::new(cx, self.id());
            let index = cx.last_child().expect("message not sent from self");
            for handler in self.message_handlers.iter() {
                update |= handler(&mut cx, data, index);
            }
            if update {
                cx.update(self.as_node(data));
            }
        }
    }
}

impl<W: Widget> Grid<W> {
    /// Construct a new instance
    #[inline]
    pub fn new() -> Self {
        Self::new_vec(vec![])
    }

    /// Construct a new instance
    #[inline]
    pub fn new_vec(widgets: Vec<(GridChildInfo, W)>) -> Self {
        let mut grid = Grid {
            widgets,
            ..Default::default()
        };
        grid.calc_dim();
        grid
    }

    /// Add a child handler to map messages of type `M` to `N`
    ///
    /// # Example
    ///
    /// ```
    /// use kas::messages::Select;
    /// use kas_widgets::{Row, Tab};
    ///
    /// #[derive(Clone, Debug)]
    /// struct MsgSelectIndex(usize);
    ///
    /// let tabs: Row<Tab> = Row::new([]).map_message(|index, Select| MsgSelectIndex(index));
    /// ```
    pub fn map_message<M, N, H>(self, handler: H) -> Self
    where
        M: Debug + 'static,
        N: Debug + 'static,
        H: Fn(usize, M) -> N + 'static,
    {
        self.on_messages(move |cx, _data, index| {
            if let Some(m) = cx.try_pop() {
                cx.push(handler(index, m));
            }
            false
        })
    }

    /// Add a child handler for messages of type `M`
    ///
    /// Where multiple message types must be handled or access to the
    /// [`AdaptEventCx`] is required, use [`Self::on_messages`] instead.
    pub fn on_message<M, H>(self, handler: H) -> Self
    where
        M: Debug + 'static,
        H: Fn(&mut AdaptEventCx, usize, M) + 'static,
    {
        self.on_messages(move |cx, _data, index| {
            if let Some(m) = cx.try_pop() {
                handler(cx, index, m);
                true
            } else {
                false
            }
        })
    }

    /// Add a child message handler (inline style)
    ///
    /// This handler is called when a child pushes a message:
    /// `f(cx, index)`, where `index` is the child's index.
    #[inline]
    pub fn on_messages<H>(mut self, handler: H) -> Self
    where
        H: Fn(&mut AdaptEventCx, &W::Data, usize) -> bool + 'static,
    {
        self.message_handlers.push(Box::new(handler));
        self
    }

    /// Get grid dimensions
    ///
    /// The numbers of rows, columns and spans is determined automatically.
    #[inline]
    pub fn dimensions(&self) -> GridDimensions {
        self.dim
    }

    /// Access layout storage
    ///
    /// Use [`Self::dimensions`] to get expected dimensions.
    #[inline]
    pub fn layout_storage(&mut self) -> &mut impl layout::GridStorage {
        &mut self.data
    }

    fn calc_dim(&mut self) {
        let mut dim = GridDimensions::default();
        for child in &self.widgets {
            dim.cols = dim.cols.max(child.0.col_end);
            dim.rows = dim.rows.max(child.0.row_end);
            if child.0.col_end - child.0.col > 1 {
                dim.col_spans += 1;
            }
            if child.0.row_end - child.0.row > 1 {
                dim.row_spans += 1;
            }
        }
        self.dim = dim;
    }

    /// Construct via a builder
    pub fn build<F: FnOnce(GridBuilder<W>)>(f: F) -> Self {
        let mut grid = Self::default();
        let _ = grid.edit(f);
        grid
    }

    /// Edit an existing grid via a builder
    ///
    /// This may be used to edit children before window construction. It may
    /// also be used from a running UI, but in this case a full reconfigure
    /// of the window's widgets is required (triggered by the the return
    /// value, [`Action::RECONFIGURE`]).
    pub fn edit<F: FnOnce(GridBuilder<W>)>(&mut self, f: F) -> Action {
        f(GridBuilder(&mut self.widgets));
        self.calc_dim();
        Action::RECONFIGURE
    }

    /// True if there are no child widgets
    pub fn is_empty(&self) -> bool {
        self.widgets.is_empty()
    }

    /// Returns the number of child widgets
    pub fn len(&self) -> usize {
        self.widgets.len()
    }

    /// Returns a reference to the child, if any
    pub fn get(&self, index: usize) -> Option<&W> {
        self.widgets.get(index).map(|t| &t.1)
    }

    /// Returns a mutable reference to the child, if any
    pub fn get_mut(&mut self, index: usize) -> Option<&mut W> {
        self.widgets.get_mut(index).map(|t| &mut t.1)
    }

    /// Iterate over childern
    pub fn iter(&self) -> impl Iterator<Item = &(GridChildInfo, W)> {
        ListIter {
            list: &self.widgets,
        }
    }

    /// Mutably iterate over childern
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut (GridChildInfo, W)> {
        ListIterMut {
            list: &mut self.widgets,
        }
    }
}

pub struct GridBuilder<'a, W: Widget>(&'a mut Vec<(GridChildInfo, W)>);
impl<'a, W: Widget> GridBuilder<'a, W> {
    /// True if there are no child widgets
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the number of child widgets
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns the number of elements the vector can hold without reallocating.
    pub fn capacity(&self) -> usize {
        self.0.capacity()
    }

    /// Reserves capacity for at least `additional` more elements to be inserted
    /// into the list. See documentation of [`Vec::reserve`].
    pub fn reserve(&mut self, additional: usize) {
        self.0.reserve(additional);
    }

    /// Remove all child widgets
    pub fn clear(&mut self) {
        self.0.clear();
    }

    /// Add a child widget
    ///
    /// The child is added to the end of the "list", thus appears last in
    /// navigation order.
    pub fn push(&mut self, info: GridChildInfo, widget: W) {
        self.0.push((info, widget));
    }

    /// Add a child widget to the given cell
    ///
    /// The child is added to the end of the "list", thus appears last in
    /// navigation order.
    pub fn push_cell(&mut self, col: u32, row: u32, widget: W) {
        let info = GridChildInfo::new(col, row);
        self.push(info, widget);
    }

    /// Add a child widget to the given cell, builder style
    ///
    /// The child is added to the end of the "list", thus appears last in
    /// navigation order.
    #[must_use]
    pub fn with_cell(self, col: u32, row: u32, widget: W) -> Self {
        self.with_cell_span(col, row, 1, 1, widget)
    }

    /// Add a child widget to the given cell, with spans
    ///
    /// Parameters `col_span` and `row_span` are the number of columns/rows
    /// spanned and should each be at least 1.
    ///
    /// The child is added to the end of the "list", thus appears last in
    /// navigation order.
    pub fn push_cell_span(&mut self, col: u32, row: u32, col_span: u32, row_span: u32, widget: W) {
        let info = GridChildInfo {
            col,
            col_end: col + col_span,
            row,
            row_end: row + row_span,
        };
        self.push(info, widget);
    }

    /// Add a child widget to the given cell, with spans, builder style
    ///
    /// Parameters `col_span` and `row_span` are the number of columns/rows
    /// spanned and should each be at least 1.
    ///
    /// The child is added to the end of the "list", thus appears last in
    /// navigation order.
    #[must_use]
    pub fn with_cell_span(
        mut self,
        col: u32,
        row: u32,
        col_span: u32,
        row_span: u32,
        widget: W,
    ) -> Self {
        self.push_cell_span(col, row, col_span, row_span, widget);
        self
    }

    /// Remove the last child widget
    ///
    /// Returns `None` if there are no children. Otherwise, this
    /// triggers a reconfigure before the next draw operation.
    pub fn pop(&mut self) -> Option<(GridChildInfo, W)> {
        self.0.pop()
    }

    /// Inserts a child widget position `index`
    ///
    /// Panics if `index > len`.
    pub fn insert(&mut self, index: usize, info: GridChildInfo, widget: W) {
        self.0.insert(index, (info, widget));
    }

    /// Removes the child widget at position `index`
    ///
    /// Panics if `index` is out of bounds.
    pub fn remove(&mut self, index: usize) -> (GridChildInfo, W) {
        self.0.remove(index)
    }

    /// Replace the child at `index`
    ///
    /// Panics if `index` is out of bounds.
    pub fn replace(&mut self, index: usize, info: GridChildInfo, widget: W) -> (GridChildInfo, W) {
        let mut item = (info, widget);
        std::mem::swap(&mut item, &mut self.0[index]);
        item
    }

    /// Append child widgets from an iterator
    pub fn extend<T: IntoIterator<Item = (GridChildInfo, W)>>(&mut self, iter: T) {
        self.0.extend(iter);
    }

    /// Resize, using the given closure to construct new widgets
    pub fn resize_with<F: Fn(usize) -> (GridChildInfo, W)>(&mut self, len: usize, f: F) {
        let l0 = self.0.len();
        if l0 > len {
            self.0.truncate(len);
        } else if l0 < len {
            self.0.reserve(len);
            for i in l0..len {
                self.0.push(f(i));
            }
        }
    }

    /// Retain only widgets satisfying predicate `f`
    ///
    /// See documentation of [`Vec::retain`].
    pub fn retain<F: FnMut(&(GridChildInfo, W)) -> bool>(&mut self, f: F) {
        self.0.retain(f);
    }

    /// Get the first index of a child occupying the given cell, if any
    pub fn find_child_cell(&self, col: u32, row: u32) -> Option<usize> {
        for (i, (info, _)) in self.0.iter().enumerate() {
            if info.col <= col && col < info.col_end && info.row <= row && row < info.row_end {
                return Some(i);
            }
        }
        None
    }

    /// Iterate over childern
    pub fn iter(&self) -> impl Iterator<Item = &(GridChildInfo, W)> {
        ListIter { list: self.0 }
    }

    /// Mutably iterate over childern
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut (GridChildInfo, W)> {
        ListIterMut { list: self.0 }
    }
}

impl<W: Widget> FromIterator<(GridChildInfo, W)> for Grid<W> {
    #[inline]
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = (GridChildInfo, W)>,
    {
        Self::new_vec(iter.into_iter().collect())
    }
}

impl<W: Widget> Index<usize> for Grid<W> {
    type Output = (GridChildInfo, W);

    fn index(&self, index: usize) -> &Self::Output {
        &self.widgets[index]
    }
}

impl<W: Widget> IndexMut<usize> for Grid<W> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.widgets[index]
    }
}

struct ListIter<'a, W: Widget> {
    list: &'a [(GridChildInfo, W)],
}
impl<'a, W: Widget> Iterator for ListIter<'a, W> {
    type Item = &'a (GridChildInfo, W);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((first, rest)) = self.list.split_first() {
            self.list = rest;
            Some(first)
        } else {
            None
        }
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }
}
impl<'a, W: Widget> ExactSizeIterator for ListIter<'a, W> {
    fn len(&self) -> usize {
        self.list.len()
    }
}

struct ListIterMut<'a, W: Widget> {
    list: &'a mut [(GridChildInfo, W)],
}
impl<'a, W: Widget> Iterator for ListIterMut<'a, W> {
    type Item = &'a mut (GridChildInfo, W);
    fn next(&mut self) -> Option<Self::Item> {
        let list = std::mem::take(&mut self.list);
        if let Some((first, rest)) = list.split_first_mut() {
            self.list = rest;
            Some(first)
        } else {
            None
        }
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }
}
impl<'a, W: Widget> ExactSizeIterator for ListIterMut<'a, W> {
    fn len(&self) -> usize {
        self.list.len()
    }
}