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
//!
//! A message dialog.
//!

use crate::_private::NonExhaustive;
use crate::button::{Button, ButtonOutcome, ButtonState, ButtonStyle};
use crate::layout::layout_dialog;
use crate::paragraph::{Paragraph, ParagraphState};
use crate::util::fill_buf_area;
use rat_event::{ct_event, ConsumedEvent, Dialog, HandleEvent, Outcome, Regular};
use rat_focus::Focus;
use rat_scrolled::{Scroll, ScrollStyle};
use ratatui::buffer::Buffer;
use ratatui::layout::{Alignment, Constraint, Flex, Rect};
use ratatui::style::Style;
use ratatui::text::{Line, Text};
#[cfg(feature = "unstable-widget-ref")]
use ratatui::widgets::StatefulWidgetRef;
use ratatui::widgets::{Block, Padding, StatefulWidget, Widget};
use std::cell::{Cell, RefCell};
use std::cmp::max;
use std::fmt::Debug;

/// Basic status dialog for longer messages.
#[derive(Debug, Default, Clone)]
pub struct MsgDialog<'a> {
    block: Option<Block<'a>>,
    style: Style,
    scroll_style: Option<ScrollStyle>,
    button_style: ButtonStyle,
}

/// Combined style.
#[derive(Debug, Clone)]
pub struct MsgDialogStyle {
    pub style: Style,
    pub scroll: Option<ScrollStyle>,
    pub button: ButtonStyle,
    pub non_exhaustive: NonExhaustive,
}

/// State & event handling.
#[derive(Debug, Clone)]
pub struct MsgDialogState {
    /// Full area.
    pub area: Rect,
    /// Area inside the borders.
    pub inner: Rect,

    /// Dialog is active.
    pub active: Cell<bool>,
    /// Dialog title
    pub message_title: RefCell<String>,
    /// Dialog text.
    pub message: RefCell<String>,

    /// Ok button
    pub button: RefCell<ButtonState>,
    /// message-text
    pub paragraph: RefCell<ParagraphState>,

    pub non_exhaustive: NonExhaustive,
}

impl<'a> MsgDialog<'a> {
    /// New widget
    pub fn new() -> Self {
        Self {
            block: None,
            style: Default::default(),
            scroll_style: Default::default(),
            button_style: Default::default(),
        }
    }

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

    /// Combined style
    pub fn styles(mut self, styles: MsgDialogStyle) -> Self {
        self.style = styles.style;
        self.scroll_style = styles.scroll;
        self.button_style = styles.button;
        self
    }

    /// Base style
    pub fn style(mut self, style: impl Into<Style>) -> Self {
        self.style = style.into();
        self
    }

    /// Scroll style.
    pub fn scroll_style(mut self, style: ScrollStyle) -> Self {
        self.scroll_style = Some(style);
        self
    }

    /// Button style.
    pub fn button_style(mut self, style: ButtonStyle) -> Self {
        self.button_style = style;
        self
    }
}

