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
///
/// Add scrolling behaviour to a widget.
///
/// [Scrolled] acts as a wrapper around a widget that implements [ScrollingWidget].
/// There is a second trait [ScrollingState] necessary for the state.
///
use crate::_private::NonExhaustive;
use crate::event::Outcome;
use crate::event::{FocusKeys, HandleEvent, MouseOnly};
use crate::view::View;
use crate::viewport::Viewport;
use crate::{ScrollingState, ScrollingWidget};
use crossterm::event::{MouseEvent, MouseEventKind};
use rat_event::{ct_event, UsedEvent};
use ratatui::buffer::Buffer;
use ratatui::layout::{Position, Rect, Size};
use ratatui::prelude::{BlockExt, Style};
use ratatui::symbols::scrollbar::Set;
use ratatui::widgets::{
    Block, Scrollbar, ScrollbarOrientation, ScrollbarState, StatefulWidget, StatefulWidgetRef,
    Widget, WidgetRef,
};
use std::cmp::min;
use std::mem;

/// A wrapper widget that scrolls it's content.
#[derive(Debug, Default, Clone)]
pub struct Scrolled<'a, T> {
    /// widget
    widget: T,

    h_overscroll: usize,
    v_overscroll: usize,
    h_scroll_policy: ScrollbarPolicy,
    v_scroll_policy: ScrollbarPolicy,
    h_scroll_position: HScrollPosition,
    v_scroll_position: VScrollPosition,

    block: Option<Block<'a>>,

    thumb_symbol: Option<&'a str>,
    thumb_style: Option<Style>,
    track_symbol: Option<&'a str>,
    track_style: Option<Style>,
    begin_symbol: Option<&'a str>,
    begin_style: Option<Style>,
    end_symbol: Option<&'a str>,
    end_style: Option<Style>,
}

/// Scrolled state.
#[derive(Debug, Clone)]
pub struct ScrolledState<WidgetState> {
    /// State of the scrolled widget.
    pub widget: WidgetState,

    /// Total screen area.
    pub area: Rect,
    /// View area.
    pub view_area: Rect,
    /// Scrollbar area.
    pub h_scrollbar_area: Option<Rect>,
    /// Scrollbar area.
    pub v_scrollbar_area: Option<Rect>,

    /// Allow overscroll by n items.
    pub v_overscroll: usize,
    /// Allow overscroll by n items.
    pub h_overscroll: usize,

    /// mouse action in progress
    pub v_drag: bool,
    pub h_drag: bool,

    pub non_exhaustive: NonExhaustive,
}

/// This policy plus the result of [ScrollingWidget::need_scroll]
/// allow to decide what to show.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ScrollbarPolicy {
    Always,
    #[default]
    AsNeeded,
    Never,
}

/// Position of the vertical scrollbar.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum VScrollPosition {
    Left,
    #[default]
    Right,
}

/// Position of the horizontal scrollbar.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum HScrollPosition {
    Top,
    #[default]
    Bottom,
}

impl<'a, T> Scrolled<'a, T> {
    /// New scrolled widget.
    pub fn new(inner: T) -> Self {
        Self {
            widget: inner,

            h_overscroll: 0,
            v_overscroll: 0,
            h_scroll_policy: Default::default(),
            v_scroll_policy: Default::default(),
            h_scroll_position: Default::default(),
            v_scroll_position: Default::default(),
            block: None,
            thumb_symbol: None,
            thumb_style: None,
            track_symbol: None,
            track_style: None,
            begin_symbol: None,
            begin_style: None,
            end_symbol: None,
            end_style: None,
        }
    }

    /// Allow overscrolling the max_offset by n.
    pub fn vertical_overscroll(mut self, n: usize) -> Self {
        self.v_overscroll = n;
        self
    }

    /// Allow overscrolling the max_offset by n.
    pub fn horizontal_overscroll(mut self, n: usize) -> Self {
        self.h_overscroll = n;
        self
    }

