Skip to content

Instantly share code, notes, and snippets.

@matthiasbeyer
Created December 6, 2019 23:10
Show Gist options
  • Save matthiasbeyer/2a61e9b9188e5a2fbcafc13b6f5b0e4c to your computer and use it in GitHub Desktop.
Save matthiasbeyer/2a61e9b9188e5a2fbcafc13b6f5b0e4c to your computer and use it in GitHub Desktop.
Context menu with Cursive
use cursive::event::{Event, Key};
use cursive::traits::*;
use cursive::views::{Dialog, EditView, OnEventView, TextArea};
use cursive::Cursive;
use cursive::view::Boxable;
use cursive::views::SelectView;
use cursive::event::EventResult;
use cursive::align::HAlign;
use cursive_context_menu::ContextMenu;
fn main() {
let mut siv = Cursive::default();
siv.add_layer(
Dialog::new()
.title("Describe your issue")
.padding((1, 1, 1, 0))
.content({
OnEventView::new(TextArea::new().with_id("text"))
.on_event(Event::CtrlChar('f'), |s| {
s.add_layer({
let mut select = SelectView::new()
// Center the text horizontally
.h_align(HAlign::Center)
// Use keyboard to jump to the pressed letters
.autojump();
select.add_all_str({
["foo", "bar", "Baz"].iter().map(ToString::to_string).collect::<Vec<String>>()
});
select.set_on_submit(|s, selection: &str| {
s.call_on_id("text", |v: &mut TextArea| {
let cursor_pos = v.cursor();
let content = v.get_content();
let (left, right) = content.split_at(cursor_pos);
v.set_content(format!("{}{}{}", left, selection, right));
});
s.pop_layer();
});
OnEventView::new(select)
.on_pre_event_inner('k', |s, _| {
s.select_up(1);
Some(EventResult::Consumed(None))
})
.on_pre_event_inner('j', |s, _| {
s.select_down(1);
Some(EventResult::Consumed(None))
})
})
})
})
.button("Ok", Cursive::quit)
.fixed_size((20, 20))
);
// We'll add a find feature!
siv.add_layer(Dialog::info("Hint: press Ctrl-F to find in text!"));
siv.run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment