rat-widget 3.0.2

ratatui widgets extended edition
Documentation
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
//! Vertical or horizontal multiple split.
//!
//! ```
//! # use ratatui_core::buffer::Buffer;
//! # use ratatui_core::layout::{Constraint, Rect};
//! # use ratatui_core::text::Line;
//! # use ratatui_core::widgets::{Widget, StatefulWidget};
//! use rat_widget::splitter::{Split, SplitState, SplitType};
//! # struct State { split: SplitState }
//! # let mut state = State { split: Default::default() };
//! # let area = Rect::default();
//! # let mut buf = Buffer::default();
//! # let buf = &mut buf;
//!
//! let split = Split::horizontal()
//!     .constraints([
//!         Constraint::Length(25),
//!         Constraint::Length(25),
//!         Constraint::Fill(1),
//!     ])
//!     .split_type(SplitType::Scroll)
//!     .into_widget(area, &mut state.split);
//!
//! Line::from("first")
//!     .render(state.split.widget_areas[0], buf);
//!
//! Line::from("second")
//!     .render(state.split.widget_areas[1], buf);
//!
//! Line::from("third")
//!     .render(state.split.widget_areas[2], buf);
//!
//! // render split decorations
//! split.render(area, buf, &mut state.split);
//!
//! ```
use crate::_private::NonExhaustive;
use crate::splitter::split_impl::{get_fill_char, get_join_0, get_join_1, get_mark_0, get_mark_1};
use crate::splitter::split_layout::layout_split;
use crate::util::{fill_buf_area, revert_style};
use rat_event::util::MouseFlagsN;
use rat_event::{HandleEvent, MouseOnly, Outcome, Regular, ct_event, event_flow};
use rat_focus::{FocusBuilder, FocusFlag, HasFocus, Navigation};
use rat_reloc::{RelocatableState, relocate_area, relocate_areas, relocate_positions};
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Constraint, Direction, Position, Rect};
use ratatui_core::style::Style;
use ratatui_core::widgets::{StatefulWidget, Widget};
use ratatui_crossterm::crossterm::event::Event;
use ratatui_widgets::block::Block;
use ratatui_widgets::borders::BorderType;
use std::cmp::{max, min};
use std::iter;
use std::rc::Rc;
use unicode_segmentation::UnicodeSegmentation;

mod split_impl;
mod split_layout;

#[derive(Debug, Default, Clone)]
/// Splits the area in multiple parts and renders a UI that
/// allows changing the sizes.
///
/// * Can hide/show regions.
/// * Resize
///     * neighbours only
///     * all regions
/// * Horizontal / vertical split. Choose one.
///
/// The widget doesn't hold references to the content widgets,
/// instead it gives back the regions where the content can be
/// rendered.
///
/// 1. Construct the Split.
/// 2. Call [Split::into_widgets] to create the actual
///    widget and the layout of the regions.
/// 3. Render the content areas.
/// 4. Render the split widget last. There are options that
///    will render above the widgets and use part of the content
///    area.
///
pub struct Split<'a> {
    // direction
    direction: Direction,
    // start constraints. used when
    // there are no widths in the state.
    constraints: Vec<Constraint>,
    // resize constraints for each area.
    resize_constraints: Vec<ResizeConstraint>,
    // resize options
    resize: SplitResize,

    // split rendering
    split_type: SplitType,
    // joiner left/top
    join_0: Option<BorderType>,
    // joiner right/bottom
    join_1: Option<BorderType>,
    // offset from left/top for the split-mar-k
    mark_offset: u16,
    // mar-k char 1
    mark_0_char: Option<&'a str>,
    // mar-k char 2
    mark_1_char: Option<&'a str>,

    // styling
    style: Style,
    block: Option<Block<'a>>,
    arrow_style: Option<Style>,
    drag_style: Option<Style>,
}

/// Widget for the Layout of the split.
#[derive(Debug, Clone)]
pub struct LayoutWidget<'a> {
    split: Rc<Split<'a>>,
}

/// Primary widget for rendering the Split.
#[derive(Debug, Clone)]
pub struct SplitWidget<'a> {
    split: Rc<Split<'a>>,
}

///
/// Combined styles for the Split.
///
#[derive(Debug, Clone)]
pub struct SplitStyle {
    /// Base style
    pub style: Style,
    /// Block
    pub block: Option<Block<'static>>,
    pub border_style: Option<Style>,
    pub title_style: Option<Style>,
    /// Arrow style.
    pub arrow_style: Option<Style>,
    /// Style while dragging.
    pub drag_style: Option<Style>,

    /// Marker for a horizontal split.
    /// Only the first 2 chars are used.
    pub horizontal_mark: Option<&'static str>,
    /// Marker for a vertical split.
    /// Only the first 2 chars are used.
    pub vertical_mark: Option<&'static str>,

    pub non_exhaustive: NonExhaustive,
}

