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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
// 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 row or column with run-time adjustable contents

use kas::dir::{Down, Right};
use kas::{layout, prelude::*};
use std::collections::hash_map::{Entry, HashMap};
use std::fmt::Debug;
use std::ops::{Index, IndexMut};

use crate::adapt::AdaptEventCx;

/// A generic row widget
///
/// See documentation of [`List`] type.
pub type Row<W> = List<W, Right>;

/// A generic column widget
///
/// See documentation of [`List`] type.
pub type Column<W> = List<W, Down>;

/// A row of boxed widgets
///
/// See documentation of [`List`] type.
pub type BoxRow<Data> = BoxList<Data, Right>;

/// A column of boxed widgets
///
/// See documentation of [`List`] type.
pub type BoxColumn<Data> = BoxList<Data, Down>;

/// A row/column of boxed widgets
///
/// This is parameterised over directionality.
///
/// See documentation of [`List`] type.
pub type BoxList<Data, D> = List<Box<dyn Widget<Data = Data>>, D>;

impl_scope! {
    /// A generic row/column widget
    ///
    /// This type is roughly [`Vec`] but for widgets. Generics:
    ///
    /// -   `W:` [`Widget`] — type of widget
    /// -   `D:` [`Directional`] — fixed or run-time direction of layout
    ///
    /// ## Alternatives
    ///
    /// Some more specific type-defs are available:
    ///
    /// -   [`Row`] and [`Column`] fix the direction `D`
    /// -   [`BoxList`] fixes the widget type to `Box<dyn Widget<Data = Data>>`
    /// -   [`BoxRow`] and [`BoxColumn`] fix both type parameters
    ///
    /// ## Performance
    ///
    /// Configuring and resizing elements is O(n) in the number of children.
    /// Drawing and event handling is O(log n) in the number of children (assuming
    /// only a small number are visible at any one time).
    ///
    /// # Messages
    ///
    /// If a handler is specified via [`Self::on_messages`] then this handler is
    /// called when a child pushes a message. This allows associating the
    /// child's index with a message.
    #[autoimpl(Default where D: Default)]
    #[widget {
        layout = slice! 'layout (self.direction, self.widgets);
    }]
    pub struct List<W: Widget, D: Directional> {
        core: widget_core!(),
        widgets: Vec<W>,
        direction: D,
        next: usize,
        id_map: HashMap<usize, usize>, // map key of Id to index
        message_handlers: Vec<Box<dyn Fn(&mut AdaptEventCx, &W::Data, usize) -> bool>>,
    }

    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.as_layout())
        }

        fn find_child_index(&self, id: &Id) -> Option<usize> {
            id.next_key_after(self.id_ref())
                .and_then(|k| self.id_map.get(&k).cloned())
        }
    }

    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.as_node(data));
            }
        }
    }

    impl Events for Self {
        /// Make a fresh id based on `self.next` then insert into `self.id_map`
        fn make_child_id(&mut self, index: usize) -> Id {
            if let Some(child) = self.widgets.get(index) {
                // Use the widget's existing identifier, if any
                if child.id_ref().is_valid() {
                    if let Some(key) = child.id_ref().next_key_after(self.id_ref()) {
                        if let Entry::Vacant(entry) = self.id_map.entry(key) {
                            entry.insert(index);
                            return child.id();
                        }
                    }
                }
            }

            loop {
                let key = self.next;
                self.next += 1;
                if let Entry::Vacant(entry) = self.id_map.entry(key) {
                    entry.insert(index);
                    return self.id_ref().make_child(key);
                }
            }
        }

        fn configure(&mut self, _: &mut ConfigCx) {
            self.id_map.clear();
        }

        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 Self
    where
        D: Default,
    {
        /// Construct a new instance
        ///
        /// This constructor is available where the direction is determined by the
        /// type: for `D: Directional + Default`. In other cases, use
        /// [`Self::new_dir`].
        pub fn new(widgets: impl Into<Vec<W>>) -> Self {
            Self::new_dir(widgets, D::default())
        }
    }

    impl<W: Widget> List<W, kas::dir::Left> {
        /// Construct a new instance
        pub fn left(widgets: impl Into<Vec<W>>) -> Self {
            Self::new(widgets)
        }
    }
    impl<W: Widget> List<W, kas::dir::Right> {
        /// Construct a new instance
        pub fn right(widgets: impl Into<Vec<W>>) -> Self {
            Self::new(widgets)
        }
    }
    impl<W: Widget> List<W, kas::dir::Up> {
        /// Construct a new instance
        pub fn up(widgets: impl Into<Vec<W>>) -> Self {
            Self::new(widgets)
        }
    }
    impl<W: Widget> List<W, kas::dir::Down> {
        /// Construct a new instance
        pub fn down(widgets: impl Into<Vec<W>>) -> Self {
            Self::new(widgets)
        }
    }

    impl<W: Widget> List<W, Direction> {
        /// Set the direction of contents
        pub fn set_direction(&mut self, direction: Direction) -> Action {
            if direction == self.direction {
                return Action::empty();
            }

            self.direction = direction;
            // Note: most of the time SET_RECT would be enough, but margins can be different
            Action::RESIZE
        }
    }

    impl Self {
        /// Construct a new instance with explicit direction
        #[inline]
        pub fn new_dir(widgets: impl Into<Vec<W>>, direction: D) -> Self {
            List {
                core: Default::default(),
                widgets: widgets.into(),
                direction,
                next: 0,
                id_map: Default::default(),
                message_handlers: vec![],
            }
        }

        /// 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
        }

        /// Edit the list of children directly
        ///
        /// 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`]).
        #[inline]
        pub fn edit<F: FnOnce(&mut Vec<W>)>(&mut self, f: F) -> Action {
            f(&mut self.widgets);
            Action::RECONFIGURE
        }

        /// Get the direction of contents
        pub fn direction(&self) -> Direction {
            self.direction.as_direction()
        }

        /// Access layout storage
        ///
        /// The number of columns/rows is [`Self.len`].
        #[inline]
        pub fn layout_storage(&mut self) -> &mut impl layout::RowStorage {
            &mut self.core.layout
        }

        /// 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()
        }

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

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

        /// 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)
        }

        /// Append a child widget
        ///
        /// The new child is configured immediately. [`Action::RESIZE`] is
        /// triggered.
        ///
        /// Returns the new element's index.
        pub fn push(&mut self, cx: &mut ConfigCx, data: &W::Data, mut widget: W) -> usize {
            let index = self.widgets.len();
            let id = self.make_child_id(index);
            cx.configure(widget.as_node(data), id);
            self.widgets.push(widget);

            cx.resize(self);
            index
        }

        /// Remove the last child widget (if any) and return
        ///
        /// Triggers [`Action::RESIZE`].
        pub fn pop(&mut self, cx: &mut EventState) -> Option<W> {
            let result = self.widgets.pop();
            if let Some(w) = result.as_ref() {
                cx.resize(&self);

                if w.id_ref().is_valid() {
                    if let Some(key) = w.id_ref().next_key_after(self.id_ref()) {
                        self.id_map.remove(&key);
                    }
                }
            }
            result
        }

        /// Inserts a child widget position `index`
        ///
        /// Panics if `index > len`.
        ///
        /// The new child is configured immediately. Triggers [`Action::RESIZE`].
        pub fn insert(&mut self, cx: &mut ConfigCx, data: &W::Data, index: usize, mut widget: W) {
            for v in self.id_map.values_mut() {
                if *v >= index {
                    *v += 1;
                }
            }

            let id = self.make_child_id(index);
            cx.configure(widget.as_node(data), id);
            self.widgets.insert(index, widget);
            cx.resize(self);
        }

        /// Removes the child widget at position `index`
        ///
        /// Panics if `index` is out of bounds.
        ///
        /// Triggers [`Action::RESIZE`].
        pub fn remove(&mut self, cx: &mut EventState, index: usize) -> W {
            let w = self.widgets.remove(index);
            if w.id_ref().is_valid() {
                if let Some(key) = w.id_ref().next_key_after(self.id_ref()) {
                    self.id_map.remove(&key);
                }
            }

            cx.resize(&self);

            for v in self.id_map.values_mut() {
                if *v > index {
                    *v -= 1;
                }
            }
            w
        }

        /// Replace the child at `index`
        ///
        /// Panics if `index` is out of bounds.
        ///
        /// The new child is configured immediately. Triggers [`Action::RESIZE`].
        pub fn replace(&mut self, cx: &mut ConfigCx, data: &W::Data, index: usize, mut w: W) -> W {
            let id = self.make_child_id(index);
            cx.configure(w.as_node(data), id);
            std::mem::swap(&mut w, &mut self.widgets[index]);

            if w.id_ref().is_valid() {
                if let Some(key) = w.id_ref().next_key_after(self.id_ref()) {
                    self.id_map.remove(&key);
                }
            }

            cx.resize(self);

            w
        }

        /// Append child widgets from an iterator
        ///
        /// New children are configured immediately. Triggers [`Action::RESIZE`].
        pub fn extend<T>(&mut self, cx: &mut ConfigCx, data: &W::Data, iter: T)
        where
            T: IntoIterator<Item = W>,
        {
            let iter = iter.into_iter();
            if let Some(ub) = iter.size_hint().1 {
                self.widgets.reserve(ub);
            }
            for mut w in iter {
                let id = self.make_child_id(self.widgets.len());
                cx.configure(w.as_node(data), id);
                self.widgets.push(w);
            }

            cx.resize(self);
        }

        /// Resize, using the given closure to construct new widgets
        ///
        /// New children are configured immediately. Triggers [`Action::RESIZE`].
        pub fn resize_with<F>(&mut self, cx: &mut ConfigCx, data: &W::Data, len: usize, f: F)
        where
            F: Fn(usize) -> W,
        {
            let old_len = self.widgets.len();

            if len < old_len {
                cx.resize(&self);
                loop {
                    let w = self.widgets.pop().unwrap();
                    if w.id_ref().is_valid() {
                        if let Some(key) = w.id_ref().next_key_after(self.id_ref()) {
                            self.id_map.remove(&key);
                        }
                    }
                    if len == self.widgets.len() {
                        return;
                    }
                }
            }

            if len > old_len {
                self.widgets.reserve(len - old_len);
                for index in old_len..len {
                    let id = self.make_child_id(index);
                    let mut w = f(index);
                    cx.configure(w.as_node(data), id);
                    self.widgets.push(w);
                }
                cx.resize(self);
            }
        }

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

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

    impl Index<usize> for Self {
        type Output = W;

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

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

impl<W: Widget, D: Directional + Default> FromIterator<W> for List<W, D> {
    #[inline]
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = W>,
    {
        Self::new(iter.into_iter().collect::<Vec<W>>())
    }
}

struct ListIter<'a, W: Widget> {
    list: &'a [W],
}
impl<'a, W: Widget> Iterator for ListIter<'a, W> {
    type Item = &'a 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 [W],
}
impl<'a, W: Widget> Iterator for ListIterMut<'a, W> {
    type Item = &'a mut 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()
    }
}