    /// Horizontal scrollbar policy.
    pub fn horizontal_scrollbar_policy(mut self, policy: ScrollbarPolicy) -> Self {
        self.h_scroll_policy = policy;
        self
    }

    /// Vertical scrollbar policy.
    pub fn vertical_scrollbar_policy(mut self, policy: ScrollbarPolicy) -> Self {
        self.v_scroll_policy = policy;
        self
    }

    /// Position
    pub fn horizontal_scroll_position(mut self, pos: HScrollPosition) -> Self {
        self.h_scroll_position = pos;
        self
    }

    /// Position
    pub fn vertical_scroll_position(mut self, pos: VScrollPosition) -> Self {
        self.v_scroll_position = pos;
        self
    }

    /// Block around the scrolled widget. The scrollbars are drawn
    /// as part of the block.
    ///
    /// Attention: There must be a border at the sides where you want
    /// the scrollbars. Otherwise, the calculations for the scrollbar placement
    /// will be off somewhat.
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    /// Symbol for the Scrollbar.
    pub fn thumb_symbol(mut self, thumb_symbol: &'a str) -> Self {
        self.thumb_symbol = Some(thumb_symbol);
        self
    }

    /// Style for the Scrollbar.
    pub fn thumb_style<S: Into<Style>>(mut self, thumb_style: S) -> Self {
        self.thumb_style = Some(thumb_style.into());
        self
    }

    /// Symbol for the Scrollbar.
    pub fn track_symbol(mut self, track_symbol: Option<&'a str>) -> Self {
        self.track_symbol = track_symbol;
        self
    }

    /// Style for the Scrollbar.
    pub fn track_style<S: Into<Style>>(mut self, track_style: S) -> Self {
        self.track_style = Some(track_style.into());
        self
    }

    /// Symbol for the Scrollbar.
    pub fn begin_symbol(mut self, begin_symbol: Option<&'a str>) -> Self {
        self.begin_symbol = begin_symbol;
        self
    }

    /// Style for the Scrollbar.
    pub fn begin_style<S: Into<Style>>(mut self, begin_style: S) -> Self {
        self.begin_style = Some(begin_style.into());
        self
    }

    /// Symbol for the Scrollbar.
    pub fn end_symbol(mut self, end_symbol: Option<&'a str>) -> Self {
        self.end_symbol = end_symbol;
        self
    }

    /// Style for the Scrollbar.
    pub fn end_style<S: Into<Style>>(mut self, end_style: S) -> Self {
        self.end_style = Some(end_style.into());
        self
    }

    /// Set all Scrollbar symbols.
    pub fn symbols(mut self, symbols: Set) -> Self {
        self.thumb_symbol = Some(symbols.thumb);
        if self.track_symbol.is_some() {
            self.track_symbol = Some(symbols.track);
        }
        if self.begin_symbol.is_some() {
            self.begin_symbol = Some(symbols.begin);
        }
        if self.end_symbol.is_some() {
            self.end_symbol = Some(symbols.end);
        }
        self
    }

    /// Set a style for all Scrollbar styles.
    pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
        let style = style.into();
        self.track_style = Some(style);
        self.thumb_style = Some(style);
        self.begin_style = Some(style);
        self.end_style = Some(style);
        self
    }
}

impl<'a, W> Scrolled<'a, View<W>>
where
    W: Widget,
{
    /// Create a `Scrolled<View<W>>` widget for widgets without builtin
    /// scrolling behaviour.
    ///
    /// You need to set a [view_size](Scrolled::view_size()) for the
    /// area the inner widget shall receive.
    ///
    /// See [Viewport] too.
    pub fn new_view(inner: W) -> Scrolled<'a, View<W>> {
        Self {
            widget: View::new(inner),
            h_overscroll: 0,
            v_overscroll: 0,
            h_scroll_policy: Default::default(),
            v_scroll_policy: Default::default(),
            h_scroll_position: Default::default(),
            v_scroll_position: Default::default(),
            block: None,
            thumb_symbol: None,
            thumb_style: None,
            track_symbol: None,
            track_style: None,
            begin_symbol: None,
            begin_style: None,
            end_symbol: None,
            end_style: None,
        }
    }

    /// Size for the inner widget.
    pub fn view_size(mut self, size: Size) -> Self {
        self.widget = self.widget.view_size(size);
        self
    }

    /// Style for the empty space outside the rendered buffer.
    pub fn view_style(mut self, style: Style) -> Self {
        self.widget = self.widget.style(style);
        self
    }
}