/// Render variants for the splitter.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub enum SplitType {
    /// Render a full splitter between the widgets. Reduces the area for
    /// each widget. Renders a blank border.
    #[default]
    FullEmpty,
    /// Render a full splitter between the widgets. Reduces the area for
    /// each widget. Renders a plain line border.
    FullPlain,
    /// Render a full splitter between the widgets. Reduces the area for
    /// each widget. Renders a double line border.
    FullDouble,
    /// Render a full splitter between the widgets. Reduces the area for
    /// each widget. Renders a thick line border.
    FullThick,
    /// Render a full splitter between the widgets. Reduces the area for
    /// each widget. Renders a border with a single line on the inside
    /// of a half block.
    FullQuadrantInside,
    /// Render a full splitter between the widgets. Reduces the area for
    /// each widget. Renders a border with a single line on the outside
    /// of a half block.
    FullQuadrantOutside,
    /// Render a minimal splitter, consisting just the two marker chars
    /// rendered over the left/top widget.
    ///
    /// If the left widget has a Scroll in that area this will integrate
    /// nicely. You will have to set `start_margin` with Scroll, then
    /// Scroll can adjust its rendering to leave space for the markers.
    /// And you want to set a `mark_offset` here.
    ///
    /// The widget will get the full area, only the marker is used
    /// for mouse interactions.
    Scroll,
    /// Don't render a splitter, fully manual mode.
    ///
    /// The widget will have the full area, but the event-handling will
    /// use the last column/row of the widget for moving the split.
    /// This can be adjusted if you change `state.split[n]` which provides
    /// the active area.
    Widget,
}

/// Strategy for resizing the split-areas.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum SplitResize {
    /// When changing a split-position limit resizing to the two
    /// adjacent neighbours of the split.
    Neighbours,
    /// When changing a split-position, allow all positions in the
    /// widgets area. Minus the minimum space required to draw the
    /// split itself.
    #[default]
    Full,
}

/// How will one split area be resized when resizing the whole split-widget.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ResizeConstraint {
    /// The length of the split-area will stay fixed, if possible.
    Fixed,
    /// The length of the split-area will scale with the widget.
    /// Each area will get a proportional part according to its current length.
    #[default]
    ScaleProportional,
    /// The length of the split-area will scale with the widget.
    /// Each area will get the same proportion of the change.
    ///
    /// If you mix this with ScaleProportional this will not work,
    /// because I don't know what you would expect to happen.
    ScaleEqual,
}

const SPLIT_WIDTH: u16 = 1;

/// State & event handling.
#[derive(Debug)]
pub struct SplitState {
    /// Total area.
    /// __readonly__. renewed for each render.
    pub area: Rect,
    /// Area inside the border.
    /// __readonly__. renewed for each render.
    pub inner: Rect,
    /// The widget areas.
    /// Use this after calling layout() to render your widgets.
    /// __readonly__ renewed for each render.
    pub widget_areas: Vec<Rect>,
    /// Area used by the splitter. This is area is used for moving the splitter.
    /// It might overlap with the widget area.
    /// __readonly__ renewed for each render.
    pub splitline_areas: Vec<Rect>,
    /// Start position for drawing the mar-k.
    /// __readonly__ renewed for each render.
    pub splitline_mark_position: Vec<Position>,
    /// Offset of the mar-k from top/left.
    /// __readonly__ renewed for each render.
    pub mark_offset: u16,

    /// Direction of the split.
    /// __readonly__ renewed for each render.
    pub direction: Direction,
    /// __readonly__ renewed for each render.
    pub split_type: SplitType,
    /// __readonly__ renewed for each render.
    pub resize: SplitResize,

    /// Layout-widths for the split-areas.
    ///
    /// This information is used after the initial render to
    /// lay out the splitter.
    area_length: Vec<u16>,
    area_constraint: Vec<Constraint>,
    /// Saved lengths for hidden splits.
    hidden_length: Vec<u16>,

    /// Focus.
    /// __read+write__
    pub focus: FocusFlag,
    /// If the splitter has the focus you can navigate between
    /// the split-markers. This is the currently active split-marker.
    /// __read+write__
    pub focus_marker: Option<usize>,

    /// Mouseflags.
    /// __read+write__
    pub mouse: MouseFlagsN,

    /// Rendering is split into base-widget and menu-popup.
    /// Relocate after rendering the popup.
    relocate_split: bool,

    pub non_exhaustive: NonExhaustive,
}

impl SplitType {
    pub fn is_full(&self) -> bool {
        use SplitType::*;
        match self {
            FullEmpty => true,
            FullPlain => true,
            FullDouble => true,
            FullThick => true,
            FullQuadrantInside => true,
            FullQuadrantOutside => true,
            Scroll => false,
            Widget => false,
        }
    }
}

