Skip to content

Commit

Permalink
[libgui - Rust] TextInputView supports a user-provided key-pressed ca…
Browse files Browse the repository at this point in the history
…llback
  • Loading branch information
codyd51 committed Feb 7, 2024
1 parent 072e9d5 commit 8847e63
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions rust_programs/libgui/src/text_input_view.rs
Expand Up @@ -20,6 +20,7 @@ use crate::window_events::KeyCode;
pub struct TextInputView {
pub view: Rc<TextView>,
is_shift_held: RefCell<bool>,
key_pressed_cb: RefCell<Option<Box<dyn Fn(&Self, KeyCode)>>>,
}

impl TextInputView {
Expand All @@ -39,6 +40,7 @@ impl TextInputView {
Rc::new(Self {
view,
is_shift_held: RefCell::new(false),
key_pressed_cb: RefCell::new(None),
})
}

Expand Down Expand Up @@ -167,6 +169,10 @@ impl TextInputView {
}
println!();
}

pub fn set_on_key_pressed<F: 'static + Fn(&Self, KeyCode)>(&self, f: F) {
*self.key_pressed_cb.borrow_mut() = Some(Box::new(f));
}
}

// TODO(PT): Model keycodes in Rust
Expand Down Expand Up @@ -258,6 +264,12 @@ impl UIElement for TextInputView {
}

fn handle_key_pressed(&self, key: KeyCode) {
// First, dispatch the user-provided callback, if set
let callback = self.key_pressed_cb.borrow();
if let Some(callback) = callback.as_ref() {
callback(self, key);
}

if is_key_shift(key) {
*self.is_shift_held.borrow_mut() = true;
}
Expand Down

0 comments on commit 8847e63

Please sign in to comment.