Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 28 additions & 11 deletions src/cef_impl/client/keyboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@

use cef::*;

/// Key handler: return 1 to consume the event, 0 to let it pass through.
type KeyHandler = dyn Fn(&KeyEvent) -> ::std::os::raw::c_int + Send + Sync;

static KEY_HANDLER: std::sync::OnceLock<Box<KeyHandler>> = std::sync::OnceLock::new();

pub fn set_key_handler(
handler: impl Fn(&KeyEvent) -> ::std::os::raw::c_int + Send + Sync + 'static,
) {
let _ = KEY_HANDLER.set(Box::new(handler));
}

#[cfg(target_os = "linux")]
type CefOsEvent<'a> = Option<&'a mut cef::sys::XEvent>;
#[cfg(target_os = "macos")]
Expand All @@ -24,19 +35,18 @@ wrap_keyboard_handler! {
_os_event: CefOsEvent<'_>,
_is_keyboard_shortcut: Option<&mut ::std::os::raw::c_int>,
) -> ::std::os::raw::c_int {
let Some(event) = event else {
return 0;
};

use cef::sys::cef_key_event_type_t;
let keydown_type: cef::KeyEventType = cef_key_event_type_t::KEYEVENT_RAWKEYDOWN.into();
if event.type_ != keydown_type {
return 0;
}

// If devtools is disabled, block devtools keyboard shortcuts.
if !self.devtools_enabled {
let Some(event) = event else {
return 0;
};

// Check if this is a keydown event.
use cef::sys::cef_key_event_type_t;
let keydown_type: cef::KeyEventType = cef_key_event_type_t::KEYEVENT_RAWKEYDOWN.into();
if event.type_ != keydown_type {
return 0;
}

// Get modifier keys.
use cef::sys::cef_event_flags_t;
#[cfg(windows)]
Expand Down Expand Up @@ -82,6 +92,13 @@ wrap_keyboard_handler! {
}
}

// does the handler want to consume a keypress?
if let Some(handler) = KEY_HANDLER.get()
&& handler(event) == 1
{
return 1;
}

0
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/cef_impl/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ mod context_menu;
mod display;
mod download;
mod drag;
mod keyboard;
pub(crate) mod keyboard;
mod life_span;
mod load;
mod permission;
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ mod window;
mod window_builder;
mod window_handle;

pub use cef_impl::client::keyboard::set_key_handler;
pub use config::{CefConfig, configure};
pub use policy::{
DEFAULT_PROMPT_TIMEOUT, DeferredResponder, DenyReason, NormalizedOrigin, PermissionAudit,
Expand Down