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
572
573
574
575
576
577
578
579
580
581
582
583
584
// 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 sizes adjustable via dividing handles

use std::collections::hash_map::{Entry, HashMap};
use std::ops::{Index, IndexMut};

use super::{GripMsg, GripPart};
use kas::layout::{self, RulesSetter, RulesSolver};
use kas::prelude::*;
use kas::theme::Feature;

/// A row/column of boxed widgets
///
/// Parameters: `Data`, `D` (direction).
///
/// See documentation of [`Splitter`] type.
pub type BoxSplitter<Data, D> = Splitter<Box<dyn Widget<Data = Data>>, D>;

impl_scope! {
    /// A resizable row/column widget
    ///
    /// Similar to [`crate::List`] but with draggable handles between items.
    // TODO: better doc
    #[derive(Clone, Default, Debug)]
    #[widget]
    pub struct Splitter<W: Widget, D: Directional = Direction> {
        core: widget_core!(),
        widgets: Vec<W>,
        handles: Vec<GripPart>,
        data: layout::DynRowStorage,
        direction: D,
        size_solved: bool,
        next: usize,
        id_map: HashMap<usize, usize>, // map key of Id to index
    }

    impl Self where D: Default {
        /// Construct a new instance
        pub fn new(widgets: impl Into<Vec<W>>) -> Self {
            Self::new_dir(widgets, Default::default())
        }
    }
    impl<W: Widget> Splitter<W, kas::dir::Right> {
        /// Construct a new instance
        pub fn right(widgets: impl Into<Vec<W>>) -> Self {
            Self::new(widgets)
        }
    }
    impl<W: Widget> Splitter<W, kas::dir::Down> {
        /// Construct a new instance
        pub fn down(widgets: impl Into<Vec<W>>) -> Self {
            Self::new(widgets)
        }
    }

    impl Self {
        /// Construct a new instance with explicit direction
        pub fn new_dir(widgets: impl Into<Vec<W>>, direction: D) -> Self {
            let widgets = widgets.into();
            let mut handles = Vec::new();
            handles.resize_with(widgets.len().saturating_sub(1), GripPart::new);
            Splitter {
                core: Default::default(),
                widgets,
                handles,
                data: Default::default(),
                direction,
                size_solved: false,
                next: 0,
                id_map: Default::default(),
            }
        }

        // Assumption: index is a valid entry of self.widgets
        fn make_next_id(&mut self, is_handle: bool, index: usize) -> Id {
            let child_index = (2 * index) + (is_handle as usize);
            if !is_handle {
                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()) {
                            self.id_map.insert(key, child_index);
                            return child.id();
                        }
                    }
                }
            }

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

    impl Layout for Self {
        #[inline]
        fn num_children(&self) -> usize {
            self.widgets.len() + self.handles.len()
        }
        fn get_child(&self, index: usize) -> Option<&dyn Layout> {
            if (index & 1) != 0 {
                self.handles.get(index >> 1).map(|w| w.as_layout())
            } else {
                self.widgets.get(index >> 1).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())
        }

        fn size_rules(&mut self, sizer: SizeCx, axis: AxisInfo) -> SizeRules {
            if self.widgets.is_empty() {
                return SizeRules::EMPTY;
            }
            assert_eq!(self.handles.len() + 1, self.widgets.len());

            let handle_rules = sizer.feature(Feature::Separator, axis);

            let dim = (self.direction, self.num_children());
            let mut solver = layout::RowSolver::new(axis, dim, &mut self.data);

            let mut n = 0;
            loop {
                assert!(n < self.widgets.len());
                let widgets = &mut self.widgets;
                solver.for_child(&mut self.data, n << 1, |axis| {
                    widgets[n].size_rules(sizer.re(), axis)
                });

                if n >= self.handles.len() {
                    break;
                }
                let handles = &mut self.handles;
                solver.for_child(&mut self.data, (n << 1) + 1, |axis| {
                    handles[n].size_rules(sizer.re(), axis);
                    handle_rules
                });
                n += 1;
            }
            solver.finish(&mut self.data)
        }

        fn set_rect(&mut self, cx: &mut ConfigCx, rect: Rect) {
            self.core.rect = rect;
            self.size_solved = true;
            if self.widgets.is_empty() {
                return;
            }
            assert!(self.handles.len() + 1 == self.widgets.len());

            let dim = (self.direction, self.num_children());
            let mut setter = layout::RowSetter::<D, Vec<i32>, _>::new(rect, dim, &mut self.data);

            let mut n = 0;
            loop {
                assert!(n < self.widgets.len());
                self.widgets[n].set_rect(cx, setter.child_rect(&mut self.data, n << 1));

                if n >= self.handles.len() {
                    break;
                }

                // TODO(opt): calculate all maximal sizes simultaneously
                let index = (n << 1) + 1;
                let track = setter.maximal_rect_of(&mut self.data, index);
                self.handles[n].set_rect(cx, track);
                let handle = setter.child_rect(&mut self.data, index);
                let _ = self.handles[n].set_size_and_offset(handle.size, handle.pos - track.pos);

                n += 1;
            }
        }

        fn find_id(&mut self, coord: Coord) -> Option<Id> {
            if !self.rect().contains(coord) || !self.size_solved {
                return None;
            }

            // find_child should gracefully handle the case that a coord is between
            // widgets, so there's no harm (and only a small performance loss) in
            // calling it twice.

            let solver = layout::RowPositionSolver::new(self.direction);
            if let Some(child) = solver.find_child_mut(&mut self.widgets, coord) {
                return child.find_id(coord).or_else(|| Some(self.id()));
            }

            let solver = layout::RowPositionSolver::new(self.direction);
            if let Some(child) = solver.find_child_mut(&mut self.handles, coord) {
                return child.find_id(coord).or_else(|| Some(self.id()));
            }

            Some(self.id())
        }

        fn draw(&mut self, mut draw: DrawCx) {
            if !self.size_solved {
                return;
            }
            // as with find_id, there's not much harm in invoking the solver twice

            let solver = layout::RowPositionSolver::new(self.direction);
            solver.for_children(&mut self.widgets, draw.get_clip_rect(), |w| {
                draw.recurse(w);
            });

            let solver = layout::RowPositionSolver::new(self.direction);
            solver.for_children(&mut self.handles, draw.get_clip_rect(), |w| {
                draw.separator(w.rect())
            });
        }
    }

    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 (index & 1) != 0 {
                if let Some(w) = self.handles.get_mut(index >> 1) {
                    closure(w.as_node(&()));
                }
            } else {
                if let Some(w) = self.widgets.get_mut(index >> 1) {
                    closure(w.as_node(data));
                }
            }
        }
    }

    impl Events for Self {
        fn make_child_id(&mut self, child_index: usize) -> Id {
            let is_handle = (child_index & 1) != 0;
            self.make_next_id(is_handle, child_index / 2)
        }

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

        fn handle_messages(&mut self, cx: &mut EventCx, _: &Self::Data) {
            let index = cx.last_child().expect("message not sent from self");
            if (index & 1) == 1 {
                if let Some(GripMsg::PressMove(offset)) = cx.try_pop() {
                    let n = index >> 1;
                    assert!(n < self.handles.len());
                    let action = self.handles[n].set_offset(offset).1;
                    cx.action(&self, action);
                    self.adjust_size(&mut cx.config_cx(), n);
                }
            }
        }
    }

    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> Splitter<W, D> {
    /// 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);
        let len = self.widgets.len().saturating_sub(1);
        self.handles.resize_with(len, GripPart::new);
        Action::RECONFIGURE
    }

    fn adjust_size(&mut self, cx: &mut ConfigCx, n: usize) {
        assert!(n < self.handles.len());
        assert_eq!(self.widgets.len(), self.handles.len() + 1);
        let index = 2 * n + 1;

        let hrect = self.handles[n].rect();
        let width1 = (hrect.pos - self.core.rect.pos).extract(self.direction);
        let width2 = (self.core.rect.size - hrect.size).extract(self.direction) - width1;

        let dim = (self.direction, self.num_children());
        let mut setter =
            layout::RowSetter::<D, Vec<i32>, _>::new_unsolved(self.core.rect, dim, &mut self.data);
        setter.solve_range(&mut self.data, 0..index, width1);
        setter.solve_range(&mut self.data, (index + 1)..dim.1, width2);
        setter.update_offsets(&mut self.data);

        let mut n = 0;
        loop {
            assert!(n < self.widgets.len());
            self.widgets[n].set_rect(cx, setter.child_rect(&mut self.data, n << 1));

            if n >= self.handles.len() {
                break;
            }

            let index = (n << 1) + 1;
            let track = self.handles[n].track();
            self.handles[n].set_rect(cx, track);
            let handle = setter.child_rect(&mut self.data, index);
            let _ = self.handles[n].set_size_and_offset(handle.size, handle.pos - track.pos);

            n += 1;
        }
    }

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

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

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

    /// 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();
        if index > 0 {
            let len = self.handles.len();
            let id = self.make_next_id(true, len);
            let mut w = GripPart::new();
            cx.configure(w.as_node(&()), id);
            self.handles.push(w);
        }

        let id = self.make_next_id(false, index);
        cx.configure(widget.as_node(data), id);
        self.widgets.push(widget);

        self.size_solved = false;
        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);
                }
            }

            if let Some(w) = self.handles.pop() {
                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 += 2;
            }
        }

        if !self.widgets.is_empty() {
            let index = index.min(self.handles.len());
            let id = self.make_next_id(true, index);
            let mut w = GripPart::new();
            cx.configure(w.as_node(&()), id);
            self.handles.insert(index, w);
        }

        let id = self.make_next_id(false, index);
        cx.configure(widget.as_node(data), id);
        self.widgets.insert(index, widget);

        self.size_solved = false;
        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 {
        if !self.handles.is_empty() {
            let index = index.min(self.handles.len());
            let w = self.handles.remove(index);
            if let Some(key) = w.id_ref().next_key_after(self.id_ref()) {
                self.id_map.remove(&key);
            }
        }

        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 -= 2;
            }
        }
        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_next_id(false, 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);
            }
        }

        self.size_solved = false;
        cx.resize(self);

        w
    }

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

        for mut widget in iter {
            let index = self.widgets.len();
            if index > 0 {
                let id = self.make_next_id(true, self.handles.len());
                let mut w = GripPart::new();
                cx.configure(w.as_node(&()), id);
                self.handles.push(w);
            }

            let id = self.make_next_id(false, index);
            cx.configure(widget.as_node(data), id);
            self.widgets.push(widget);
        }

        self.size_solved = false;
        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: Fn(usize) -> W>(
        &mut self,
        data: &W::Data,
        cx: &mut ConfigCx,
        len: usize,
        f: F,
    ) {
        let old_len = self.widgets.len();

        if len < old_len {
            cx.resize(&self);
            loop {
                let result = self.widgets.pop();
                if let Some(w) = result.as_ref() {
                    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 let Some(w) = self.handles.pop() {
                        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 {
                if index > 0 {
                    let id = self.make_next_id(true, self.handles.len());
                    let mut w = GripPart::new();
                    cx.configure(w.as_node(&()), id);
                    self.handles.push(w);
                }

                let id = self.make_next_id(false, index);
                let mut widget = f(index);
                cx.configure(widget.as_node(data), id);
                self.widgets.push(widget);
            }

            self.size_solved = false;
            cx.resize(self);
        }
    }
}