impl Default for SplitStyle {
    fn default() -> Self {
        Self {
            style: Default::default(),
            block: Default::default(),
            border_style: Default::default(),
            title_style: Default::default(),
            arrow_style: Default::default(),
            drag_style: Default::default(),
            horizontal_mark: Default::default(),
            vertical_mark: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl<'a> Split<'a> {
    /// Create a new split.
    ///
    /// To have any split-areas you must set a list of [constraints]
    /// for both the number and initial sizes of the areas.
    pub fn new() -> Self {
        Self {
            direction: Direction::Horizontal,
            ..Default::default()
        }
    }

    /// Horizontal split.
    pub fn horizontal() -> Self {
        Self {
            direction: Direction::Horizontal,
            ..Default::default()
        }
    }

    /// Vertical split
    pub fn vertical() -> Self {
        Self {
            direction: Direction::Horizontal,
            ..Default::default()
        }
    }

    /// Set constraints for the initial area sizes.
    /// If the window is resized the current widths are used as
    /// constraints for recalculating.
    ///
    /// The number of constraints determines the number of areas.
    pub fn constraints(mut self, constraints: impl IntoIterator<Item = Constraint>) -> Self {
        self.constraints = constraints.into_iter().collect();
        self.resize_constraints = iter::from_fn(|| Some(ResizeConstraint::ScaleProportional))
            .take(self.constraints.len())
            .collect();
        self
    }

    /// Set the behaviour for each area when resizing the split-widget itself.
    pub fn resize_constraint(mut self, n: usize, constraint: ResizeConstraint) -> Self {
        self.resize_constraints[n] = constraint;
        self
    }

    /// Layout direction of the widgets.
    /// Direction::Horizontal means the widgets are laid out left to right,
    /// with a vertical split area in between.
    pub fn direction(mut self, direction: Direction) -> Self {
        self.direction = direction;
        self
    }

    /// Controls rendering of the splitter.
    pub fn split_type(mut self, split_type: SplitType) -> Self {
        self.split_type = split_type;
        self
    }

    /// Controls resizing the split areas.
    pub fn resize(mut self, resize: SplitResize) -> Self {
        self.resize = resize;
        self
    }

    /// Draw a join character between the split and the
    /// borders. This sets the border type used for the
    /// surrounding border.
    pub fn join(mut self, border: BorderType) -> Self {
        self.join_0 = Some(border);
        self.join_1 = Some(border);
        self
    }

    /// Draw a join character between the split and the
    /// border on the left/top side. This sets the border type
    /// used for the left/top border.
    pub fn join_0(mut self, border: BorderType) -> Self {
        self.join_0 = Some(border);
        self
    }

    /// Draw a join character between the split and the
    /// border on the right/bottom side. This sets the border type
    /// used for the right/bottom border.
    pub fn join_1(mut self, border: BorderType) -> Self {
        self.join_1 = Some(border);
        self
    }

    /// Outer block.
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    /// Set all styles.
    pub fn styles(mut self, styles: SplitStyle) -> Self {
        self.style = styles.style;
        if styles.block.is_some() {
            self.block = styles.block;
        }
        if let Some(border_style) = styles.border_style {
            self.block = self.block.map(|v| v.border_style(border_style));
        }
        if let Some(title_style) = styles.title_style {
            self.block = self.block.map(|v| v.title_style(title_style));
        }
        self.block = self.block.map(|v| v.style(self.style));

        if styles.drag_style.is_some() {
            self.drag_style = styles.drag_style;
        }
        if styles.arrow_style.is_some() {
            self.arrow_style = styles.arrow_style;
        }
        match self.direction {
            Direction::Horizontal => {
                if let Some(mark) = styles.horizontal_mark {
                    let mut g = mark.graphemes(true);
                    if let Some(g0) = g.next() {
                        self.mark_0_char = Some(g0);
                    }
                    if let Some(g1) = g.next() {
                        self.mark_1_char = Some(g1);
                    }
                }
            }
            Direction::Vertical => {
                if let Some(mark) = styles.vertical_mark {
                    let mut g = mark.graphemes(true);
                    if let Some(g0) = g.next() {
                        self.mark_0_char = Some(g0);
                    }
                    if let Some(g1) = g.next() {
                        self.mark_1_char = Some(g1);
                    }
                }
            }
        }
        self
    }

    /// Style for the split area.
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self.block = self.block.map(|v| v.style(style));
        self
    }

    /// Style for the arrows.
    pub fn arrow_style(mut self, style: Style) -> Self {
        self.arrow_style = Some(style);
        self
    }

    /// Style while dragging the splitter.
    pub fn drag_style(mut self, style: Style) -> Self {
        self.drag_style = Some(style);
        self
    }

    /// Offset for the split marker from the top/left.
    pub fn mark_offset(mut self, offset: u16) -> Self {
        self.mark_offset = offset;
        self
    }

    /// First marker char for the splitter.
    pub fn mark_0(mut self, mark: &'a str) -> Self {
        self.mark_0_char = Some(mark);
        self
    }

    /// Second marker char for the splitter.
    pub fn mark_1(mut self, mark: &'a str) -> Self {
        self.mark_1_char = Some(mark);
        self
    }

    /// Constructs the widget for rendering.
    ///
    /// Returns the SplitWidget that actually renders the split decorations.
    ///
    /// Use [SplitState::widget_areas] to render your contents, and
    /// then render the SplitWidget. This allows it to render some
    /// decorations on top of your widgets.
    #[deprecated(since = "2.4.0", note = "use into_widgets() instead")]
    pub fn into_widget(self, area: Rect, state: &mut SplitState) -> SplitWidget<'a> {
        layout_split(&self, area, state);
        SplitWidget {
            split: Rc::new(self),
        }
    }

    /// Constructs the widgets for rendering.
    ///
    /// Returns the SplitWidget that actually renders the split.
    /// Returns a `Vec<Rect>` with the regions for each split.
    ///
    /// Render your content first, using the layout information.
    /// And the SplitWidget as last to allow rendering over
    /// the content widgets.
    #[deprecated(since = "2.4.0", note = "use into_widgets() instead")]
    pub fn into_widget_layout(
        self,
        area: Rect,
        state: &mut SplitState,
    ) -> (SplitWidget<'a>, Vec<Rect>) {
        layout_split(&self, area, state);
        (
            SplitWidget {
                split: Rc::new(self),
            },
            state.widget_areas.clone(),
        )
    }

    /// Constructs the widgets for rendering.
    ///
    /// Returns the LayoutWidget that must run first. It
    /// doesn't actually render anything, it just calculates
    /// the layout for the split regions.
    ///
    /// Use the layout in [SplitState::widget_areas] to render
    /// your widgets.
    ///
    /// The SplitWidget actually renders the split itself.
    /// Render it after you finished with the content.
    pub fn into_widgets(self) -> (LayoutWidget<'a>, SplitWidget<'a>) {
        let split = Rc::new(self);
        (
            LayoutWidget {
                split: split.clone(), //
            },
            SplitWidget {
                split, //
            },
        )
    }
}

impl<'a> StatefulWidget for &Split<'a> {
    type State = SplitState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        layout_split(self, area, state);
        render_split(self, buf, state);
        state.relocate_split = false;
    }
}