impl<'a, W> Scrolled<'a, Viewport<W>>
where
    W: StatefulWidget,
{
    /// Create a `Scrolled<Viewport<W>>` widget for widgets without builtin
    /// scrolling behaviour.
    ///
    /// You need to set a [view_size](Scrolled::view_size()) for the
    /// area the inner widget shall receive.
    ///
    /// See [Viewport] too.
    pub fn new_viewport(inner: W) -> Scrolled<'a, Viewport<W>> {
        Self {
            widget: Viewport::new(inner),
            h_overscroll: 0,
            v_overscroll: 0,
            h_scroll_policy: Default::default(),
            v_scroll_policy: Default::default(),
            h_scroll_position: Default::default(),
            v_scroll_position: Default::default(),
            block: None,
            thumb_symbol: None,
            thumb_style: None,
            track_symbol: None,
            track_style: None,
            begin_symbol: None,
            begin_style: None,
            end_symbol: None,
            end_style: None,
        }
    }

    /// Size for the inner widget.
    pub fn view_size(mut self, size: Size) -> Self {
        self.widget = self.widget.view_size(size);
        self
    }

    /// Style for the empty space outside the rendered buffer.
    pub fn view_style(mut self, style: Style) -> Self {
        self.widget = self.widget.style(style);
        self
    }
}

impl<'a, W> StatefulWidgetRef for Scrolled<'a, W>
where
    W: StatefulWidgetRef + ScrollingWidget<W::State>,
    W::State: ScrollingState,
{
    type State = ScrolledState<W::State>;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        let scroll_param = self
            .widget
            .need_scroll(self.block.inner_if_some(area), &mut state.widget);

        render_impl(self, area, buf, state, scroll_param, |area, buf, state| {
            self.widget.render_ref(area, buf, state);
        });
    }
}

impl<'a, W> StatefulWidget for Scrolled<'a, W>
where
    W: StatefulWidget + ScrollingWidget<W::State> + Default,
    W::State: ScrollingState,
{
    type State = ScrolledState<W::State>;

    fn render(mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        // reduced area for the widget to account for possible scrollbars.
        let view_area = if self.block.is_some() {
            // block should already account for the scrollbars.
            self.block.inner_if_some(area)
        } else {
            let w = if self.h_scroll_policy != ScrollbarPolicy::Never {
                area.width - 1
            } else {
                area.width
            };
            let h = if self.v_scroll_policy != ScrollbarPolicy::Never {
                area.height - 1
            } else {
                area.height
            };
            Rect::new(area.x, area.y, w, h)
        };

        let scroll_param = self.widget.need_scroll(view_area, &mut state.widget);

        let inner = mem::take(&mut self.widget);

        render_impl(&self, area, buf, state, scroll_param, |area, buf, state| {
            inner.render(area, buf, state);
        });
    }
}

fn render_impl<FnRender, W, WState>(
    widget: &Scrolled<'_, W>,
    area: Rect,
    buf: &mut Buffer,
    state: &mut ScrolledState<WState>,
    scroll_param: (bool, bool),
    render_inner: FnRender,
) where
    W: ScrollingWidget<WState>,
    WState: ScrollingState,
    FnRender: FnOnce(Rect, &mut Buffer, &mut WState),
{
    state.area = area;
    state.v_overscroll = widget.v_overscroll;
    state.h_overscroll = widget.h_overscroll;

    let has_hscroll = widget.h_scroll_policy.apply(scroll_param.0);
    let has_vscroll = widget.v_scroll_policy.apply(scroll_param.1);

    // Calculate the areas for the scrollbars and the view-area.
    // If there is a block set, assume there is a right and a bottom border too.
    // Currently, there is no way to know it. Overwriting part of the content is
    // ok in this case.
    if has_vscroll && has_hscroll {
        let mut vscrollbar_area = area.columns().last().expect("scroll");
        if widget.block.is_some() {
            vscrollbar_area.y += 1;
            vscrollbar_area.height -= 2;
        } else {
            vscrollbar_area.height -= 1;
        }
        state.v_scrollbar_area = Some(vscrollbar_area);

        let mut hscrollbar_area = area.rows().last().expect("scroll");
        if widget.block.is_some() {
            hscrollbar_area.x += 1;
            hscrollbar_area.width -= 2;
        } else {
            hscrollbar_area.width -= 1;
        }
        state.h_scrollbar_area = Some(hscrollbar_area);

        if let Some(block) = widget.block.as_ref() {
            state.view_area = block.inner(area);
        } else {
            state.view_area = area;
            state.view_area.width -= 1;
            state.view_area.height -= 1;
        }
    } else if has_vscroll {
        let mut vscrollbar_area = area.columns().last().expect("scroll");
        if widget.block.is_some() {
            vscrollbar_area.y += 1;
            vscrollbar_area.height -= 1;
        } else {
            vscrollbar_area.height -= 0;
        }
        state.v_scrollbar_area = Some(vscrollbar_area);

        state.h_scrollbar_area = None;

        if let Some(block) = widget.block.as_ref() {
            state.view_area = block.inner(area);
        } else {
            state.view_area = area;
            state.view_area.width -= 1;
            state.view_area.height -= 0;
        }
    } else if has_hscroll {
        state.v_scrollbar_area = None;

        let mut hscrollbar_area = area.rows().last().expect("scroll");
        if widget.block.is_some() {
            hscrollbar_area.x += 1;
            hscrollbar_area.width -= 1;
        } else {
            hscrollbar_area.width -= 0;
        }
        state.h_scrollbar_area = Some(hscrollbar_area);

        if let Some(block) = widget.block.as_ref() {
            state.view_area = block.inner(area);
        } else {
            state.view_area = area;
            state.view_area.width -= 0;
            state.view_area.height -= 1;
        }
    } else {
        state.v_scrollbar_area = None;
        state.h_scrollbar_area = None;

        if let Some(block) = widget.block.as_ref() {
            state.view_area = block.inner(area);
        } else {
            state.view_area = area;
            state.view_area.width -= 0;
            state.view_area.height -= 0;
        }
    }

    render_inner(state.view_area, buf, &mut state.widget);

    widget.block.render_ref(area, buf);

    if let Some(vscrollbar_area) = state.v_scrollbar_area {
        let mut vscroll = Scrollbar::new(widget.v_scroll_position.orientation());
        if let Some(thumb_symbol) = widget.thumb_symbol {
            vscroll = vscroll.thumb_symbol(thumb_symbol);
        }
        if let Some(track_symbol) = widget.track_symbol {
            vscroll = vscroll.track_symbol(Some(track_symbol));
        }
        if let Some(begin_symbol) = widget.begin_symbol {
            vscroll = vscroll.begin_symbol(Some(begin_symbol));
        }
        if let Some(end_symbol) = widget.end_symbol {
            vscroll = vscroll.end_symbol(Some(end_symbol));
        }
        if let Some(thumb_style) = widget.thumb_style {
            vscroll = vscroll.thumb_style(thumb_style);
        }
        if let Some(track_style) = widget.track_style {
            vscroll = vscroll.track_style(track_style);
        }
        if let Some(begin_style) = widget.begin_style {
            vscroll = vscroll.begin_style(begin_style);
        }
        if let Some(end_style) = widget.end_style {
            vscroll = vscroll.end_style(end_style);
        }

        let max_offset = state.widget.vertical_max_offset();
        let offset = state.widget.vertical_offset();
        let view_len = state.widget.vertical_page();

        let mut vscroll_state = ScrollbarState::new(max_offset)
            .position(offset)
            .viewport_content_length(view_len);
        vscroll.render(vscrollbar_area, buf, &mut vscroll_state);
    }

    if let Some(hscrollbar_area) = state.h_scrollbar_area {
        let mut hscroll = Scrollbar::new(widget.h_scroll_position.orientation());
        if let Some(thumb_symbol) = widget.thumb_symbol {
            hscroll = hscroll.thumb_symbol(thumb_symbol);
        }
        if let Some(track_symbol) = widget.track_symbol {
            hscroll = hscroll.track_symbol(Some(track_symbol));
        }
        if let Some(begin_symbol) = widget.begin_symbol {
            hscroll = hscroll.begin_symbol(Some(begin_symbol));
        }
        if let Some(end_symbol) = widget.end_symbol {
            hscroll = hscroll.end_symbol(Some(end_symbol));
        }
        if let Some(thumb_style) = widget.thumb_style {
            hscroll = hscroll.thumb_style(thumb_style);
        }
        if let Some(track_style) = widget.track_style {
            hscroll = hscroll.track_style(track_style);
        }
        if let Some(begin_style) = widget.begin_style {
            hscroll = hscroll.begin_style(begin_style);
        }
        if let Some(end_style) = widget.end_style {
            hscroll = hscroll.end_style(end_style);
        }

        let max_offset = state.widget.horizontal_max_offset();
        let offset = state.widget.horizontal_offset();
        let view_len = state.widget.horizontal_page();

        let mut hscroll_state = ScrollbarState::new(max_offset)
            .position(offset)
            .viewport_content_length(view_len);

        hscroll.render(hscrollbar_area, buf, &mut hscroll_state);
    }
}