impl Default for MsgDialogStyle {
    fn default() -> Self {
        Self {
            style: Default::default(),
            scroll: Default::default(),
            button: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl MsgDialogState {
    /// Show the dialog.
    pub fn set_active(&self, active: bool) {
        self.active.set(active);
        self.paragraph.borrow_mut().set_line_offset(0);
        self.paragraph.borrow_mut().set_col_offset(0);
    }

    /// Dialog is active.
    pub fn active(&self) -> bool {
        self.active.get()
    }

    /// Clear message text, set active to false.
    pub fn clear(&self) {
        self.active.set(false);
        *self.message.borrow_mut() = Default::default();
    }

    /// Set the title for the message.
    pub fn title(&self, title: impl Into<String>) {
        *self.message_title.borrow_mut() = title.into();
    }

    /// *Append* to the message.
    pub fn append(&self, msg: &str) {
        self.set_active(true);
        let mut message = self.message.borrow_mut();
        if !message.is_empty() {
            message.push('\n');
        }
        message.push_str(msg);
    }
}

impl Default for MsgDialogState {
    fn default() -> Self {
        let s = Self {
            active: Default::default(),
            area: Default::default(),
            inner: Default::default(),
            message: Default::default(),
            button: Default::default(),
            paragraph: Default::default(),
            non_exhaustive: NonExhaustive,
            message_title: Default::default(),
        };
        s.paragraph.borrow().focus.set(true);
        s
    }
}

impl MsgDialogState {
    fn focus(&self) -> Focus {
        let mut f = Focus::new();
        f.add(&*self.paragraph.borrow());
        f.add(&*self.button.borrow());
        f
    }
}

#[cfg(feature = "unstable-widget-ref")]
impl<'a> StatefulWidgetRef for MsgDialog<'a> {
    type State = MsgDialogState;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_ref(self, area, buf, state);
    }
}

impl<'a> StatefulWidget for MsgDialog<'a> {
    type State = MsgDialogState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_ref(&self, area, buf, state);
    }
}

fn render_ref(widget: &MsgDialog<'_>, area: Rect, buf: &mut Buffer, state: &mut MsgDialogState) {
    if state.active.get() {
        let mut block;
        let title = state.message_title.borrow();
        let block = if let Some(b) = &widget.block {
            if !title.is_empty() {
                block = b.clone().title(title.as_str());
                &block
            } else {
                b
            }
        } else {
            block = Block::bordered()
                .style(widget.style)
                .padding(Padding::new(1, 1, 1, 1));
            if !title.is_empty() {
                block = block.title(title.as_str());
            }
            &block
        };

        let l_dlg = layout_dialog(
            area, //
            Some(&block),
            [Constraint::Length(10)],
            0,
            Flex::End,
        );
        state.area = l_dlg.area;
        state.inner = l_dlg.inner;

        fill_buf_area(buf, state.area, " ", widget.style);
        block.render(state.area, buf);

        {
            let scroll = if let Some(style) = &widget.scroll_style {
                Scroll::new().styles(style.clone())
            } else {
                Scroll::new().style(widget.style)
            };

            let message = state.message.borrow();
            let mut lines = Vec::new();
            for t in message.split('\n') {
                lines.push(Line::from(t));
            }
            let text = Text::from(lines).alignment(Alignment::Center);
            Paragraph::new(text).scroll(scroll).render(
                l_dlg.content,
                buf,
                &mut state.paragraph.borrow_mut(),
            );
        }

        Button::from("Ok")
            .styles(widget.button_style.clone())
            .render(l_dlg.buttons[0], buf, &mut state.button.borrow_mut());
    }
}

impl HandleEvent<crossterm::event::Event, Dialog, Outcome> for MsgDialogState {
    fn handle(&mut self, event: &crossterm::event::Event, _: Dialog) -> Outcome {
        if self.active.get() {
            let mut focus = self.focus();
            let f = focus.handle(event, Regular);

            let mut r = match self.button.borrow_mut().handle(event, Regular) {
                ButtonOutcome::Pressed => {
                    self.clear();
                    self.active.set(false);
                    Outcome::Changed
                }
                v => v.into(),
            };
            r = r.or_else(|| self.paragraph.borrow_mut().handle(event, Regular));
            r = r.or_else(|| match event {
                ct_event!(keycode press Esc) => {
                    self.clear();
                    self.active.set(false);
                    Outcome::Changed
                }
                _ => Outcome::Continue,
            });
            // mandatory consume everything else.
            max(max(Outcome::Unchanged, f), r)
        } else {
            Outcome::Continue
        }
    }
}

/// Handle events for the MsgDialog.
pub fn handle_dialog_events(
    state: &mut MsgDialogState,
    event: &crossterm::event::Event,
) -> Outcome {
    state.handle(event, Dialog)
}