cursive/examples/src/bin/text_area.rs

76 lines
2.3 KiB
Rust
Raw Normal View History

2017-12-07 23:49:12 +00:00
use cursive::event::{Event, Key};
use cursive::traits::*;
2017-12-07 23:49:12 +00:00
use cursive::views::{Dialog, EditView, OnEventView, TextArea};
2018-06-11 06:29:10 +00:00
use cursive::Cursive;
2016-08-02 07:32:16 +00:00
fn main() {
let mut siv = cursive::default();
2016-08-02 07:32:16 +00:00
2017-12-07 23:49:12 +00:00
// The main dialog will just have a textarea.
// Its size expand automatically with the content.
2017-10-12 23:38:55 +00:00
siv.add_layer(
Dialog::new()
.title("Describe your issue")
.padding_lrtb(1, 1, 1, 0)
2020-01-06 23:39:30 +00:00
.content(TextArea::new().with_name("text"))
2017-10-12 23:38:55 +00:00
.button("Ok", Cursive::quit),
);
2016-08-02 07:32:16 +00:00
2017-12-07 23:49:12 +00:00
// We'll add a find feature!
2018-06-16 20:23:09 +00:00
siv.add_layer(Dialog::info("Hint: press Ctrl-F to find in text!"));
2017-12-07 23:49:12 +00:00
siv.add_global_callback(Event::CtrlChar('f'), |s| {
// When Ctrl-F is pressed, show the Find popup.
// Pressing the Escape key will discard it.
s.add_layer(
OnEventView::new(
Dialog::new()
.title("Find")
.content(
EditView::new()
.on_submit(find)
2020-01-06 23:39:30 +00:00
.with_name("edit")
2017-12-07 23:49:12 +00:00
.min_width(10),
2019-03-01 00:04:14 +00:00
)
.button("Ok", |s| {
2018-08-22 20:33:29 +00:00
let text = s
2020-01-06 23:39:30 +00:00
.call_on_name("edit", |view: &mut EditView| {
2018-06-11 06:29:10 +00:00
view.get_content()
2019-03-01 00:04:14 +00:00
})
.unwrap();
2017-12-07 23:49:12 +00:00
find(s, &text);
2019-03-01 00:04:14 +00:00
})
.dismiss_button("Cancel"),
)
.on_event(Event::Key(Key::Esc), |s| {
s.pop_layer();
}),
2017-12-07 23:49:12 +00:00
)
});
2016-08-02 07:32:16 +00:00
siv.run();
}
2017-12-07 23:49:12 +00:00
fn find(siv: &mut Cursive, text: &str) {
// First, remove the find popup
siv.pop_layer();
2020-01-06 23:39:30 +00:00
let res = siv.call_on_name("text", |v: &mut TextArea| {
2017-12-07 23:49:12 +00:00
// Find the given text from the text area content
// Possible improvement: search after the current cursor.
if let Some(i) = v.get_content().find(text) {
// If we found it, move the cursor
v.set_cursor(i);
Ok(())
} else {
// Otherwise, return an error so we can show a warning.
Err(())
}
});
if let Some(Err(())) = res {
// If we didn't find anything, tell the user!
siv.add_layer(Dialog::info(format!("`{}` not found", text)));
}
}