impl ScrollbarPolicy {
    /// Apply the policy to the scroll-flag received from the inner widget.
    pub fn apply(&self, scroll: bool) -> bool {
        match self {
            ScrollbarPolicy::Always => true,
            ScrollbarPolicy::AsNeeded => scroll,
            ScrollbarPolicy::Never => false,
        }
    }
}

impl HScrollPosition {
    /// Convert to ScrollbarOrientation.
    pub fn orientation(&self) -> ScrollbarOrientation {
        match self {
            HScrollPosition::Top => ScrollbarOrientation::HorizontalTop,
            HScrollPosition::Bottom => ScrollbarOrientation::HorizontalBottom,
        }
    }
}

impl VScrollPosition {
    /// Convert to ScrollbarOrientation.
    pub fn orientation(&self) -> ScrollbarOrientation {
        match self {
            VScrollPosition::Left => ScrollbarOrientation::VerticalLeft,
            VScrollPosition::Right => ScrollbarOrientation::VerticalRight,
        }
    }
}

impl<WState: Default> Default for ScrolledState<WState> {
    fn default() -> Self {
        Self {
            widget: Default::default(),
            area: Default::default(),
            view_area: Default::default(),
            h_scrollbar_area: None,
            v_scrollbar_area: None,
            v_overscroll: 0,
            h_overscroll: 0,
            v_drag: false,
            h_drag: false,
            non_exhaustive: NonExhaustive,
        }
    }
}

impl<WState: ScrollingState> ScrolledState<WState> {
    /// Current vertical offset.
    pub fn vertical_offset(&self) -> usize {
        self.widget.vertical_offset()
    }

    /// Current horizontal offset.
    pub fn horizontal_offset(&self) -> usize {
        self.widget.horizontal_offset()
    }