impl<'a> StatefulWidget for Split<'a> {
    type State = SplitState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        layout_split(&self, area, state);
        render_split(&self, buf, state);
        state.relocate_split = false;
    }
}

impl<'a> StatefulWidget for &LayoutWidget<'a> {
    type State = SplitState;

    fn render(self, area: Rect, _buf: &mut Buffer, state: &mut Self::State) {
        // just run the layout here. SplitWidget renders the rest.
        layout_split(&self.split, area, state);
    }
}

impl<'a> StatefulWidget for LayoutWidget<'a> {
    type State = SplitState;

    fn render(self, area: Rect, _buf: &mut Buffer, state: &mut Self::State) {
        // just run the layout here. SplitWidget renders the rest.
        layout_split(&self.split, area, state);
    }
}

impl<'a> StatefulWidget for &SplitWidget<'a> {
    type State = SplitState;

    fn render(self, _area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_split(&self.split, buf, state);
    }
}

impl StatefulWidget for SplitWidget<'_> {
    type State = SplitState;

    fn render(self, _area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_split(&self.split, buf, state);
    }
}

fn render_split(split: &Split<'_>, buf: &mut Buffer, state: &mut SplitState) {
    let area = state.area;
    if state.is_focused() {
        if state.focus_marker.is_none() {
            state.focus_marker = Some(0);
        }
    } else {
        state.focus_marker = None;
    }

    split.block.clone().render(area, buf);

    for (n, split_area) in state.splitline_areas.iter().enumerate() {
        // skip 0 width/height
        if split.direction == Direction::Horizontal {
            if split_area.width == 0 {
                continue;
            }
        } else {
            if split_area.height == 0 {
                continue;
            }
        }

        let (style, arrow_style) = if Some(n) == state.mouse.drag.get()
            || Some(n) == state.focus_marker
            || Some(n) == state.mouse.hover.get()
        {
            if let Some(drag) = split.drag_style {
                (drag, drag)
            } else {
                (revert_style(split.style), revert_style(split.style))
            }
        } else {
            if let Some(arrow) = split.arrow_style {
                (split.style, arrow)
            } else {
                (split.style, split.style)
            }
        };

        if let Some(fill) = get_fill_char(split) {
            fill_buf_area(buf, *split_area, fill, style);
        }

        let mark = state.splitline_mark_position[n];
        if split.direction == Direction::Horizontal {
            if buf.area.contains((mark.x, mark.y).into()) {
                if let Some(cell) = buf.cell_mut((mark.x, mark.y)) {
                    cell.set_style(arrow_style);
                    cell.set_symbol(get_mark_0(split));
                }
            }
            if buf.area.contains((mark.x, mark.y + 1).into()) {
                if let Some(cell) = buf.cell_mut((mark.x, mark.y + 1)) {
                    cell.set_style(arrow_style);
                    cell.set_symbol(get_mark_1(split));
                }
            }
        } else {
            if let Some(cell) = buf.cell_mut((mark.x, mark.y)) {
                cell.set_style(arrow_style);
                cell.set_symbol(get_mark_0(split));
            }
            if let Some(cell) = buf.cell_mut((mark.x + 1, mark.y)) {
                cell.set_style(arrow_style);
                cell.set_symbol(get_mark_1(split));
            }
        }

        if let Some((pos_0, c_0)) = get_join_0(split, *split_area, state) {
            if let Some(cell) = buf.cell_mut((pos_0.x, pos_0.y)) {
                cell.set_symbol(c_0);
            }
        }
        if let Some((pos_1, c_1)) = get_join_1(split, *split_area, state) {
            if let Some(cell) = buf.cell_mut((pos_1.x, pos_1.y)) {
                cell.set_symbol(c_1);
            }
        }
    }
}

