use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug};
use std::rc::Rc;
use std::sync::LazyLock;
use waft_foundation::{
App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, ListenableObject, Listener,
};
use waft_scheduler::{FrameCallback, SchedulerBinding};
use waft_services::{
HardwareKeyboard, KeyEvent, KeyboardKey, KeyboardLockMode, LogicalKeyboardKey,
};
use crate::framework::{
BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget,
StatelessWidget, WidgetRef,
};
use crate::widgets::actions::{Actions, IntentRef};
use crate::widgets::focus_manager::{AnyFocusNode, KeyEventResult, primary_focus};
use crate::widgets::focus_scope::Focus;
static CONTROL_SYNONYMS: LazyLock<HashSet<LogicalKeyboardKey>> = LazyLock::new(|| {
LogicalKeyboardKey::expand_synonyms(&HashSet::from([LogicalKeyboardKey::CONTROL]))
});
static SHIFT_SYNONYMS: LazyLock<HashSet<LogicalKeyboardKey>> = LazyLock::new(|| {
LogicalKeyboardKey::expand_synonyms(&HashSet::from([LogicalKeyboardKey::SHIFT]))
});
static ALT_SYNONYMS: LazyLock<HashSet<LogicalKeyboardKey>> = LazyLock::new(|| {
LogicalKeyboardKey::expand_synonyms(&HashSet::from([LogicalKeyboardKey::ALT]))
});
static META_SYNONYMS: LazyLock<HashSet<LogicalKeyboardKey>> = LazyLock::new(|| {
LogicalKeyboardKey::expand_synonyms(&HashSet::from([LogicalKeyboardKey::META]))
});
#[derive(Clone, PartialEq, Eq)]
pub struct KeySet<T: KeyboardKey + std::hash::Hash> {
keys: HashSet<T>,
}
impl<T: KeyboardKey + std::hash::Hash> KeySet<T> {
pub fn new(key1: T, key2: Option<T>, key3: Option<T>, key4: Option<T>) -> KeySet<T> {
let mut keys = HashSet::from([key1]);
let mut count = 1;
for key in [key2, key3, key4].into_iter().flatten() {
keys.insert(key);
count += 1;
}
debug_assert!(
keys.len() == count,
"Two or more provided keys are identical. Each key must appear only once."
);
KeySet { keys }
}
pub fn from_set(keys: HashSet<T>) -> KeySet<T> {
debug_assert!(!keys.is_empty());
KeySet { keys }
}
pub fn keys(&self) -> HashSet<T> {
self.keys.clone()
}
}
impl<T: KeyboardKey + std::hash::Hash> Debug for KeySet<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeySet").field("keys", &self.keys).finish()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LockState {
#[default]
Ignored,
Locked,
Unlocked,
}
pub trait ShortcutActivator: Debug {
fn triggers(&self) -> Option<Vec<LogicalKeyboardKey>> {
None
}
fn accepts(&self, app: &App, event: &KeyEvent, state: Handle<HardwareKeyboard>) -> bool;
fn debug_describe_keys(&self) -> String;
}
pub type ShortcutActivatorRef = Rc<dyn ShortcutActivator>;
pub type ShortcutMap = Vec<(ShortcutActivatorRef, IntentRef)>;
#[derive(Clone, PartialEq, Eq)]
pub struct LogicalKeySet {
key_set: KeySet<LogicalKeyboardKey>,
triggers: HashSet<LogicalKeyboardKey>,
}
impl LogicalKeySet {
pub fn new(
key1: LogicalKeyboardKey,
key2: Option<LogicalKeyboardKey>,
key3: Option<LogicalKeyboardKey>,
key4: Option<LogicalKeyboardKey>,
) -> LogicalKeySet {
LogicalKeySet::of(KeySet::new(key1, key2, key3, key4))
}
pub fn from_set(keys: HashSet<LogicalKeyboardKey>) -> LogicalKeySet {
LogicalKeySet::of(KeySet::from_set(keys))
}
fn of(key_set: KeySet<LogicalKeyboardKey>) -> LogicalKeySet {
let triggers = key_set
.keys()
.into_iter()
.flat_map(|key| match unmap_synonyms(key) {
Some(keys) => keys,
None => vec![key],
})
.collect();
LogicalKeySet { key_set, triggers }
}
pub fn keys(&self) -> HashSet<LogicalKeyboardKey> {
self.key_set.keys()
}
fn check_key_requirements(&self, pressed: &HashSet<LogicalKeyboardKey>) -> bool {
let collapsed_required = LogicalKeyboardKey::collapse_synonyms(&self.keys());
let collapsed_pressed = LogicalKeyboardKey::collapse_synonyms(pressed);
collapsed_required.len() == collapsed_pressed.len()
&& collapsed_required.difference(&collapsed_pressed).count() == 0
}
}
fn modifiers() -> [LogicalKeyboardKey; 4] {
[
LogicalKeyboardKey::ALT,
LogicalKeyboardKey::CONTROL,
LogicalKeyboardKey::META,
LogicalKeyboardKey::SHIFT,
]
}
fn unmap_synonyms(key: LogicalKeyboardKey) -> Option<Vec<LogicalKeyboardKey>> {
if key == LogicalKeyboardKey::CONTROL {
return Some(vec![
LogicalKeyboardKey::CONTROL_LEFT,
LogicalKeyboardKey::CONTROL_RIGHT,
]);
}
if key == LogicalKeyboardKey::SHIFT {
return Some(vec![
LogicalKeyboardKey::SHIFT_LEFT,
LogicalKeyboardKey::SHIFT_RIGHT,
]);
}
if key == LogicalKeyboardKey::ALT {
return Some(vec![
LogicalKeyboardKey::ALT_LEFT,
LogicalKeyboardKey::ALT_RIGHT,
]);
}
if key == LogicalKeyboardKey::META {
return Some(vec![
LogicalKeyboardKey::META_LEFT,
LogicalKeyboardKey::META_RIGHT,
]);
}
None
}
impl Debug for LogicalKeySet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LogicalKeySet")
.field("keys", &self.debug_describe_keys())
.finish()
}
}
impl ShortcutActivator for LogicalKeySet {
fn triggers(&self) -> Option<Vec<LogicalKeyboardKey>> {
Some(self.triggers.iter().copied().collect())
}
fn accepts(&self, app: &App, event: &KeyEvent, state: Handle<HardwareKeyboard>) -> bool {
if !matches!(event, KeyEvent::Down(_) | KeyEvent::Repeat(_)) {
return false;
}
self.triggers.contains(&event.logical_key())
&& self.check_key_requirements(&state.logical_keys_pressed(app))
}
fn debug_describe_keys(&self) -> String {
let mut sorted_keys: Vec<LogicalKeyboardKey> = self.keys().into_iter().collect();
sorted_keys.sort_by(|a, b| {
let a_is_modifier = !a.synonyms().is_empty() || modifiers().contains(a);
let b_is_modifier = !b.synonyms().is_empty() || modifiers().contains(b);
if a_is_modifier && !b_is_modifier {
return std::cmp::Ordering::Less;
}
if b_is_modifier && !a_is_modifier {
return std::cmp::Ordering::Greater;
}
a.debug_name().cmp(&b.debug_name())
});
sorted_keys
.iter()
.map(|key| format!("{:?}", key.debug_name()))
.collect::<Vec<String>>()
.join(" + ")
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SingleActivator {
pub trigger: LogicalKeyboardKey,
pub control: bool,
pub shift: bool,
pub alt: bool,
pub meta: bool,
pub num_lock: LockState,
pub include_repeats: bool,
}
impl SingleActivator {
pub fn new(trigger: LogicalKeyboardKey) -> SingleActivator {
debug_assert!(
![
LogicalKeyboardKey::CONTROL,
LogicalKeyboardKey::CONTROL_LEFT,
LogicalKeyboardKey::CONTROL_RIGHT,
LogicalKeyboardKey::SHIFT,
LogicalKeyboardKey::SHIFT_LEFT,
LogicalKeyboardKey::SHIFT_RIGHT,
LogicalKeyboardKey::ALT,
LogicalKeyboardKey::ALT_LEFT,
LogicalKeyboardKey::ALT_RIGHT,
LogicalKeyboardKey::META,
LogicalKeyboardKey::META_LEFT,
LogicalKeyboardKey::META_RIGHT,
]
.contains(&trigger)
);
SingleActivator {
trigger,
control: false,
shift: false,
alt: false,
meta: false,
num_lock: LockState::Ignored,
include_repeats: true,
}
}
pub fn control(mut self, control: bool) -> SingleActivator {
self.control = control;
self
}
pub fn shift(mut self, shift: bool) -> SingleActivator {
self.shift = shift;
self
}
pub fn alt(mut self, alt: bool) -> SingleActivator {
self.alt = alt;
self
}
pub fn meta(mut self, meta: bool) -> SingleActivator {
self.meta = meta;
self
}
pub fn num_lock(mut self, num_lock: LockState) -> SingleActivator {
self.num_lock = num_lock;
self
}
pub fn include_repeats(mut self, include_repeats: bool) -> SingleActivator {
self.include_repeats = include_repeats;
self
}
fn should_accept_modifiers(&self, pressed: &HashSet<LogicalKeyboardKey>) -> bool {
self.control == intersects(pressed, &CONTROL_SYNONYMS)
&& self.shift == intersects(pressed, &SHIFT_SYNONYMS)
&& self.alt == intersects(pressed, &ALT_SYNONYMS)
&& self.meta == intersects(pressed, &META_SYNONYMS)
}
fn should_accept_num_lock(&self, app: &App, state: Handle<HardwareKeyboard>) -> bool {
match self.num_lock {
LockState::Ignored => true,
LockState::Locked => state
.lock_modes_enabled(app)
.contains(&KeyboardLockMode::NumLock),
LockState::Unlocked => !state
.lock_modes_enabled(app)
.contains(&KeyboardLockMode::NumLock),
}
}
}
fn intersects(
pressed: &HashSet<LogicalKeyboardKey>,
synonyms: &HashSet<LogicalKeyboardKey>,
) -> bool {
pressed.intersection(synonyms).next().is_some()
}
impl ShortcutActivator for SingleActivator {
fn triggers(&self) -> Option<Vec<LogicalKeyboardKey>> {
Some(vec![self.trigger])
}
fn accepts(&self, app: &App, event: &KeyEvent, state: Handle<HardwareKeyboard>) -> bool {
(matches!(event, KeyEvent::Down(_))
|| (self.include_repeats && matches!(event, KeyEvent::Repeat(_))))
&& self.trigger == event.logical_key()
&& self.should_accept_modifiers(&state.logical_keys_pressed(app))
&& self.should_accept_num_lock(app, state)
}
fn debug_describe_keys(&self) -> String {
let mut keys: Vec<String> = Vec::new();
if self.control {
keys.push("Control".to_string());
}
if self.alt {
keys.push("Alt".to_string());
}
if self.meta {
keys.push("Meta".to_string());
}
if self.shift {
keys.push("Shift".to_string());
}
keys.push(
self.trigger
.debug_name()
.unwrap_or_else(|| format!("{:?}", self.trigger)),
);
keys.join(" + ")
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CharacterActivator {
pub alt: bool,
pub control: bool,
pub meta: bool,
pub include_repeats: bool,
pub character: String,
}
impl CharacterActivator {
pub fn new(character: impl Into<String>) -> CharacterActivator {
CharacterActivator {
alt: false,
control: false,
meta: false,
include_repeats: true,
character: character.into(),
}
}
pub fn alt(mut self, alt: bool) -> CharacterActivator {
self.alt = alt;
self
}
pub fn control(mut self, control: bool) -> CharacterActivator {
self.control = control;
self
}
pub fn meta(mut self, meta: bool) -> CharacterActivator {
self.meta = meta;
self
}
pub fn include_repeats(mut self, include_repeats: bool) -> CharacterActivator {
self.include_repeats = include_repeats;
self
}
fn should_accept_modifiers(&self, pressed: &HashSet<LogicalKeyboardKey>) -> bool {
self.control == intersects(pressed, &CONTROL_SYNONYMS)
&& self.alt == intersects(pressed, &ALT_SYNONYMS)
&& self.meta == intersects(pressed, &META_SYNONYMS)
}
}
impl ShortcutActivator for CharacterActivator {
fn accepts(&self, app: &App, event: &KeyEvent, state: Handle<HardwareKeyboard>) -> bool {
event.character() == Some(self.character.as_str())
&& (matches!(event, KeyEvent::Down(_))
|| (self.include_repeats && matches!(event, KeyEvent::Repeat(_))))
&& self.should_accept_modifiers(&state.logical_keys_pressed(app))
}
fn debug_describe_keys(&self) -> String {
let mut keys: Vec<String> = Vec::new();
if self.alt {
keys.push("Alt".to_string());
}
if self.control {
keys.push("Control".to_string());
}
if self.meta {
keys.push("Meta".to_string());
}
keys.push(format!("'{}'", self.character));
keys.join(" + ")
}
}
pub struct ActivatorIntentPair {
activator: ShortcutActivatorRef,
intent: IntentRef,
}
pub struct ShortcutManagerData {
modal: bool,
shortcuts: ShortcutMap,
indexed_shortcuts_cache:
Option<Rc<HashMap<Option<LogicalKeyboardKey>, Vec<ActivatorIntentPair>>>>,
}
impl ShortcutManagerData {
pub fn new() -> ShortcutManagerData {
ShortcutManagerData {
modal: false,
shortcuts: Vec::new(),
indexed_shortcuts_cache: None,
}
}
}
impl Default for ShortcutManagerData {
fn default() -> ShortcutManagerData {
ShortcutManagerData::new()
}
}
#[macro_export]
macro_rules! shortcut_manager_accessors {
() => {
fn shortcut_manager_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::ShortcutManagerData {
&app.get(self).shortcut_manager
}
fn shortcut_manager_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::ShortcutManagerData {
&mut app.get_mut(self).shortcut_manager
}
};
}
pub trait ShortcutManagerBase: ChangeNotifier + Sized + 'static {
fn shortcut_manager_data(self: Handle<Self>, app: &App) -> &ShortcutManagerData;
fn shortcut_manager_data_mut(self: Handle<Self>, app: &mut App) -> &mut ShortcutManagerData;
fn as_shortcut_manager(self: Handle<Self>) -> AnyShortcutManager {
AnyShortcutManager {
id: self.id(),
vtable: const { &ShortcutManagerVTable::of::<Self>() },
}
}
fn modal(self: Handle<Self>, app: &App) -> bool {
self.shortcut_manager_data(app).modal
}
fn set_modal(self: Handle<Self>, app: &mut App, modal: bool) {
self.shortcut_manager_data_mut(app).modal = modal;
}
fn shortcuts(self: Handle<Self>, app: &App) -> ShortcutMap {
self.shortcut_manager_data(app).shortcuts.clone()
}
fn set_shortcuts(self: Handle<Self>, app: &mut App, value: ShortcutMap) {
if !same_shortcuts(&self.shortcut_manager_data(app).shortcuts, &value) {
let data = self.shortcut_manager_data_mut(app);
data.shortcuts = value;
data.indexed_shortcuts_cache = None;
self.notify_listeners(app);
}
}
fn indexed_shortcuts(
self: Handle<Self>,
app: &mut App,
) -> Rc<HashMap<Option<LogicalKeyboardKey>, Vec<ActivatorIntentPair>>> {
if let Some(cache) = self
.shortcut_manager_data(app)
.indexed_shortcuts_cache
.clone()
{
return cache;
}
let indexed = Rc::new(index_shortcuts(&self.shortcut_manager_data(app).shortcuts));
self.shortcut_manager_data_mut(app).indexed_shortcuts_cache = Some(Rc::clone(&indexed));
indexed
}
fn find(
self: Handle<Self>,
app: &mut App,
event: &KeyEvent,
state: Handle<HardwareKeyboard>,
) -> Option<IntentRef> {
let indexed = self.indexed_shortcuts(app);
let key = Some(event.logical_key());
let candidates = indexed
.get(&key)
.into_iter()
.flatten()
.chain(indexed.get(&None).into_iter().flatten());
for activator_intent in candidates {
if activator_intent.activator.accepts(app, event, state) {
return Some(Rc::clone(&activator_intent.intent));
}
}
None
}
fn handle_keypress(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
event: &KeyEvent,
) -> KeyEventResult {
ShortcutManagerKeypress::handle_keypress(self, app, context, event)
}
}
pub trait ShortcutManagerKeypress: ShortcutManagerBase {
fn handle_keypress(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
event: &KeyEvent,
) -> KeyEventResult {
let _ = context;
let keyboard = HardwareKeyboard::instance(app);
let intent = self.find(app, event, keyboard);
let context = primary_focus(app).and_then(|node| node.context(app));
if let Some(intent) = intent
&& let Some(context) = context
&& let Some(action) = Actions::maybe_find(app, context, intent.intent_type())
{
let (enabled, invoke_result) = Actions::of(app, context).invoke_action_if_enabled(
app,
action,
&*intent,
Some(context),
);
if enabled {
return action.to_key_event_result(app, &*intent, invoke_result.as_ref());
}
}
if self.modal(app) {
KeyEventResult::SkipRemainingHandlers
} else {
KeyEventResult::Ignored
}
}
}
impl<T: ShortcutManagerBase> ShortcutManagerKeypress for T {}
struct ShortcutManagerVTable {
type_name: fn() -> &'static str,
shortcuts: fn(&App, HandleId) -> ShortcutMap,
set_shortcuts: fn(&mut App, HandleId, ShortcutMap),
modal: fn(&App, HandleId) -> bool,
set_modal: fn(&mut App, HandleId, bool),
handle_keypress: fn(&mut App, HandleId, BuildContext, &KeyEvent) -> KeyEventResult,
dispose: fn(&mut App, HandleId),
}
fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
Handle::from_id(id)
}
impl ShortcutManagerVTable {
const fn of<L: ShortcutManagerBase>() -> ShortcutManagerVTable {
ShortcutManagerVTable {
type_name: std::any::type_name::<L>,
shortcuts: |app, id| L::shortcuts(resolve(id), app),
set_shortcuts: |app, id, value| L::set_shortcuts(resolve(id), app, value),
modal: |app, id| L::modal(resolve(id), app),
set_modal: |app, id, value| L::set_modal(resolve(id), app, value),
handle_keypress: |app, id, context, event| {
L::handle_keypress(resolve(id), app, context, event)
},
dispose: |app, id| {
let handle: Handle<L> = resolve(id);
app.get_mut(handle).change_notifier_data_mut().dispose();
},
}
}
}
#[derive(Clone, Copy)]
pub struct AnyShortcutManager {
id: HandleId,
vtable: &'static ShortcutManagerVTable,
}
impl PartialEq for AnyShortcutManager {
fn eq(&self, other: &AnyShortcutManager) -> bool {
self.id == other.id
}
}
impl Eq for AnyShortcutManager {}
impl fmt::Debug for AnyShortcutManager {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
}
}
impl AnyShortcutManager {
pub fn id(self) -> HandleId {
self.id
}
pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
app.handle::<T>(self.id)
}
pub fn shortcuts(self, app: &App) -> ShortcutMap {
(self.vtable.shortcuts)(app, self.id)
}
pub fn set_shortcuts(self, app: &mut App, value: ShortcutMap) {
(self.vtable.set_shortcuts)(app, self.id, value);
}
pub fn modal(self, app: &App) -> bool {
(self.vtable.modal)(app, self.id)
}
pub fn set_modal(self, app: &mut App, value: bool) {
(self.vtable.set_modal)(app, self.id, value);
}
pub fn handle_keypress(
self,
app: &mut App,
context: BuildContext,
event: &KeyEvent,
) -> KeyEventResult {
(self.vtable.handle_keypress)(app, self.id, context, event)
}
pub fn dispose(self, app: &mut App) {
(self.vtable.dispose)(app, self.id);
}
}
pub struct ShortcutManager {
change_notifier: ChangeNotifierData,
shortcut_manager: ShortcutManagerData,
}
impl ShortcutManager {
pub fn new(app: &mut App) -> Handle<ShortcutManager> {
app.create(ShortcutManager {
change_notifier: ChangeNotifierData::new(),
shortcut_manager: ShortcutManagerData::new(),
})
}
}
impl ShortcutManagerBase for ShortcutManager {
crate::shortcut_manager_accessors!();
}
impl ChangeNotifier for ShortcutManager {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
fn index_shortcuts(
source: &ShortcutMap,
) -> HashMap<Option<LogicalKeyboardKey>, Vec<ActivatorIntentPair>> {
let mut result: HashMap<Option<LogicalKeyboardKey>, Vec<ActivatorIntentPair>> = HashMap::new();
for (activator, intent) in source {
let nullable_triggers = activator.triggers();
let triggers: Vec<Option<LogicalKeyboardKey>> = match nullable_triggers {
Some(triggers) => triggers.into_iter().map(Some).collect(),
None => vec![None],
};
for trigger in triggers {
result
.entry(trigger)
.or_default()
.push(ActivatorIntentPair {
activator: Rc::clone(activator),
intent: Rc::clone(intent),
});
}
}
result
}
fn same_shortcuts(a: &ShortcutMap, b: &ShortcutMap) -> bool {
a.len() == b.len()
&& a.iter()
.zip(b.iter())
.all(|(a, b)| Rc::ptr_eq(&a.0, &b.0) && Rc::ptr_eq(&a.1, &b.1))
}
pub struct Shortcuts {
pub key: Option<KeyRef>,
pub manager: Option<AnyShortcutManager>,
pub child: WidgetRef,
pub debug_label: Option<String>,
pub include_semantics: bool,
shortcuts: ShortcutMap,
}
impl Shortcuts {
pub fn new<K>(shortcuts: ShortcutMap, child: impl IntoWidget<K>) -> Shortcuts {
Shortcuts {
key: None,
manager: None,
child: child.into_widget(),
debug_label: None,
include_semantics: true,
shortcuts,
}
}
pub fn manager<K>(manager: AnyShortcutManager, child: impl IntoWidget<K>) -> Shortcuts {
Shortcuts {
manager: Some(manager),
..Shortcuts::new(Vec::new(), child)
}
}
pub fn key(mut self, key: KeyRef) -> Shortcuts {
self.key = Some(key);
self
}
pub fn debug_label(mut self, debug_label: impl Into<String>) -> Shortcuts {
self.debug_label = Some(debug_label.into());
self
}
pub fn include_semantics(mut self, include_semantics: bool) -> Shortcuts {
self.include_semantics = include_semantics;
self
}
pub fn get_shortcuts(&self, app: &App) -> ShortcutMap {
match self.manager {
None => self.shortcuts.clone(),
Some(manager) => manager.shortcuts(app),
}
}
}
impl fmt::Debug for Shortcuts {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Shortcuts")
.field("manager", &self.manager)
.field("debugLabel", &self.debug_label)
.finish_non_exhaustive()
}
}
impl StatefulWidget for Shortcuts {
type State = ShortcutsState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> ShortcutsState {
ShortcutsState {
state: StateData::new(),
internal_manager: None,
}
}
}
pub struct ShortcutsState {
state: StateData<Shortcuts>,
internal_manager: Option<Handle<ShortcutManager>>,
}
impl ShortcutsState {
pub fn manager(self: Handle<Self>, app: &App) -> AnyShortcutManager {
self.widget(app)
.manager
.or_else(|| {
app.get(self)
.internal_manager
.map(ShortcutManagerBase::as_shortcut_manager)
})
.expect("a Shortcuts state has either the widget's manager or its own")
}
fn handle_on_key_event(
self: Handle<Self>,
app: &mut App,
node: AnyFocusNode,
event: &KeyEvent,
) -> KeyEventResult {
let Some(context) = node.context(app) else {
return KeyEventResult::Ignored;
};
self.manager(app).handle_keypress(app, context, event)
}
}
impl State for ShortcutsState {
type Widget = Shortcuts;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
if self.widget(app).manager.is_none() {
let manager = ShortcutManager::new(app);
app.get_mut(self).internal_manager = Some(manager);
let shortcuts = self.widget(app).get_shortcuts(app);
manager.set_shortcuts(app, shortcuts);
}
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Shortcuts) {
if self.widget(app).manager != old_widget.manager {
if self.widget(app).manager.is_some() {
if let Some(internal) = app.get_mut(self).internal_manager.take() {
app.get_mut(internal).change_notifier.dispose();
}
} else if app.get(self).internal_manager.is_none() {
let manager = ShortcutManager::new(app);
app.get_mut(self).internal_manager = Some(manager);
}
}
if let Some(internal) = app.get(self).internal_manager {
let shortcuts = self.widget(app).get_shortcuts(app);
internal.set_shortcuts(app, shortcuts);
}
}
fn dispose(self: Handle<Self>, app: &mut App) {
if let Some(internal) = app.get(self).internal_manager {
app.get_mut(internal).change_notifier.dispose();
}
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let widget = self.widget(app);
let debug_label = match &widget.debug_label {
Some(label) => format!("Shortcuts: {label}"),
None => "Shortcuts".to_string(),
};
let include_semantics = widget.include_semantics;
let child = widget.child.clone();
Focus::new(child)
.debug_label(debug_label)
.can_request_focus(false)
.on_key_event(Rc::new(move |app, node, event| {
self.handle_on_key_event(app, node, event)
}))
.include_semantics(include_semantics)
.into_widget()
}
}
pub struct CallbackShortcuts {
pub key: Option<KeyRef>,
pub bindings: Vec<(ShortcutActivatorRef, Listener)>,
pub child: WidgetRef,
}
impl CallbackShortcuts {
pub fn new<K>(
bindings: Vec<(ShortcutActivatorRef, Listener)>,
child: impl IntoWidget<K>,
) -> CallbackShortcuts {
CallbackShortcuts {
key: None,
bindings,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> CallbackShortcuts {
self.key = Some(key);
self
}
fn apply_key_event_binding(
app: &mut App,
binding: &(ShortcutActivatorRef, Listener),
event: &KeyEvent,
) -> bool {
let keyboard = HardwareKeyboard::instance(app);
if binding.0.accepts(app, event, keyboard) {
binding.1.call(app);
return true;
}
false
}
}
impl fmt::Debug for CallbackShortcuts {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CallbackShortcuts").finish_non_exhaustive()
}
}
impl StatelessWidget for CallbackShortcuts {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
let bindings: Rc<Vec<(ShortcutActivatorRef, Listener)>> = Rc::new(
self.bindings
.iter()
.map(|(activator, callback)| (Rc::clone(activator), callback.clone()))
.collect(),
);
Focus::new(self.child.clone())
.can_request_focus(false)
.skip_traversal(true)
.on_key_event(Rc::new(move |app, _node, event| {
let mut result = KeyEventResult::Ignored;
for binding in bindings.iter() {
result = if CallbackShortcuts::apply_key_event_binding(app, binding, event) {
KeyEventResult::Handled
} else {
result
};
}
result
}))
.into_widget()
}
}
pub struct ShortcutRegistryEntry {
registry: Handle<ShortcutRegistry>,
}
impl ShortcutRegistryEntry {
pub fn registry(self: Handle<Self>, app: &App) -> Handle<ShortcutRegistry> {
app.get(self).registry
}
pub fn replace_all(self: Handle<Self>, app: &mut App, value: ShortcutMap) {
let registry = app.get(self).registry;
registry.replace_all(app, self, value);
}
pub fn dispose(self: Handle<Self>, app: &mut App) {
let registry = app.get(self).registry;
registry.dispose_entry(app, self);
}
}
pub struct ShortcutRegistry {
change_notifier: ChangeNotifierData,
notification_scheduled: bool,
disposed: bool,
registered_shortcuts: Vec<(Handle<ShortcutRegistryEntry>, ShortcutMap)>,
}
impl ShortcutRegistry {
pub fn new(app: &mut App) -> Handle<ShortcutRegistry> {
app.create(ShortcutRegistry {
change_notifier: ChangeNotifierData::new(),
notification_scheduled: false,
disposed: false,
registered_shortcuts: Vec::new(),
})
}
pub fn dispose(self: Handle<Self>, app: &mut App) {
let this = app.get_mut(self);
this.change_notifier.dispose();
this.disposed = true;
}
pub fn shortcuts(self: Handle<Self>, app: &App) -> ShortcutMap {
debug_assert!(ChangeNotifierData::debug_assert_not_disposed(
app.get(self).change_notifier_data()
));
app.get(self)
.registered_shortcuts
.iter()
.flat_map(|(_, shortcuts)| shortcuts.iter().cloned())
.collect()
}
pub fn add_all(
self: Handle<Self>,
app: &mut App,
value: ShortcutMap,
) -> Handle<ShortcutRegistryEntry> {
debug_assert!(ChangeNotifierData::debug_assert_not_disposed(
app.get(self).change_notifier_data()
));
debug_assert!(
!value.is_empty(),
"Cannot register an empty map of shortcuts"
);
let entry = app.create(ShortcutRegistryEntry { registry: self });
app.get_mut(self).registered_shortcuts.push((entry, value));
self.notify_listeners_next_frame(app);
entry
}
fn notify_listeners_next_frame(self: Handle<Self>, app: &mut App) {
if !app.get(self).notification_scheduled {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _duration| {
app.get_mut(self).notification_scheduled = false;
if !app.get(self).disposed {
self.notify_listeners(app);
}
}),
None,
);
app.get_mut(self).notification_scheduled = true;
}
}
pub fn of(app: &mut App, context: BuildContext) -> Handle<ShortcutRegistry> {
ShortcutRegistry::maybe_of(app, context).expect(
"Unable to find a ShortcutRegistrar widget in the context.\n\
ShortcutRegistrar.of() was called with a context that does not contain a \
ShortcutRegistrar widget.",
)
}
pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<ShortcutRegistry>> {
context
.depend_on_inherited_widget_of_exact_type::<ShortcutRegistrarScope>(app)
.map(|inherited| inherited.registry)
}
fn replace_all(
self: Handle<Self>,
app: &mut App,
entry: Handle<ShortcutRegistryEntry>,
value: ShortcutMap,
) {
debug_assert!(ChangeNotifierData::debug_assert_not_disposed(
app.get(self).change_notifier_data()
));
debug_assert!(self.debug_check_entry_is_valid(app, entry));
for registered in app.get_mut(self).registered_shortcuts.iter_mut() {
if registered.0 == entry {
registered.1 = value;
break;
}
}
self.notify_listeners_next_frame(app);
}
fn dispose_entry(self: Handle<Self>, app: &mut App, entry: Handle<ShortcutRegistryEntry>) {
debug_assert!(self.debug_check_entry_is_valid(app, entry));
let registered = &mut app.get_mut(self).registered_shortcuts;
let before = registered.len();
registered.retain(|(registered, _)| *registered != entry);
if app.get(self).registered_shortcuts.len() != before {
self.notify_listeners_next_frame(app);
}
}
fn debug_check_entry_is_valid(
self: Handle<Self>,
app: &App,
entry: Handle<ShortcutRegistryEntry>,
) -> bool {
if !app
.get(self)
.registered_shortcuts
.iter()
.any(|(registered, _)| *registered == entry)
{
assert!(
app.get(entry).registry != self,
"entry {entry:?} is invalid.\nThe entry has already been disposed of. Tokens \
are not valid after dispose is called on them, and should no longer be used."
);
panic!(
"Foreign entry {entry:?} used.\nThis entry was not created by this registry, \
it was created by {:?}, and should be used with that registry instead.",
app.get(entry).registry
);
}
true
}
}
impl ChangeNotifier for ShortcutRegistry {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
#[derive(Debug)]
pub struct ShortcutRegistrar {
pub key: Option<KeyRef>,
pub child: WidgetRef,
}
impl ShortcutRegistrar {
pub fn new<K>(child: impl IntoWidget<K>) -> ShortcutRegistrar {
ShortcutRegistrar {
key: None,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> ShortcutRegistrar {
self.key = Some(key);
self
}
}
impl StatefulWidget for ShortcutRegistrar {
type State = ShortcutRegistrarState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> ShortcutRegistrarState {
ShortcutRegistrarState {
state: StateData::new(),
registry: None,
manager: None,
shortcuts_changed: None,
}
}
}
pub struct ShortcutRegistrarState {
state: StateData<ShortcutRegistrar>,
registry: Option<Handle<ShortcutRegistry>>,
manager: Option<Handle<ShortcutManager>>,
shortcuts_changed: Option<Listener>,
}
impl ShortcutRegistrarState {
pub fn registry(self: Handle<Self>, app: &App) -> Handle<ShortcutRegistry> {
app.get(self).registry.expect("created in init_state")
}
pub fn manager(self: Handle<Self>, app: &App) -> Handle<ShortcutManager> {
app.get(self).manager.expect("created in init_state")
}
fn shortcuts_changed(self: Handle<Self>, app: &mut App) {
let registry = self.registry(app);
let shortcuts = registry.shortcuts(app);
self.manager(app).set_shortcuts(app, shortcuts);
}
}
impl State for ShortcutRegistrarState {
type Widget = ShortcutRegistrar;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let registry = ShortcutRegistry::new(app);
let manager = ShortcutManager::new(app);
let this = app.get_mut(self);
this.registry = Some(registry);
this.manager = Some(manager);
let listener = Listener::handle_method(self, ShortcutRegistrarState::shortcuts_changed);
app.get_mut(self).shortcuts_changed = Some(listener.clone());
registry.add_listener(app, listener);
}
fn dispose(self: Handle<Self>, app: &mut App) {
let registry = self.registry(app);
if let Some(listener) = app.get_mut(self).shortcuts_changed.take() {
registry.remove_listener(app, &listener);
}
registry.dispose(app);
let manager = self.manager(app);
app.get_mut(manager).change_notifier.dispose();
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let registry = self.registry(app);
let manager = self.manager(app);
let child = self.widget(app).child.clone();
ShortcutRegistrarScope {
registry,
child: Shortcuts::manager(manager.as_shortcut_manager(), child)
.debug_label("<Shortcut Registrar>")
.into_widget(),
}
.into_widget()
}
}
#[derive(Debug)]
struct ShortcutRegistrarScope {
registry: Handle<ShortcutRegistry>,
child: WidgetRef,
}
impl InheritedWidget for ShortcutRegistrarScope {
fn child(&self) -> &WidgetRef {
&self.child
}
fn update_should_notify(&self, old_widget: &ShortcutRegistrarScope) -> bool {
self.registry != old_widget.registry
}
}
#[cfg(test)]
mod tests {
use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::time::Duration;
use waft_services::{KeyDownEvent, KeyUpEvent, PhysicalKeyboardKey};
use super::*;
use crate::widgets::actions::{Action, AnyAction, CallbackAction, Intent};
use crate::widgets::basic::SizedBox;
use crate::widgets::focus_manager::tests::{app_with_view, mount};
#[derive(Debug)]
struct SaveIntent;
impl Intent for SaveIntent {
fn as_any(&self) -> &dyn Any {
self
}
}
fn key_down(physical: PhysicalKeyboardKey, logical: LogicalKeyboardKey) -> KeyEvent {
KeyEvent::Down(KeyDownEvent::new(physical, logical, Duration::ZERO))
}
fn key_up(physical: PhysicalKeyboardKey, logical: LogicalKeyboardKey) -> KeyEvent {
KeyEvent::Up(KeyUpEvent::new(physical, logical, Duration::ZERO))
}
fn save_action(app: &mut App, log: &Rc<RefCell<Vec<&'static str>>>) -> AnyAction {
let log = Rc::clone(log);
let action = CallbackAction::<SaveIntent>::new(
app,
Rc::new(move |_app, _intent| {
log.borrow_mut().push("saved");
None
}),
);
Action::as_action(action)
}
#[test]
fn a_shortcut_maps_a_key_event_to_an_intent_and_invokes_its_action() {
let cell = app_with_view();
let mut app = cell.borrow_mut();
let log: Rc<RefCell<Vec<&'static str>>> = Rc::default();
let action = save_action(&mut app, &log);
let shortcuts: ShortcutMap = vec![(
Rc::new(SingleActivator::new(LogicalKeyboardKey::KEY_S).control(true)),
Rc::new(SaveIntent),
)];
drop(app);
mount(
&cell,
Shortcuts::new(
shortcuts,
Actions::new(
HashMap::from([(TypeId::of::<SaveIntent>(), action)]),
Focus::new(SizedBox::shrink()).autofocus(true),
),
)
.into_widget(),
);
let mut app = cell.borrow_mut();
let keyboard = HardwareKeyboard::instance(&mut app);
assert!(!keyboard.handle_key_event(
&mut app,
&key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S)
));
assert!(log.borrow().is_empty());
keyboard.handle_key_event(
&mut app,
&key_up(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S),
);
keyboard.handle_key_event(
&mut app,
&key_down(
PhysicalKeyboardKey::CONTROL_LEFT,
LogicalKeyboardKey::CONTROL_LEFT,
),
);
assert!(keyboard.handle_key_event(
&mut app,
&key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S)
));
assert_eq!(*log.borrow(), ["saved"]);
}
#[test]
fn a_logical_key_set_activates_on_the_whole_combination() {
let cell = app_with_view();
let mut app = cell.borrow_mut();
let log: Rc<RefCell<Vec<&'static str>>> = Rc::default();
let action = save_action(&mut app, &log);
let shortcuts: ShortcutMap = vec![(
Rc::new(LogicalKeySet::new(
LogicalKeyboardKey::CONTROL,
Some(LogicalKeyboardKey::KEY_S),
None,
None,
)),
Rc::new(SaveIntent),
)];
drop(app);
mount(
&cell,
Shortcuts::new(
shortcuts,
Actions::new(
HashMap::from([(TypeId::of::<SaveIntent>(), action)]),
Focus::new(SizedBox::shrink()).autofocus(true),
),
)
.into_widget(),
);
let mut app = cell.borrow_mut();
let keyboard = HardwareKeyboard::instance(&mut app);
keyboard.handle_key_event(
&mut app,
&key_down(
PhysicalKeyboardKey::CONTROL_LEFT,
LogicalKeyboardKey::CONTROL_LEFT,
),
);
assert!(keyboard.handle_key_event(
&mut app,
&key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S)
));
assert_eq!(*log.borrow(), ["saved"]);
}
#[test]
fn callback_shortcuts_call_every_binding_that_accepts_the_event() {
let cell = app_with_view();
let app = cell.borrow();
let log: Rc<RefCell<Vec<&'static str>>> = Rc::default();
let first = Rc::clone(&log);
let second = Rc::clone(&log);
let bindings: Vec<(ShortcutActivatorRef, Listener)> = vec![
(
Rc::new(SingleActivator::new(LogicalKeyboardKey::KEY_A)),
Listener::new(move |_app| first.borrow_mut().push("first")),
),
(
Rc::new(CharacterActivator::new("a")),
Listener::new(move |_app| second.borrow_mut().push("second")),
),
];
drop(app);
mount(
&cell,
CallbackShortcuts::new(bindings, Focus::new(SizedBox::shrink()).autofocus(true))
.into_widget(),
);
let mut app = cell.borrow_mut();
let keyboard = HardwareKeyboard::instance(&mut app);
let event = KeyEvent::Down(
KeyDownEvent::new(
PhysicalKeyboardKey::KEY_A,
LogicalKeyboardKey::KEY_A,
Duration::ZERO,
)
.character("a"),
);
assert!(keyboard.handle_key_event(&mut app, &event));
assert_eq!(*log.borrow(), ["first", "second"]);
}
#[test]
fn the_manager_reindexes_and_notifies_when_its_shortcuts_change() {
let cell = app_with_view();
mount(&cell, SizedBox::shrink().into_widget());
let mut app = cell.borrow_mut();
let manager = ShortcutManager::new(&mut app);
let notifications: Rc<RefCell<u32>> = Rc::default();
let sink = Rc::clone(¬ifications);
manager.add_listener(&mut app, Listener::new(move |_app| *sink.borrow_mut() += 1));
let activator: ShortcutActivatorRef =
Rc::new(SingleActivator::new(LogicalKeyboardKey::KEY_S));
let intent: IntentRef = Rc::new(SaveIntent);
let shortcuts: ShortcutMap = vec![(Rc::clone(&activator), Rc::clone(&intent))];
manager.set_shortcuts(&mut app, shortcuts.clone());
assert_eq!(*notifications.borrow(), 1);
manager.set_shortcuts(&mut app, shortcuts);
assert_eq!(*notifications.borrow(), 1);
let keyboard = HardwareKeyboard::instance(&mut app);
let found = manager.find(
&mut app,
&key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S),
keyboard,
);
assert!(found.is_some_and(|found| Rc::ptr_eq(&found, &intent)));
}
#[test]
fn the_registry_merges_its_entries_into_the_registrars_manager() {
let cell = app_with_view();
let mut app = cell.borrow_mut();
let log: Rc<RefCell<Vec<&'static str>>> = Rc::default();
let action = save_action(&mut app, &log);
let captured: Rc<std::cell::Cell<Option<BuildContext>>> = Rc::default();
let sink = Rc::clone(&captured);
drop(app);
mount(
&cell,
ShortcutRegistrar::new(Actions::new(
HashMap::from([(TypeId::of::<SaveIntent>(), action)]),
crate::widgets::basic::Builder::new(move |_app, context| {
sink.set(Some(context));
Focus::new(SizedBox::shrink()).autofocus(true).into_widget()
}),
))
.into_widget(),
);
let mut app = cell.borrow_mut();
let context = captured.get().expect("the builder ran");
let registry = ShortcutRegistry::of(&mut app, context);
let entry = registry.add_all(
&mut app,
vec![(
Rc::new(SingleActivator::new(LogicalKeyboardKey::KEY_S)),
Rc::new(SaveIntent),
)],
);
crate::test_harness::pump_every_view(&mut app, std::time::Duration::ZERO);
let keyboard = HardwareKeyboard::instance(&mut app);
assert!(keyboard.handle_key_event(
&mut app,
&key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S)
));
assert_eq!(*log.borrow(), ["saved"]);
entry.dispose(&mut app);
crate::test_harness::pump_every_view(&mut app, std::time::Duration::ZERO);
log.borrow_mut().clear();
keyboard.handle_key_event(
&mut app,
&key_up(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S),
);
assert!(!keyboard.handle_key_event(
&mut app,
&key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S)
));
assert!(log.borrow().is_empty());
}
}