Update mutation example

This commit is contained in:
Alexandre Bury 2015-05-23 16:46:38 -07:00
parent 7e823435cd
commit 5a4c34361c
2 changed files with 29 additions and 6 deletions

View File

@ -1,19 +1,36 @@
extern crate cursive; extern crate cursive;
use cursive::Cursive; use cursive::Cursive;
use cursive::view::{IdView,TextView,Dialog,Selector}; use cursive::view::{IdView,TextView,Dialog,Selector,KeyEventView};
fn show_popup(siv: &mut Cursive) {
siv.add_layer(Dialog::new(TextView::new("Tak!"))
.button("Change", |s,_| {
// Look for a view tagged "text". We _know_ it's there, so unwrap it.
let view = s.find::<TextView>(&Selector::Id("text")).unwrap();
let content: String = view.get_content().chars().rev().collect();
view.set_content(&content);
})
.dismiss_button("Ok"));
}
fn main() { fn main() {
let mut siv = Cursive::new(); let mut siv = Cursive::new();
let content = "Press Q to quit the application.\n\nPress P to bring back the popup.";
siv.add_global_callback('q' as i32, |s,_| s.quit()); siv.add_global_callback('q' as i32, |s,_| s.quit());
siv.add_layer(IdView::new("text", TextView::new("Aaahh\nAaaah\nAaaah\nAaaaah\nAaaaah\nAaaaah\nAaaaah\nAaaaaah\nAaaaah"))); // Let's wrap the view to give it a recognizable ID, so we can look for it.
// We add the P callback on the textview only (and not globally),
// so that we can't call it when the popup is already visible.
siv.add_layer(KeyEventView::new(IdView::new("text", TextView::new(content)))
.register('p' as i32, |s,_| show_popup(s)));
show_popup(&mut siv);
siv.add_layer(Dialog::new(TextView::new("Tak!"))
.button("Change", |s,_| s.find::<TextView>(&Selector::Id("text")).unwrap()
.set_content("Bleeeeh\nBleeeeeeeeeeh\nBleeeh") )
.dismiss_button("Ok"));
siv.run(); siv.run();
} }

View File

@ -33,10 +33,16 @@ impl TextView {
} }
} }
/// Replace the text in this view.
pub fn set_content(&mut self, content: &str) { pub fn set_content(&mut self, content: &str) {
self.content = content.to_string(); self.content = content.to_string();
} }
/// Returns the current text in this view.
pub fn get_content(&self) -> &str {
&self.content
}
/// Returns the number of lines required to display the content /// Returns the number of lines required to display the content
/// with the given width. /// with the given width.
fn get_num_lines(&self, max_width: usize) -> usize { fn get_num_lines(&self, max_width: usize) -> usize {