    /// Change the offset. Limits the offset to max_v_offset + v_overscroll.
    ///
    /// Due to overscroll it's possible that this is an invalid
    /// offset for the widget. The widget must deal with this
    /// situation.
    pub fn set_vertical_offset(&mut self, offset: usize) -> bool {
        let voffset = min(
            offset,
            self.widget.vertical_max_offset() + self.v_overscroll,
        );
        self.widget.set_vertical_offset(voffset)
    }

    /// Change the offset. Limits the offset to max_h_offset + h_overscroll.
    ///
    /// Due to overscroll it's possible that this is an invalid
    /// offset for the widget. The widget must deal with this
    /// situation.
    pub fn set_horizontal_offset(&mut self, offset: usize) -> bool {
        let hoffset = min(
            offset,
            self.widget.horizontal_max_offset() + self.h_overscroll,
        );
        self.widget.set_horizontal_offset(hoffset)
    }

    /// Scroll up by n.
    pub fn scroll_up(&mut self, n: usize) -> bool {
        self.set_vertical_offset(self.vertical_offset().saturating_sub(n))
    }

    /// Scroll down by n, but limited by the max_offset + overscroll
    pub fn scroll_down(&mut self, n: usize) -> bool {
        let v_offset = min(
            self.widget.vertical_offset() + n,
            self.widget.vertical_max_offset() + self.v_overscroll,
        );
        self.set_vertical_offset(v_offset)
    }

    /// Scroll up by n.
    pub fn scroll_left(&mut self, n: usize) -> bool {
        self.set_horizontal_offset(self.horizontal_offset().saturating_sub(n))
    }

    /// Scroll right by n, but limited by the max_offset + overscroll
    pub fn scroll_right(&mut self, n: usize) -> bool {
        let hoffset = min(
            self.widget.horizontal_offset() + n,
            self.widget.horizontal_max_offset() + self.h_overscroll,
        );
        self.set_horizontal_offset(hoffset)
    }

    pub fn widget_mut(&mut self) -> &mut WState {
        &mut self.widget
    }
}

impl<R, WState> HandleEvent<crossterm::event::Event, FocusKeys, Outcome<R>>
    for ScrolledState<WState>
where
    WState: ScrollingState
        + HandleEvent<crossterm::event::Event, FocusKeys, R>
        + HandleEvent<crossterm::event::Event, MouseOnly, R>,
    R: PartialEq + UsedEvent,
{
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: FocusKeys) -> Outcome<R> {
        let r = self.widget.handle(event, FocusKeys);
        if !r.used_event() {
            self.handle(event, MouseOnly)
        } else {
            Outcome::Inner(r)
        }
    }
}

/// Handle events for the Scrolled widget and the scrollbars.
impl<R, WState> HandleEvent<crossterm::event::Event, MouseOnly, Outcome<R>>
    for ScrolledState<WState>
