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
use crate::{
    hlayout,
    views::{LoadingAnimation, Spacer}
};
use std::fmt::Display;
use cursive_core::{
    Cursive, With,
    view::Nameable,
    event::{Event, Key},
    views::{
        EditView,
        Dialog,
        OnEventView,
        NamedView,
        Checkbox,
        LinearLayout,
        TextView,
        DummyView,
        ResizedView
    },
    utils::markup::StyledString,
    theme::{
        PaletteColor,
        Color,
        BaseColor,
        ColorType,
        ColorStyle,
        BorderStyle,
        Theme
    }
};

#[cfg(feature = "buffered_backend")]
use cursive::CursiveRunnable;

#[cfg(feature = "buffered_backend")]
use std::convert::Infallible;

/// Convenience function that generates a better looking Cursive theme
///
/// # Example
/// ```
/// let mut root = cursive::default();
/// root.set_theme(better_theme());
/// ```
pub fn better_theme() -> Theme {
    let mut theme_def = Theme {
        shadow: false,
        .. Theme::default()
    };
    theme_def.palette[PaletteColor::Background] = Color::TerminalDefault;
    theme_def.palette[PaletteColor::Primary] = Color::Light(BaseColor::White);
    theme_def.palette[PaletteColor::View] = Color::TerminalDefault;
    theme_def.palette[PaletteColor::Highlight] = Color::Light(BaseColor::Blue);
    theme_def.palette[PaletteColor::HighlightText] = Color::Dark(BaseColor::White);
    theme_def.palette[PaletteColor::Secondary] = Color::Dark(BaseColor::Blue);
    theme_def.palette[PaletteColor::TitlePrimary] = Color::Light(BaseColor::Blue);
    theme_def.palette[PaletteColor::TitleSecondary] = Color::Dark(BaseColor::Blue);
    theme_def.borders = BorderStyle::Outset;
    theme_def
}

/// Convenience function that creates a dialog that runs a callback if the
/// user selects "Yes"
///
/// # Example
/// ```
/// let mut root = cursive::default();
/// root.add_layer(confirm_dialog("Are you sure?", "I solemnly swear that I am up to no good. /s", |view| view.quit()));
/// root.run();
/// ```
pub fn confirm_dialog<C, T, U>(title: T, text: U, cb: C) -> OnEventView<Dialog>
where
    C: Fn(&mut Cursive) + 'static,
    T: Display,
    U: Into<StyledString>
{
    Dialog::text(text)
        .dismiss_button("No")
        .button("Yes", cb)
        .title(title.to_string())
        .wrap_with(OnEventView::new)
        .on_event(Event::Key(Key::Esc), |r| {
            if r.screen().len() <= 1 { r.quit(); }
            else { r.pop_layer(); }
        })
}

/// Convenience function that shows a user a dialog box
/// with a message that includes a back button
///
/// # Example
/// ```
/// let mut root = cursive::default();
/// root.add_layer(info_dialog("Info", "This is important!"));
/// root.run();
/// ```
pub fn info_dialog<T: Display, U: Into<StyledString>>(title: T, text: U) -> OnEventView<Dialog> {
    Dialog::text(text)
        .dismiss_button("Back")
        .title(title.to_string())
        .wrap_with(OnEventView::new)
        .on_event(Event::Key(Key::Esc), |r| {
            if r.screen().len() <= 1 { r.quit(); }
            else { r.pop_layer(); }
        })
}

/// Convenience function that creates a named `EditView` that has a better
/// looking style and can optionally act as a password entry box
///
/// # Example
/// ```
/// let mut root = cursive::default();
/// root.add_fullscreen_layer(
///     Dialog::around(styled_editview("yes", "edit", false))
///         .button("Quit", |r| r.quit())
///         .title("Styled EditView Example")
/// );
/// root.run();
/// ```
pub fn styled_editview<C: Display>(content: C, view_name: &str, password: bool) -> NamedView<EditView> {
    styled_editview_color(content, view_name, password, PaletteColor::TitlePrimary)
}

/// Same as `styled_editview()` but allows for a color to be chosen instead of using the highlight color
pub fn styled_editview_color<T: Display, C: Into<ColorType>>(content: T, view_name: &str, password: bool, color: C) -> NamedView<EditView> {
    let input_style = ColorStyle::new(
        color,
        Color::Light(BaseColor::White),
    );
    let view = EditView::new().content(content.to_string()).style(input_style).filler(" ");

    if password { view.secret() }
    else { view }
        .with_name(view_name)
}

