cursive/examples/edit.rs

61 lines
2.0 KiB
Rust
Raw Normal View History

use cursive::traits::*;
2019-11-15 19:41:05 +00:00
use cursive::views::{Dialog, Edit, Text};
2018-06-11 06:29:10 +00:00
use cursive::Cursive;
fn main() {
let mut siv = Cursive::default();
2015-05-26 23:11:22 +00:00
// Create a dialog with an edit text and a button.
// The user can either hit the <Ok> button,
// or press Enter on the edit text.
2017-10-12 23:38:55 +00:00
siv.add_layer(
Dialog::new()
.title("Enter your name")
2018-01-16 02:55:27 +00:00
// Padding is (left, right, top, bottom)
2017-10-12 23:38:55 +00:00
.padding((1, 1, 1, 0))
.content(
2019-11-15 19:41:05 +00:00
Edit::new()
2018-06-20 17:28:44 +00:00
// Call `show_popup` when the user presses `Enter`
2017-10-12 23:38:55 +00:00
.on_submit(show_popup)
2019-11-15 19:41:05 +00:00
// Give the `Edit` a name so we can refer to it later.
2017-10-12 23:38:55 +00:00
.with_id("name")
2018-06-20 17:28:44 +00:00
// Wrap this in a `BoxView` with a fixed width.
// Do this _after_ `with_id` or the name will point to the
2019-11-15 19:41:05 +00:00
// `BoxView` instead of `Edit`!
2017-10-12 23:38:55 +00:00
.fixed_width(20),
)
.button("Ok", |s| {
2018-01-16 02:55:27 +00:00
// This will run the given closure, *ONLY* if a view with the
// correct type and the given ID is found.
2019-03-01 00:04:14 +00:00
let name = s
2019-11-15 19:41:05 +00:00
.call_on_id("name", |view: &mut Edit| {
2019-03-01 00:04:14 +00:00
// We can return content from the closure!
view.get_content()
})
.unwrap();
2018-01-16 02:55:27 +00:00
// Run the next step
2017-10-12 23:38:55 +00:00
show_popup(s, &name);
}),
);
siv.run();
}
2018-01-16 02:55:27 +00:00
// This will replace the current layer with a new popup.
// If the name is empty, we'll show an error message instead.
fn show_popup(s: &mut Cursive, name: &str) {
if name.is_empty() {
2018-06-20 17:28:44 +00:00
// Try again as many times as we need!
s.add_layer(Dialog::info("Please enter a name!"));
} else {
let content = format!("Hello {}!", name);
2018-06-20 17:28:44 +00:00
// Remove the initial popup
s.pop_layer();
2018-06-20 17:28:44 +00:00
// And put a new one instead
2017-10-12 23:38:55 +00:00
s.add_layer(
2019-11-15 19:41:05 +00:00
Dialog::around(Text::new(content)).button("Quit", |s| s.quit()),
2017-10-12 23:38:55 +00:00
);
}
}