where
    WState: ScrollingState + HandleEvent<crossterm::event::Event, MouseOnly, R>,
    R: PartialEq + UsedEvent,
{
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: MouseOnly) -> Outcome<R> {
        let r = match event {
            crossterm::event::Event::Mouse(MouseEvent {
                kind:
                    MouseEventKind::Down(_)
                    | MouseEventKind::Up(_)
                    | MouseEventKind::ScrollDown
                    | MouseEventKind::ScrollUp
                    | MouseEventKind::ScrollLeft
                    | MouseEventKind::ScrollRight,
                column,
                row,
                ..
            }) => {
                // only forward certain mouse events if they are inside
                // the view_area. this prevents scrollbar collisions.
                if self.view_area.contains(Position::new(*column, *row)) {
                    Outcome::Inner(self.widget.handle(event, MouseOnly))
                } else {
                    Outcome::NotUsed
                }
            }
            _ => Outcome::Inner(self.widget.handle(event, MouseOnly)),
        };

        if !r.used_event() {
            match event {
                ct_event!(mouse down Left for column,row) => {
                    // Click in the scrollbar sets the offset to some absolute position.
                    if let Some(vscroll_area) = self.v_scrollbar_area {
                        if vscroll_area.contains(Position::new(*column, *row)) {
                            // correct for the top `^` and bottom `v` arrows.
                            let row = row.saturating_sub(vscroll_area.y).saturating_sub(1) as usize;
                            let height = vscroll_area.height.saturating_sub(2) as usize;

                            let pos = (self.widget.vertical_max_offset() * row) / height;

                            self.v_drag = true;
                            if self.widget.set_vertical_offset(pos) {
                                return Outcome::Changed;
                            } else {
                                return Outcome::NotUsed;
                            }
                        }
                    }
                    if let Some(hscroll_area) = self.h_scrollbar_area {
                        if hscroll_area.contains(Position::new(*column, *row)) {
                            // correct for the left `<` and right `>` arrows.
                            let col =
                                column.saturating_sub(hscroll_area.x).saturating_sub(1) as usize;
                            let width = hscroll_area.width.saturating_sub(2) as usize;

                            let pos = (self.widget.horizontal_max_offset() * col) / width;

                            self.h_drag = true;
                            if self.widget.set_horizontal_offset(pos) {
                                return Outcome::Changed;
                            } else {
                                return Outcome::NotUsed;
                            }
                        }
                    }
                }
                ct_event!(mouse drag Left for column, row) => {
                    // dragging around the scroll bar
                    if self.v_drag {
                        if let Some(vscroll_area) = self.v_scrollbar_area {
                            // correct for the top `^` and bottom `v` arrows.
                            let row = row.saturating_sub(vscroll_area.y).saturating_sub(1) as usize;
                            let height = vscroll_area.height.saturating_sub(2) as usize;

                            let pos = (self.widget.vertical_max_offset() * row) / height;
                            if self.set_vertical_offset(pos) {
                                return Outcome::Changed;
                            } else {
                                return Outcome::NotUsed;
                            }
                        }
                    }
                    if self.h_drag {
                        if let Some(hscroll_area) = self.h_scrollbar_area {
                            // correct for the left `<` and right `>` arrows.
                            let col =
                                column.saturating_sub(hscroll_area.x).saturating_sub(1) as usize;
                            let width = hscroll_area.width.saturating_sub(2) as usize;

                            let pos = (col * self.widget.horizontal_max_offset()) / width;
                            if self.set_horizontal_offset(pos) {
                                return Outcome::Changed;
                            } else {
                                return Outcome::NotUsed;
                            }
                        }
                    }
                }

                ct_event!(mouse moved) => {
                    // reset drag
                    self.v_drag = false;
                    self.h_drag = false;
                }

                ct_event!(scroll down for column, row) => {
                    if self.area.contains(Position::new(*column, *row)) {
                        if self.scroll_down(self.widget.vertical_scroll()) {
                            return Outcome::Changed;
                        } else {
                            return Outcome::NotUsed;
                        }
                    }
                }
                ct_event!(scroll up for column, row) => {
                    if self.area.contains(Position::new(*column, *row)) {
                        if self.widget.scroll_up(self.widget.vertical_scroll()) {
                            return Outcome::Changed;
                        } else {
                            return Outcome::NotUsed;
                        }
                    }
                }
                ct_event!(scroll ALT down for column, row) => {
                    // right scroll with ALT. shift doesn't work?
                    if self.area.contains(Position::new(*column, *row)) {
                        if self.scroll_right(self.widget.horizontal_scroll()) {
                            return Outcome::Changed;
                        } else {
                            return Outcome::NotUsed;
                        }
                    }
                }
                ct_event!(scroll ALT up for column, row) => {
                    // right scroll with ALT. shift doesn't work?
                    if self.area.contains(Position::new(*column, *row)) {
                        if self.widget.scroll_left(self.widget.horizontal_scroll()) {
                            return Outcome::Changed;
                        } else {
                            return Outcome::NotUsed;
                        }
                    }
                }
                _ => {}
            }
            Outcome::NotUsed
        } else {
            r
        }
    }
}