impl Default for SplitState {
    fn default() -> Self {
        Self {
            area: Default::default(),
            inner: Default::default(),
            widget_areas: Default::default(),
            splitline_areas: Default::default(),
            splitline_mark_position: Default::default(),
            mark_offset: Default::default(),
            direction: Default::default(),
            split_type: Default::default(),
            resize: Default::default(),
            area_length: Default::default(),
            area_constraint: Default::default(),
            hidden_length: Default::default(),
            focus: Default::default(),
            focus_marker: Default::default(),
            mouse: Default::default(),
            relocate_split: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl Clone for SplitState {
    fn clone(&self) -> Self {
        Self {
            area: self.area,
            inner: self.inner,
            widget_areas: self.widget_areas.clone(),
            splitline_areas: self.splitline_areas.clone(),
            splitline_mark_position: self.splitline_mark_position.clone(),
            mark_offset: self.mark_offset,
            direction: self.direction,
            split_type: self.split_type,
            resize: self.resize,
            area_length: self.area_length.clone(),
            area_constraint: self.area_constraint.clone(),
            hidden_length: self.hidden_length.clone(),
            focus: self.focus.new_instance(),
            focus_marker: self.focus_marker,
            mouse: Default::default(),
            relocate_split: self.relocate_split,
            non_exhaustive: NonExhaustive,
        }
    }
}

impl HasFocus for SplitState {
    fn build(&self, builder: &mut FocusBuilder) {
        builder.leaf_widget(self);
    }

    fn focus(&self) -> FocusFlag {
        self.focus.clone()
    }

    fn area(&self) -> Rect {
        // not mouse focusable
        Rect::default()
    }

    fn navigable(&self) -> Navigation {
        Navigation::Leave
    }
}

impl RelocatableState for SplitState {
    fn relocate(&mut self, shift: (i16, i16), clip: Rect) {
        // relocate after the popup/split itself is rendered.
        if !self.relocate_split {
            self.area = relocate_area(self.area, shift, clip);
            self.inner = relocate_area(self.inner, shift, clip);
            relocate_areas(self.widget_areas.as_mut_slice(), shift, clip);
            relocate_areas(self.splitline_areas.as_mut_slice(), shift, clip);
            relocate_positions(self.splitline_mark_position.as_mut_slice(), shift, clip);
        }
    }

    fn relocate_popup(&mut self, shift: (i16, i16), clip: Rect) {
        if self.relocate_split {
            self.relocate_split = false;
            self.area = relocate_area(self.area, shift, clip);
            self.inner = relocate_area(self.inner, shift, clip);
            relocate_areas(self.widget_areas.as_mut_slice(), shift, clip);
            relocate_areas(self.splitline_areas.as_mut_slice(), shift, clip);
            relocate_positions(self.splitline_mark_position.as_mut_slice(), shift, clip);
        }
    }
}

#[allow(clippy::len_without_is_empty)]
impl SplitState {
    /// New state.
    pub fn new() -> Self {
        Self::default()
    }

    /// New state with a focus-name.
    pub fn named(name: &str) -> Self {
        let mut z = Self::default();
        z.focus = z.focus.with_name(name);
        z
    }

    /// Set the position for the nth splitter.
    ///
    /// The position is limited the combined area of the two adjacent areas.
    /// The position is further limited to leave space for rendering the
    /// splitter.
    ///
    pub fn set_screen_split_pos(&mut self, n: usize, pos: (u16, u16)) -> bool {
        if self.is_hidden(n) {
            return false;
        }
        if self.direction == Direction::Horizontal {
            let pos = if pos.0 < self.inner.left() {
                0
            } else if pos.0 < self.inner.right() {
                pos.0 - self.inner.x
            } else {
                self.inner.width
            };

            let split_pos = self.split_pos(n);
            self.set_split_pos(n, pos);

            split_pos != self.split_pos(n)
        } else {
            let pos = if pos.1 < self.inner.top() {
                0
            } else if pos.1 < self.inner.bottom() {
                pos.1 - self.inner.y
            } else {
                self.inner.height
            };

            let split_pos = self.split_pos(n);
            self.set_split_pos(n, pos);

            split_pos != self.split_pos(n)
        }
    }

    /// Move the nth split position.
    /// If delta is greater than the area length it sets the
    /// length to 0.
    pub fn move_split_left(&mut self, n: usize, delta: u16) -> bool {
        let split_pos = self.split_pos(n);
        self.set_split_pos(n, split_pos - delta);

        split_pos != self.split_pos(n)
    }

    /// Move the nth split position.
    /// Does nothing if the change is bigger than the length of the split.
    pub fn move_split_right(&mut self, n: usize, delta: u16) -> bool {
        let split_pos = self.split_pos(n);
        self.set_split_pos(n, split_pos + delta);

        split_pos != self.split_pos(n)
    }

    /// Move the nth split position.
    /// Does nothing if the change is bigger than the length of the split.
    pub fn move_split_up(&mut self, n: usize, delta: u16) -> bool {
        self.move_split_left(n, delta)
    }

    /// Move the nth split position.
    /// Does nothing if the change is bigger than the length of the split.
    pub fn move_split_down(&mut self, n: usize, delta: u16) -> bool {
        self.move_split_right(n, delta)
    }

    /// Select the next splitter for manual adjustment.
    pub fn select_next_split(&mut self) -> bool {
        if self.is_focused() {
            let n = self.focus_marker.unwrap_or_default();
            if n + 1 >= self.area_length.len().saturating_sub(1) {
                self.focus_marker = Some(0);
            } else {
                self.focus_marker = Some(n + 1);
            }
            true
        } else {
            false
        }
    }

    /// Select the previous splitter for manual adjustment.
    pub fn select_prev_split(&mut self) -> bool {
        if self.is_focused() {
            let n = self.focus_marker.unwrap_or_default();
            if n == 0 {
                self.focus_marker =
                    Some(self.area_length.len().saturating_sub(1).saturating_sub(1));
            } else {
                self.focus_marker = Some(n - 1);
            }
            true
        } else {
            false
        }
    }

    /// Number of split-areas
    pub fn len(&self) -> usize {
        self.area_length.len()
    }

    /// Get all area lengths.
    pub fn area_lengths(&self) -> &[u16] {
        &self.area_length
    }

    /// Set all area lengths.
    ///
    /// This will adjust the list of the hidden splits too.
    ///
    /// __Caution__
    /// If the sum of the lengths doesn't match the display-width
    /// this will trigger a layout and will use the given lenghts
    /// as Constraint::Fill().
    ///
    /// __Caution__
    ///
    /// If a length is 0 it will not display the split at all.
    pub fn set_area_lengths(&mut self, lengths: Vec<u16>) {
        self.area_length = lengths;
        self.area_constraint.clear();
        while self.hidden_length.len() < self.area_length.len() {
            self.hidden_length.push(0);
        }
        while self.hidden_length.len() > self.area_length.len() {
            self.hidden_length.pop();
        }
    }

    /// Get the value of the hidden lengths.
    pub fn hidden_lengths(&self) -> &[u16] {
        &self.hidden_length
    }

    /// Set the value of the hidden lengths.
    ///
    /// This will take at most area_length.len() items of this Vec.
    /// And it will fill missing items as 0.
    pub fn set_hidden_lengths(&mut self, hidden: Vec<u16>) {
        for i in 0..self.hidden_length.len() {
            if let Some(v) = hidden.get(i) {
                self.hidden_length[i] = *v;
            } else {
                self.hidden_length[i] = 0;
            }
        }
    }

    /// Length of the nth split.
    ///
    /// __Caution__
    ///
    /// This length **includes** the width of the split itself.
    /// Which may or may not take some space. Except for the last.
    /// So it will be better to use `widget_areas` for anything
    /// rendering related.
    ///
    pub fn area_len(&self, n: usize) -> u16 {
        if n >= self.area_length.len() {
            return 0;
        }
        self.area_length[n]
    }

    /// Sum of all area lengths.
    pub fn total_area_len(&self) -> u16 {
        self.area_length.iter().sum()
    }

    /// Set the length of the nth split.
    ///
    /// This resets any hidden state of the nth split.
    ///
    /// __Caution__
    /// The sum of all lengths must be equal with the width/height of
    /// the splitter. If it is not this operation doesn't set the
    /// absolute width of the nth split. Instead, it triggers a layout
    /// of the widget, takes all the lengths as Constraint::Fill()
    /// values and redistributes the size.
    ///
    /// You can either ensure to change some other len to accommodate
    /// for your changes. Or use [set_split_pos](Self::set_split_pos) or
    /// [set_screen_split_pos](Self::set_screen_split_pos)
    ///
    /// __Caution__
    ///
    /// This length **includes** the width of the split itself.
    /// Which may or may not take some space. Except for the last area.
    /// Which doesn't have a split.
    ///
    /// So:
    /// - If you set the length to 0 the area will be hidden completely
    ///   and no split will be shown.
    /// - A value of 1 is fine.
    /// - The last area can have a length 0 and that's fine too.
    ///
    /// __Caution__
    ///
    /// Before the first render this will do nothing.
    /// Use [set_area_lengths](SplitState::set_area_lengths) to initialize the areas.
    ///
    pub fn set_area_len(&mut self, n: usize, len: u16) {
        if n >= self.area_length.len() {
            return;
        }
        self.area_length[n] = len;
        self.area_constraint.clear();
        self.hidden_length[n] = 0;
    }

    /// Returns the position of the nth split.
    ///
    /// __Caution__
    ///
    /// The numbering for the splitters goes from `0` to `len-1` __exclusive__.
    /// Split `n` marks the gap between area `n` and `n+1`.
    ///
    /// __Caution__
    ///
    /// This returns the position of the gap between two adjacent
    /// split-areas. Use `splitline_areas` for anything rendering related.
    pub fn split_pos(&self, n: usize) -> u16 {
        if n + 1 >= self.area_length.len() {
            return self.area_length.iter().sum();
        }
        self.area_length[..n + 1].iter().sum()
    }

    /// Sets the position of the nth split.
    ///
    /// Depending on the resize strategy this can limit the allowed positions
    /// for the split.
    ///
    /// __Caution__
    ///
    /// The numbering for the splitters goes from `0` to `len-1` __exclusive__.
    /// Split `n` marks the gap between area `n` and `n+1`.
    ///
    /// __Caution__
    ///
    /// This marks the position of the gap between two adjacent
    /// split-areas. If you start from screen-coordinates it might
    /// be easier to use [set_screen_split_pos](Self::set_screen_split_pos)
    pub fn set_split_pos(&mut self, n: usize, pos: u16) {
        if n + 1 >= self.area_length.len() {
            return;
        }

        match self.resize {
            SplitResize::Neighbours => {
                self.set_split_pos_neighbour(n, pos);
            }
            SplitResize::Full => {
                self.set_split_pos_full(n, pos);
            }
        }
    }

    /// Limits the possible position of the split to the
    /// width of the two direct neighbours of the split.
    fn set_split_pos_neighbour(&mut self, n: usize, pos: u16) {
        assert!(n + 1 < self.area_length.len());

        // create dual
        let mut pos_vec = Vec::new();
        let mut pp = 0;
        for len in &self.area_length {
            pp += *len;
            pos_vec.push(pp);
        }
        // last is not a split
        let pos_count = pos_vec.len();

        let (min_pos, max_pos) = if n == 0 {
            if n + 2 >= pos_count {
                (SPLIT_WIDTH, pos_vec[n + 1])
            } else {
                (SPLIT_WIDTH, pos_vec[n + 1] - SPLIT_WIDTH)
            }
        } else if n + 2 < pos_count {
            (pos_vec[n - 1] + 1, pos_vec[n + 1] - SPLIT_WIDTH)
        } else {
            (pos_vec[n - 1] + 1, pos_vec[n + 1])
        };

        pos_vec[n] = min(max(min_pos, pos), max_pos);

        // revert dual
        for i in 0..pos_vec.len() {
            if i > 0 {
                self.area_length[i] = pos_vec[i] - pos_vec[i - 1];
            } else {
                self.area_length[i] = pos_vec[i];
            }
        }
        self.area_constraint.clear();
    }

    /// Allows the full range for the split-pos.
    /// Minus the space needed to render the split itself.
    #[allow(clippy::needless_range_loop)]
    #[allow(clippy::comparison_chain)]
    fn set_split_pos_full(&mut self, n: usize, pos: u16) {
        assert!(n + 1 < self.area_length.len());

        let total_len = self.total_area_len();

        // create dual
        let mut pos_vec = Vec::new();
        let mut pp = 0;
        for len in &self.area_length {
            pp += *len;
            pos_vec.push(pp);
        }
        // last is not a split
        pos_vec.pop();
        let pos_count = pos_vec.len();

        let mut min_pos = SPLIT_WIDTH;
        for i in 0..pos_vec.len() {
            if i < n {
                if self.area_length[i] == 0 {
                    pos_vec[i] = min_pos;
                } else if self.hidden_length[i] != 0 {
                    pos_vec[i] = min_pos;
                    min_pos += SPLIT_WIDTH;
                } else {
                    if pos_vec[i] >= pos {
                        // how many split between here and there
                        let rest_area_count = n - (i + 1);
                        let rest_area_width = rest_area_count as u16 * SPLIT_WIDTH;
                        // min
                        pos_vec[i] = max(
                            min_pos,
                            pos.saturating_sub(SPLIT_WIDTH)
                                .saturating_sub(rest_area_width),
                        );
                        min_pos += SPLIT_WIDTH;
                    } else {
                        // unchanged
                    }
                }
            } else if i == n {
                // remaining area count with a split
                let rest_area_count = pos_count - (i + 1);
                let rest_area_width = rest_area_count as u16 * SPLIT_WIDTH;
                let rest_len = total_len - (min_pos + 1);
                // min for remaining areas
                let rest_len = rest_len - rest_area_width;
                // last can be 0
                let rest_len = rest_len + SPLIT_WIDTH;

                let max_pos = min_pos + rest_len;

                pos_vec[i] = min(max(min_pos, pos), max_pos);

                min_pos = pos_vec[i] + SPLIT_WIDTH;
            } else {
                if self.area_length[i] == 0 {
                    pos_vec[i] = min_pos;
                } else if self.hidden_length[i] != 0 {
                    pos_vec[i] = min_pos;
                    min_pos += SPLIT_WIDTH;
                } else {
                    if pos_vec[i] <= pos {
                        pos_vec[i] = min_pos;
                        min_pos += SPLIT_WIDTH;
                    } else {
                        // unchanged
                    }
                }
            }
        }

        // revert dual
        for i in 0..pos_vec.len() {
            if i > 0 {
                self.area_length[i] = pos_vec[i] - pos_vec[i - 1];
            } else {
                self.area_length[i] = pos_vec[i];
            }
        }
        self.area_length[pos_count] = total_len - pos_vec[pos_count - 1];
        self.area_constraint.clear();
    }

    /// Is the split hidden?
    pub fn is_hidden(&self, n: usize) -> bool {
        self.hidden_length[n] > 0
    }

    /// Hide the split and adds its area to the following split.
    /// If there is no following split it will go left/up.
    /// Leaves enough space to render the splitter.
    pub fn hide_split(&mut self, n: usize) -> bool {
        if self.hidden_length[n] == 0 {
            self.area_constraint.clear();

            let mut hide = if n + 1 == self.area_length.len() {
                self.area_length[n]
            } else {
                self.area_length[n].saturating_sub(SPLIT_WIDTH)
            };
            for idx in n + 1..self.area_length.len() {
                if self.hidden_length[idx] == 0 {
                    self.area_length[idx] += hide;
                    hide = 0;
                    break;
                }
            }
            if hide > 0 {
                for idx in (0..n).rev() {
                    if self.hidden_length[idx] == 0 {
                        self.area_length[idx] += hide;
                        hide = 0;
                        break;
                    }
                }
            }

            if hide > 0 {
                // don't hide last split.
                self.hidden_length[n] = 0;
                false
            } else {
                if n + 1 == self.area_length.len() {
                    self.hidden_length[n] = self.area_length[n];
                    self.area_length[n] = 0;
                } else {
                    self.hidden_length[n] = self.area_length[n].saturating_sub(SPLIT_WIDTH);
                    self.area_length[n] = 1;
                };
                true
            }
        } else {
            false
        }
    }

    /// Show a hidden split.
    /// It will first try to reduce the areas to the right,
    /// and then the areas to the left to make space.
    pub fn show_split(&mut self, n: usize) -> bool {
        let mut show = self.hidden_length[n];
        if show > 0 {
            for idx in n + 1..self.area_length.len() {
                if self.hidden_length[idx] == 0 {
                    // steal as much as we can
                    if self.area_length[idx] > show + SPLIT_WIDTH {
                        self.area_length[idx] -= show;
                        show = 0;
                    } else if self.area_length[idx] > SPLIT_WIDTH {
                        show -= self.area_length[idx] - SPLIT_WIDTH;
                        self.area_length[idx] = SPLIT_WIDTH;
                    }
                    if show == 0 {
                        break;
                    }
                }
            }
            if show > 0 {
                for idx in (0..n).rev() {
                    if self.hidden_length[idx] == 0 {
                        if self.area_length[idx] > show + SPLIT_WIDTH {
                            self.area_length[idx] -= show;
                            show = 0;
                        } else if self.area_length[idx] > SPLIT_WIDTH {
                            show -= self.area_length[idx] - SPLIT_WIDTH;
                            self.area_length[idx] = SPLIT_WIDTH;
                        }
                        if show == 0 {
                            break;
                        }
                    }
                }
            }

            self.area_length[n] += self.hidden_length[n] - show;
            self.hidden_length[n] = 0;
            self.area_constraint.clear();
            true
        } else {
            false
        }
    }
}

impl HandleEvent<Event, Regular, Outcome> for SplitState {
    fn handle(&mut self, event: &Event, _qualifier: Regular) -> Outcome {
        event_flow!(
            return if self.is_focused() {
                if let Some(n) = self.focus_marker {
                    match event {
                        ct_event!(keycode press Left) => self.select_prev_split().into(),
                        ct_event!(keycode press Right) => self.select_next_split().into(),
                        ct_event!(keycode press Up) => self.select_prev_split().into(),
                        ct_event!(keycode press Down) => self.select_next_split().into(),

                        ct_event!(keycode press CONTROL-Left) => self.move_split_left(n, 1).into(),
                        ct_event!(keycode press CONTROL-Right) => {
                            self.move_split_right(n, 1).into()
                        }
                        ct_event!(keycode press CONTROL-Up) => self.move_split_up(n, 1).into(),
                        ct_event!(keycode press CONTROL-Down) => self.move_split_down(n, 1).into(),
                        _ => Outcome::Continue,
                    }
                } else {
                    Outcome::Continue
                }
            } else {
                Outcome::Continue
            }
        );

        self.handle(event, MouseOnly)
    }
}

impl HandleEvent<Event, MouseOnly, Outcome> for SplitState {
    fn handle(&mut self, event: &Event, _qualifier: MouseOnly) -> Outcome {
        match event {
            ct_event!(mouse any for m) if self.mouse.hover(&self.splitline_areas, m) => {
                Outcome::Changed
            }
            ct_event!(mouse any for m) => {
                let was_drag = self.mouse.drag.get();
                if self.mouse.drag(&self.splitline_areas, m) {
                    if let Some(n) = self.mouse.drag.get() {
                        self.set_screen_split_pos(n, self.mouse.pos_of(m)).into()
                    } else {
                        Outcome::Continue
                    }
                } else {
                    // repaint after drag is finished. resets the displayed style.
                    if was_drag.is_some() {
                        Outcome::Changed
                    } else {
                        Outcome::Continue
                    }
                }
            }
            _ => Outcome::Continue,
        }
    }
}

/// Handle all events.
/// Text events are only processed if focus is true.
/// Mouse events are processed if they are in range.
pub fn handle_events(state: &mut SplitState, focus: bool, event: &Event) -> Outcome {
    state.focus.set(focus);
    HandleEvent::handle(state, event, Regular)
}

/// Handle only mouse-events.
pub fn handle_mouse_events(state: &mut SplitState, event: &Event) -> Outcome {
    HandleEvent::handle(state, event, MouseOnly)
}