/// Convenience function that return the state of a named check box
///
/// Returns false if the checkbox is not checked or the checkbox with
/// the specified name does not exist
pub fn get_checkbox_option(root: &mut Cursive, name: &str) -> bool {
    if let Some(cbox) = root.find_name::<Checkbox>(name) {
        cbox.is_checked()
    }
    else { false }
}

/// Convenience function that returns a horizontal `LinearLayout` that is a named check box with a label
pub fn labeled_checkbox(text: &str, name: &str, checked: bool) -> LinearLayout {
    labeled_checkbox_cb(text, name, checked, |_, _| { })
}

/// Same as `labeled_checkbox()` but also accepts a closure to execute when the check box's state changes
pub fn labeled_checkbox_cb<C: Fn(&mut Cursive, bool) + 'static>(text: &str, name: &str, checked: bool, callback: C) -> LinearLayout {
    hlayout!(
        Checkbox::new()
            .with_checked(checked)
            .on_change(callback)
            .with_name(name),
        TextView::new(format!(" {text}"))
    )
}

/// Convenience function that shows a loading pop up
///
/// # Example
/// ```
/// let mut root = cursive::default();
/// root.set_theme(better_theme());
/// load_resource(&mut root,
///     "Loading...", "Loading Dummy Number...",
///     || {
///         thread::sleep(Duration::from_secs(5));
///         2 + 4
///     },
///     |root, val| {
///         assert_eq!(val, 6);
///         root.quit()
///     }
/// );
///
/// root.run();
/// ```
pub fn load_resource<T, R, F, D, M>(root: &mut Cursive, title: D, msg: M, task: R, finish_task: F)
where
    D: Display,
    T: Send + Sync + 'static,
    R: FnOnce() -> T + Send + Sync + 'static,
    M: Into<StyledString>,
    F: FnOnce(&mut Cursive, T) + Send + Sync + 'static
{
    let loader = LoadingAnimation::new(msg, move || (task(), finish_task));
    if root.fps().is_none() { root.set_fps(30); }
    root.add_layer(
        Dialog::around(loader.with_name("load")).title(title.to_string())
            .wrap_with(OnEventView::new)
            .on_event(Event::Refresh, |root: &mut Cursive| {
                let mut loader = root.find_name::<LoadingAnimation<(T, F)>>("load").unwrap();
                if loader.is_done() {
                    root.pop_layer();
                    let (val, finish_func) = loader.finish().unwrap();
                    finish_func(root, val);
                }
            })
    );
}

/// Horizontal spacer with fixed width
pub fn fixed_hspacer(width: usize) -> Spacer { ResizedView::with_fixed_width(width, DummyView) }

/// Horizontal spacer fills all the available width
pub fn filled_hspacer() -> Spacer { ResizedView::with_full_width(DummyView) }

/// Vertical spacer with fixed height
pub fn fixed_vspacer(height: usize) -> Spacer { ResizedView::with_fixed_height(height, DummyView) }

/// Vertical spacer fills all the available height
pub fn filled_vspacer() -> Spacer { ResizedView::with_full_height(DummyView) }

/// Creates a termion-based buffered backend cursive root using the `cursive_buffered_backend` crate
///
/// This is meant to be used with the `ImageView` view to avoid visual glitches and can also be used
/// if the termion backend on its own causes screen flickering
///
/// This function panics if the backend can't be created
///
/// Example:
/// ```
/// //let mut root = cursive::default(); // use the line below instead
/// let mut root = cursive_extras::buffered_backend_root();
/// root.add_layer(
///     Dialog::around(TextView::new("Yes"))
///         .title("Example")
///         .button("Quit", |r| r.quit())
/// );
/// root.run();
/// ```
#[cfg(feature = "buffered_backend")]
pub fn buffered_backend_root() -> CursiveRunnable {
    use cursive_core::backend::Backend;
    use cursive_buffered_backend::BufferedBackend;
    use cursive::backends::termion::Backend as TermionBackend;

    CursiveRunnable::new(|| -> Result<Box<dyn Backend>, Infallible> {
        let backend = TermionBackend::init().expect("Why is the backend not starting?");
        let buffered_backend = BufferedBackend::new(backend);
        Ok(Box::new(buffered_backend))
    })
}