use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;
use waft_embedder::TargetPlatform;
use waft_foundation::{App, Handle, Listener, OptionRetained, Ref, ValueChanged};
use crate::framework::{
AnyElement, BuildContext, ComponentElement, ComponentElementData, Element, ElementData,
ElementLifecycle, IntoWidget, KeyRef, ProxyElement, Slot, State, StateData, StatefulWidget,
Widget, WidgetKind, WidgetRef, component_element_overrides, downcast_widget,
};
use crate::widgets::basic::Semantics;
use crate::widgets::focus_manager::{
AnyFocusNode, FocusAttachment, FocusNode, FocusNodeLeaf, FocusNodeRef, FocusOnKeyEventCallback,
FocusScopeNode,
};
pub struct Focus {
pub key: Option<KeyRef>,
pub parent_node: Option<FocusNodeRef>,
pub child: WidgetRef,
pub focus_node: Option<FocusNodeRef>,
pub autofocus: bool,
pub on_focus_change: Option<ValueChanged<bool>>,
pub include_semantics: bool,
using_external_focus: bool,
on_key_event: Option<FocusOnKeyEventCallback>,
can_request_focus: Option<bool>,
skip_traversal: Option<bool>,
descendants_are_focusable: Option<bool>,
descendants_are_traversable: Option<bool>,
debug_label: Option<String>,
}
impl Focus {
pub fn new<K>(child: impl IntoWidget<K>) -> Focus {
Focus {
key: None,
parent_node: None,
child: child.into_widget(),
focus_node: None,
autofocus: false,
on_focus_change: None,
include_semantics: true,
using_external_focus: false,
on_key_event: None,
can_request_focus: None,
skip_traversal: None,
descendants_are_focusable: None,
descendants_are_traversable: None,
debug_label: None,
}
}
pub fn with_external_focus_node<K>(
child: impl IntoWidget<K>,
focus_node: FocusNodeRef,
) -> Focus {
Focus {
focus_node: Some(focus_node),
using_external_focus: true,
..Focus::new(child)
}
}
pub fn key(mut self, key: KeyRef) -> Focus {
self.key = Some(key);
self
}
pub fn parent_node(mut self, parent_node: FocusNodeRef) -> Focus {
self.parent_node = Some(parent_node);
self
}
pub fn focus_node(mut self, focus_node: FocusNodeRef) -> Focus {
self.focus_node = Some(focus_node);
self
}
pub fn autofocus(mut self, autofocus: bool) -> Focus {
self.autofocus = autofocus;
self
}
pub fn on_focus_change(mut self, on_focus_change: impl Fn(&mut App, bool) + 'static) -> Focus {
self.on_focus_change = Some(Rc::new(on_focus_change));
self
}
pub fn on_key_event(mut self, on_key_event: FocusOnKeyEventCallback) -> Focus {
self.on_key_event = Some(on_key_event);
self
}
pub fn can_request_focus(mut self, can_request_focus: bool) -> Focus {
self.can_request_focus = Some(can_request_focus);
self
}
pub fn skip_traversal(mut self, skip_traversal: bool) -> Focus {
self.skip_traversal = Some(skip_traversal);
self
}
pub fn descendants_are_focusable(mut self, descendants_are_focusable: bool) -> Focus {
self.descendants_are_focusable = Some(descendants_are_focusable);
self
}
pub fn descendants_are_traversable(mut self, descendants_are_traversable: bool) -> Focus {
self.descendants_are_traversable = Some(descendants_are_traversable);
self
}
pub fn include_semantics(mut self, include_semantics: bool) -> Focus {
self.include_semantics = include_semantics;
self
}
pub fn debug_label(mut self, debug_label: impl Into<String>) -> Focus {
self.debug_label = Some(debug_label.into());
self
}
pub fn get_on_key_event(&self, app: &App) -> Option<FocusOnKeyEventCallback> {
self.on_key_event.clone().or_else(|| {
self.focus_node
.handle()
.and_then(|node| node.on_key_event(app))
})
}
pub fn get_can_request_focus(&self, app: &mut App) -> bool {
let (explicit, node) = (self.can_request_focus, self.focus_node.handle());
Focus::resolve_can_request_focus(explicit, node, app)
}
fn resolve_can_request_focus(
explicit: Option<bool>,
node: Option<AnyFocusNode>,
app: &mut App,
) -> bool {
explicit
.or_else(|| node.map(|node| node.can_request_focus(app)))
.unwrap_or(true)
}
pub fn get_skip_traversal(&self, app: &mut App) -> bool {
let (explicit, node) = (self.skip_traversal, self.focus_node.handle());
Focus::resolve_skip_traversal(explicit, node, app)
}
fn resolve_skip_traversal(
explicit: Option<bool>,
node: Option<AnyFocusNode>,
app: &mut App,
) -> bool {
explicit
.or_else(|| node.map(|node| node.skip_traversal(app)))
.unwrap_or(false)
}
pub fn get_descendants_are_focusable(&self, app: &App) -> bool {
self.descendants_are_focusable
.or_else(|| {
self.focus_node
.handle()
.map(|node| node.descendants_are_focusable(app))
})
.unwrap_or(true)
}
pub fn get_descendants_are_traversable(&self, app: &App) -> bool {
self.descendants_are_traversable
.or_else(|| {
self.focus_node
.handle()
.map(|node| node.descendants_are_traversable(app))
})
.unwrap_or(true)
}
pub fn get_debug_label(&self, app: &App) -> Option<String> {
self.debug_label.clone().or_else(|| {
self.focus_node
.handle()
.and_then(|node| node.debug_label(app))
})
}
pub fn of(
app: &mut App,
context: BuildContext,
scope_ok: bool,
create_dependency: bool,
) -> AnyFocusNode {
let node = Focus::maybe_of(app, context, scope_ok, create_dependency);
let node = node.expect(
"Focus.of() was called with a context that does not contain a Focus widget.\n\
No Focus widget ancestor could be found starting from the context that was passed \
to Focus.of(). This can happen because you are using a widget that looks for a \
Focus ancestor, and do not have a Focus widget descendant in the nearest \
FocusScope.",
);
debug_assert!(
scope_ok || node.as_scope().is_none(),
"Focus.of() was called with a context that does not contain a Focus between the \
given context and the nearest FocusScope widget."
);
node
}
pub fn maybe_of(
app: &mut App,
context: BuildContext,
scope_ok: bool,
create_dependency: bool,
) -> Option<AnyFocusNode> {
let node = if create_dependency {
context
.depend_on_inherited_widget_of_exact_type::<FocusInheritedScope>(app)
.map(|scope| scope.node.handle())
} else {
context
.get_inherited_widget_of_exact_type::<FocusInheritedScope>(app)
.map(|scope| scope.node.handle())
}?;
match node.as_scope() {
Some(_) if !scope_ok => None,
_ => Some(node),
}
}
pub fn is_at(app: &mut App, context: BuildContext) -> bool {
match Focus::maybe_of(app, context, false, true) {
Some(node) => node.has_focus(app),
None => false,
}
}
}
impl fmt::Debug for Focus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Focus")
.field("debugLabel", &self.debug_label)
.field("autofocus", &self.autofocus)
.field("focusNode", &self.focus_node)
.finish_non_exhaustive()
}
}
impl StatefulWidget for Focus {
type State = FocusState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> FocusState {
FocusState {
state: StateData::new(),
focus: FocusStateData::new(),
}
}
}
pub struct FocusStateData {
internal_node: Option<FocusNodeRef>,
had_primary_focus: bool,
could_request_focus: bool,
descendants_were_focusable: bool,
descendants_were_traversable: bool,
did_autofocus: bool,
focus_attachment: Option<Ref<FocusAttachment>>,
}
impl FocusStateData {
pub fn new() -> FocusStateData {
FocusStateData {
internal_node: None,
had_primary_focus: false,
could_request_focus: false,
descendants_were_focusable: false,
descendants_were_traversable: false,
did_autofocus: false,
focus_attachment: None,
}
}
}
impl Default for FocusStateData {
fn default() -> FocusStateData {
FocusStateData::new()
}
}
pub trait FocusStateLeaf: State + Sized + 'static {
fn focus_state_data(self: Handle<Self>, app: &App) -> &FocusStateData;
fn focus_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut FocusStateData;
fn focus_widget(self: Handle<Self>, app: &App) -> &Focus;
fn create_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef;
fn widget_can_request_focus(self: Handle<Self>, app: &mut App) -> bool {
let widget = self.focus_widget(app);
let (explicit, node) = (widget.can_request_focus, widget.focus_node.handle());
Focus::resolve_can_request_focus(explicit, node, app)
}
fn widget_skip_traversal(self: Handle<Self>, app: &mut App) -> bool {
let widget = self.focus_widget(app);
let (explicit, node) = (widget.skip_traversal, widget.focus_node.handle());
Focus::resolve_skip_traversal(explicit, node, app)
}
fn focus_node(self: Handle<Self>, app: &mut App) -> AnyFocusNode {
if let Some(node) = self.focus_widget(app).focus_node.handle() {
return node;
}
if let Some(node) = self.focus_state_data(app).internal_node.handle() {
return node;
}
let node = self.create_node(app);
let handle = node.handle();
self.focus_state_data_mut(app).internal_node = Some(node);
handle
}
fn kept_focus_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
let node = self.focus_node(app);
node.keep(app)
}
fn init_node(self: Handle<Self>, app: &mut App) {
let focus_node = self.focus_node(app);
if !self.focus_widget(app).using_external_focus {
let descendants_are_focusable =
self.focus_widget(app).get_descendants_are_focusable(app);
focus_node.set_descendants_are_focusable(app, descendants_are_focusable);
let descendants_are_traversable =
self.focus_widget(app).get_descendants_are_traversable(app);
focus_node.set_descendants_are_traversable(app, descendants_are_traversable);
let skip_traversal = self.widget_skip_traversal(app);
focus_node.set_skip_traversal(app, skip_traversal);
if let Some(can_request_focus) = self.focus_widget(app).can_request_focus {
focus_node.set_can_request_focus(app, can_request_focus);
}
}
let could_request_focus = focus_node.can_request_focus(app);
let descendants_were_focusable = focus_node.descendants_are_focusable(app);
let descendants_were_traversable = focus_node.descendants_are_traversable(app);
let had_primary_focus = focus_node.has_primary_focus(app);
let data = self.focus_state_data_mut(app);
data.could_request_focus = could_request_focus;
data.descendants_were_focusable = descendants_were_focusable;
data.descendants_were_traversable = descendants_were_traversable;
data.had_primary_focus = had_primary_focus;
let context = self.context(app);
let on_key_event = self.focus_widget(app).get_on_key_event(app);
let attachment = focus_node.attach(app, Some(context), on_key_event);
self.focus_state_data_mut(app).focus_attachment = Some(attachment);
focus_node.add_listener(
app,
Listener::handle_method(self, Self::handle_focus_changed),
);
}
fn dispose_focus(self: Handle<Self>, app: &mut App) {
let focus_node = self.focus_node(app);
focus_node.remove_listener(
app,
&Listener::handle_method(self, Self::handle_focus_changed),
);
self.focus_state_data(app)
.focus_attachment
.handle()
.expect("attached in init_state")
.detach(app);
if let Some(internal_node) = self.focus_state_data(app).internal_node.handle() {
internal_node.dispose(app);
}
}
fn did_change_dependencies_focus(self: Handle<Self>, app: &mut App) {
if let Some(attachment) = self.focus_state_data(app).focus_attachment.handle() {
attachment.reparent(app, None);
}
self.handle_autofocus(app);
}
fn handle_autofocus(self: Handle<Self>, app: &mut App) {
if !self.focus_state_data(app).did_autofocus && self.focus_widget(app).autofocus {
let context = self.context(app);
let scope = FocusScope::of(app, context, true);
let focus_node = self.focus_node(app);
scope.autofocus(app, focus_node);
self.focus_state_data_mut(app).did_autofocus = true;
}
}
fn deactivate_focus(self: Handle<Self>, app: &mut App) {
if let Some(attachment) = self.focus_state_data(app).focus_attachment.handle() {
attachment.reparent(app, None);
}
self.focus_state_data_mut(app).did_autofocus = false;
}
fn did_update_widget_focus(self: Handle<Self>, app: &mut App, old_widget: &Focus) {
if cfg!(debug_assertions) {
let widget_label = self.focus_widget(app).debug_label.clone();
if old_widget.focus_node == self.focus_widget(app).focus_node
&& !self.focus_widget(app).using_external_focus
&& old_widget.debug_label != widget_label
{
let focus_node = self.focus_node(app);
let label = self.focus_widget(app).get_debug_label(app);
focus_node.set_debug_label(app, label);
}
}
if old_widget.focus_node == self.focus_widget(app).focus_node {
if !self.focus_widget(app).using_external_focus {
let focus_node = self.focus_node(app);
let on_key_event = self.focus_widget(app).get_on_key_event(app);
let same_handler = match (&on_key_event, &focus_node.on_key_event(app)) {
(None, None) => true,
(Some(a), Some(b)) => Rc::ptr_eq(a, b),
_ => false,
};
if !same_handler {
focus_node.set_on_key_event(app, on_key_event);
}
let skip_traversal = self.widget_skip_traversal(app);
focus_node.set_skip_traversal(app, skip_traversal);
if let Some(can_request_focus) = self.focus_widget(app).can_request_focus {
focus_node.set_can_request_focus(app, can_request_focus);
}
let descendants_are_focusable =
self.focus_widget(app).get_descendants_are_focusable(app);
focus_node.set_descendants_are_focusable(app, descendants_are_focusable);
let descendants_are_traversable =
self.focus_widget(app).get_descendants_are_traversable(app);
focus_node.set_descendants_are_traversable(app, descendants_are_traversable);
}
} else {
self.focus_state_data(app)
.focus_attachment
.handle()
.expect("attached in init_state")
.detach(app);
if let Some(old_node) = old_widget.focus_node.handle() {
old_node.remove_listener(
app,
&Listener::handle_method(self, Self::handle_focus_changed),
);
}
self.init_node(app);
}
if old_widget.autofocus != self.focus_widget(app).autofocus {
self.handle_autofocus(app);
}
}
fn handle_focus_changed(self: Handle<Self>, app: &mut App) {
let focus_node = self.focus_node(app);
let has_primary_focus = focus_node.has_primary_focus(app);
let can_request_focus = focus_node.can_request_focus(app);
let descendants_are_focusable = focus_node.descendants_are_focusable(app);
let descendants_are_traversable = focus_node.descendants_are_traversable(app);
if let Some(on_focus_change) = self.focus_widget(app).on_focus_change.clone() {
let has_focus = focus_node.has_focus(app);
on_focus_change(app, has_focus);
}
if self.focus_state_data(app).had_primary_focus != has_primary_focus {
self.set_state(app, |state| {
state.focus_state_data_field().had_primary_focus = has_primary_focus;
});
}
if self.focus_state_data(app).could_request_focus != can_request_focus {
self.set_state(app, |state| {
state.focus_state_data_field().could_request_focus = can_request_focus;
});
}
if self.focus_state_data(app).descendants_were_focusable != descendants_are_focusable {
self.set_state(app, |state| {
state.focus_state_data_field().descendants_were_focusable =
descendants_are_focusable;
});
}
if self.focus_state_data(app).descendants_were_traversable != descendants_are_traversable {
self.set_state(app, |state| {
state.focus_state_data_field().descendants_were_traversable =
descendants_are_traversable;
});
}
}
fn focus_state_data_field(&mut self) -> &mut FocusStateData;
}
pub struct FocusState {
state: StateData<Focus>,
focus: FocusStateData,
}
impl FocusStateLeaf for FocusState {
fn focus_state_data(self: Handle<Self>, app: &App) -> &FocusStateData {
&app.get(self).focus
}
fn focus_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut FocusStateData {
&mut app.get_mut(self).focus
}
fn focus_state_data_field(&mut self) -> &mut FocusStateData {
&mut self.focus
}
fn focus_widget(self: Handle<Self>, app: &App) -> &Focus {
self.widget(app)
}
fn create_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
let node = FocusNode::new(app);
let label = self.widget(app).get_debug_label(app);
node.set_debug_label(app, label);
let can_request_focus = self.widget_can_request_focus(app);
node.set_can_request_focus(app, can_request_focus);
let descendants_are_focusable = self.widget(app).get_descendants_are_focusable(app);
node.set_descendants_are_focusable(app, descendants_are_focusable);
let descendants_are_traversable = self.widget(app).get_descendants_are_traversable(app);
node.set_descendants_are_traversable(app, descendants_are_traversable);
let skip_traversal = self.widget_skip_traversal(app);
node.set_skip_traversal(app, skip_traversal);
node.into_erased()
}
}
impl State for FocusState {
type Widget = Focus;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
self.init_node(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
self.dispose_focus(app);
}
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
self.did_change_dependencies_focus(app);
}
fn deactivate(self: Handle<Self>, app: &mut App) {
self.deactivate_focus(app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Focus) {
self.did_update_widget_focus(app, old_widget);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let parent_node = self.widget(app).parent_node.handle();
self.focus_state_data(app)
.focus_attachment
.handle()
.expect("attached in init_state")
.reparent(app, parent_node);
let mut child = self.widget(app).child.clone();
let node = self.kept_focus_node(app);
if self.widget(app).include_semantics {
let could_request_focus = self.focus_state_data(app).could_request_focus;
let had_primary_focus = self.focus_state_data(app).had_primary_focus;
let mut semantics = Semantics::new().focusable(could_request_focus);
if app.platform().target_platform() != TargetPlatform::IOS && could_request_focus {
let node = node.clone();
semantics =
semantics.on_focus(Rc::new(move |app: &mut App| node.request_focus(app, None)));
}
if could_request_focus {
semantics = semantics.focused(had_primary_focus);
}
child = semantics.child(child).into_widget();
}
FocusInheritedScope { node, child }.into_widget()
}
}
pub struct FocusScope {
focus: Focus,
}
impl FocusScope {
pub fn new<K>(child: impl IntoWidget<K>) -> FocusScope {
FocusScope {
focus: Focus::new(child),
}
}
pub fn with_external_focus_node<K>(
child: impl IntoWidget<K>,
focus_scope_node: Ref<FocusScopeNode>,
) -> FocusScope {
FocusScope {
focus: Focus::with_external_focus_node(child, focus_scope_node.into_erased()),
}
}
pub fn node(mut self, node: Ref<FocusScopeNode>) -> FocusScope {
self.focus.focus_node = Some(node.into_erased());
self
}
pub fn key(mut self, key: KeyRef) -> FocusScope {
self.focus = self.focus.key(key);
self
}
pub fn parent_node(mut self, parent_node: FocusNodeRef) -> FocusScope {
self.focus = self.focus.parent_node(parent_node);
self
}
pub fn autofocus(mut self, autofocus: bool) -> FocusScope {
self.focus = self.focus.autofocus(autofocus);
self
}
pub fn on_focus_change(
mut self,
on_focus_change: impl Fn(&mut App, bool) + 'static,
) -> FocusScope {
self.focus = self.focus.on_focus_change(on_focus_change);
self
}
pub fn on_key_event(mut self, on_key_event: FocusOnKeyEventCallback) -> FocusScope {
self.focus = self.focus.on_key_event(on_key_event);
self
}
pub fn can_request_focus(mut self, can_request_focus: bool) -> FocusScope {
self.focus = self.focus.can_request_focus(can_request_focus);
self
}
pub fn skip_traversal(mut self, skip_traversal: bool) -> FocusScope {
self.focus = self.focus.skip_traversal(skip_traversal);
self
}
pub fn descendants_are_focusable(mut self, descendants_are_focusable: bool) -> FocusScope {
self.focus = self
.focus
.descendants_are_focusable(descendants_are_focusable);
self
}
pub fn descendants_are_traversable(mut self, descendants_are_traversable: bool) -> FocusScope {
self.focus = self
.focus
.descendants_are_traversable(descendants_are_traversable);
self
}
pub fn include_semantics(mut self, include_semantics: bool) -> FocusScope {
self.focus = self.focus.include_semantics(include_semantics);
self
}
pub fn debug_label(mut self, debug_label: impl Into<String>) -> FocusScope {
self.focus = self.focus.debug_label(debug_label);
self
}
pub fn focus(&self) -> &Focus {
&self.focus
}
pub fn of(
app: &mut App,
context: BuildContext,
create_dependency: bool,
) -> Handle<FocusScopeNode> {
Focus::maybe_of(app, context, true, create_dependency)
.and_then(|node| node.nearest_scope(app))
.unwrap_or_else(|| {
let owner = context
.owner(app)
.expect("a mounted element has a build owner");
let manager = owner.focus_manager(app);
manager.root_scope(app).handle()
})
}
}
impl fmt::Debug for FocusScope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FocusScope")
.field("focus", &self.focus)
.finish()
}
}
impl StatefulWidget for FocusScope {
type State = FocusScopeState;
fn key(&self) -> Option<&KeyRef> {
self.focus.key.as_ref()
}
fn create_state(&self) -> FocusScopeState {
FocusScopeState {
state: StateData::new(),
focus: FocusStateData::new(),
}
}
}
pub struct FocusScopeState {
state: StateData<FocusScope>,
focus: FocusStateData,
}
impl FocusStateLeaf for FocusScopeState {
fn focus_state_data(self: Handle<Self>, app: &App) -> &FocusStateData {
&app.get(self).focus
}
fn focus_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut FocusStateData {
&mut app.get_mut(self).focus
}
fn focus_state_data_field(&mut self) -> &mut FocusStateData {
&mut self.focus
}
fn focus_widget(self: Handle<Self>, app: &App) -> &Focus {
&self.widget(app).focus
}
fn create_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
let node = FocusScopeNode::new(app);
let label = self.focus_widget(app).get_debug_label(app);
node.set_debug_label(app, label);
let can_request_focus = self.widget_can_request_focus(app);
node.set_can_request_focus(app, can_request_focus);
let skip_traversal = self.widget_skip_traversal(app);
node.set_skip_traversal(app, skip_traversal);
node.into_erased()
}
}
impl State for FocusScopeState {
type Widget = FocusScope;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
self.init_node(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
self.dispose_focus(app);
}
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
self.did_change_dependencies_focus(app);
}
fn deactivate(self: Handle<Self>, app: &mut App) {
self.deactivate_focus(app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FocusScope) {
self.did_update_widget_focus(app, &old_widget.focus);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let parent_node = self.widget(app).focus.parent_node.handle();
self.focus_state_data(app)
.focus_attachment
.handle()
.expect("attached in init_state")
.reparent(app, parent_node);
let child = self.widget(app).focus.child.clone();
let node = self.kept_focus_node(app);
let result = FocusInheritedScope { node, child }.into_widget();
if self.widget(app).focus.include_semantics {
return Semantics::new()
.explicit_child_nodes(true)
.child(result)
.into_widget();
}
result
}
}
struct FocusInheritedScope {
node: FocusNodeRef,
child: WidgetRef,
}
impl FocusInheritedScope {
fn into_widget(self) -> WidgetRef {
Rc::new(self)
}
}
impl fmt::Debug for FocusInheritedScope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("_FocusInheritedScope")
.field("node", &self.node)
.finish_non_exhaustive()
}
}
impl crate::framework::InheritedWidget for FocusInheritedScope {
fn child(&self) -> &WidgetRef {
&self.child
}
fn update_should_notify(&self, old_widget: &FocusInheritedScope) -> bool {
old_widget.node != self.node
}
}
impl Widget for FocusInheritedScope {
fn key(&self) -> Option<&KeyRef> {
None
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
FocusInheritedScopeElement::new(app, this).as_element()
}
fn as_any(&self) -> &dyn Any {
self
}
fn widget_type(&self) -> TypeId {
TypeId::of::<FocusInheritedScope>()
}
fn kind(&self) -> WidgetKind {
WidgetKind::Other
}
}
struct FocusInheritedScopeElement {
element: ElementData,
component: ComponentElementData,
dependents: HashMap<AnyElement, Option<Rc<dyn Any>>>,
dirty: bool,
}
impl FocusInheritedScopeElement {
fn new(app: &mut App, widget: WidgetRef) -> Handle<Self> {
let node = FocusInheritedScopeElement::widget_of(&widget).node.handle();
let this = app
.create(FocusInheritedScopeElement {
element: ElementData::new(widget),
component: ComponentElementData::default(),
dependents: HashMap::new(),
dirty: false,
})
.into_tree_node(app);
node.add_listener(
app,
Listener::handle_method(this, FocusInheritedScopeElement::handle_update),
);
this
}
fn widget_of(widget: &WidgetRef) -> &FocusInheritedScope {
downcast_widget::<FocusInheritedScope>(&**widget)
.expect("a FocusInheritedScopeElement holds its FocusInheritedScope")
}
fn widget(self: Handle<Self>, app: &App) -> &FocusInheritedScope {
FocusInheritedScopeElement::widget_of(self.as_element().widget(app))
}
fn handle_update(self: Handle<Self>, app: &mut App) {
app.get_mut(self).dirty = true;
self.as_element().mark_needs_build(app);
}
fn notify_clients(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
let dependents: Vec<AnyElement> = app.get(self).dependents.keys().copied().collect();
for dependent in dependents {
let _ = &old_widget;
dependent.did_change_dependencies(app);
}
app.get_mut(self).dirty = false;
}
}
impl ComponentElement for FocusInheritedScopeElement {
fn component_data(self: Handle<Self>, app: &App) -> &ComponentElementData {
&app.get(self).component
}
fn component_data_mut(self: Handle<Self>, app: &mut App) -> &mut ComponentElementData {
&mut app.get_mut(self).component
}
fn build(self: Handle<Self>, app: &mut App) -> WidgetRef {
if app.get(self).dirty {
let widget = self.as_element().widget(app).clone();
FocusInheritedScopeElement::notify_clients(self, app, widget);
}
self.proxied_child(app)
}
}
impl ProxyElement for FocusInheritedScopeElement {
fn proxied_child(self: Handle<Self>, app: &App) -> WidgetRef {
self.widget(app).child.clone()
}
fn updated(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
let old_node = FocusInheritedScopeElement::widget_of(&old_widget)
.node
.handle();
if old_node != self.widget(app).node {
FocusInheritedScopeElement::notify_clients(self, app, old_widget);
}
}
fn notify_clients(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
FocusInheritedScopeElement::notify_clients(self, app, old_widget);
}
}
impl Element for FocusInheritedScopeElement {
crate::element_accessors!();
component_element_overrides!();
const IS_INHERITED_ELEMENT: bool = true;
fn mount(
self: Handle<Self>,
app: &mut App,
parent: Option<AnyElement>,
new_slot: Option<Slot>,
) {
ComponentElement::mount(self, app, parent, new_slot);
}
fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
let old_node = self.widget(app).node.handle();
let new_node = FocusInheritedScopeElement::widget_of(&new_widget)
.node
.handle();
if old_node != new_node {
old_node.remove_listener(
app,
&Listener::handle_method(self, FocusInheritedScopeElement::handle_update),
);
new_node.add_listener(
app,
Listener::handle_method(self, FocusInheritedScopeElement::handle_update),
);
}
ProxyElement::update(self, app, new_widget);
}
fn perform_rebuild(self: Handle<Self>, app: &mut App) {
ComponentElement::perform_rebuild(self, app);
}
fn unmount(self: Handle<Self>, app: &mut App) {
let node = self.widget(app).node.handle();
node.remove_listener(
app,
&Listener::handle_method(self, FocusInheritedScopeElement::handle_update),
);
crate::framework::ElementBase::unmount(self, app);
}
fn update_inheritance(self: Handle<Self>, app: &mut App) {
debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Active);
let incoming = self
.as_element()
.parent(app)
.and_then(|parent| parent.inherited_elements(app));
let mut widgets: HashMap<TypeId, AnyElement> = incoming
.map(|incoming| (*incoming).clone())
.unwrap_or_default();
widgets.insert(TypeId::of::<FocusInheritedScope>(), self.as_element());
self.as_element()
.set_inherited_elements(app, Some(Rc::new(widgets)));
}
fn debug_deactivated(self: Handle<Self>, app: &mut App) {
debug_assert!(app.get(self).dependents.is_empty());
debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Inactive);
}
fn update_dependencies(
self: Handle<Self>,
app: &mut App,
dependent: AnyElement,
_aspect: Option<Rc<dyn Any>>,
) {
app.get_mut(self).dependents.insert(dependent, None);
}
fn remove_dependent(self: Handle<Self>, app: &mut App, dependent: AnyElement) {
app.get_mut(self).dependents.remove(&dependent);
}
}
#[derive(Debug)]
pub struct ExcludeFocus {
pub key: Option<KeyRef>,
pub excluding: bool,
pub child: WidgetRef,
}
impl ExcludeFocus {
pub fn new<K>(child: impl IntoWidget<K>) -> ExcludeFocus {
ExcludeFocus {
key: None,
excluding: true,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> ExcludeFocus {
self.key = Some(key);
self
}
pub fn excluding(mut self, excluding: bool) -> ExcludeFocus {
self.excluding = excluding;
self
}
}
impl crate::framework::StatelessWidget for ExcludeFocus {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
Focus::new(self.child.clone())
.can_request_focus(false)
.skip_traversal(true)
.include_semantics(false)
.descendants_are_focusable(!self.excluding)
.into_widget()
}
}
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
use super::*;
use crate::framework::GlobalKey;
use crate::testing::test_widgets;
use crate::widgets::basic::{Builder, Center, Padding, SizedBox};
use crate::widgets::focus_manager::{FocusManager, FocusNode, KeyEventResult};
use crate::widgets::value_listenable_builder::ValueListenableBuilder;
use waft_foundation::ValueNotifier;
type Captured = Rc<Cell<Option<AnyFocusNode>>>;
fn probe(captured: &Captured) -> WidgetRef {
let captured = Rc::clone(captured);
Builder::new(move |app, context| {
captured.set(Focus::maybe_of(app, context, false, true));
SizedBox::shrink().into_widget()
})
.into_widget()
}
#[test]
fn a_kept_node_remounts_after_the_focus_it_hung_under_is_freed() {
test_widgets(|tester| {
let mut app = tester.cell.borrow_mut();
let node: FocusNodeRef = FocusNode::new(&mut app).into_erased();
let layout = app.create(ValueNotifier::new(0));
drop(app);
let widget = ValueListenableBuilder::new(Rc::new(layout.clone()), {
let node = node.clone();
move |_app, _context, layout: &i32, _child| match layout {
0 => Focus::new(Focus::new(SizedBox::shrink()).focus_node(node.clone()))
.debug_label("outer")
.into_widget(),
1 => SizedBox::shrink().into_widget(),
_ => Focus::new(SizedBox::shrink())
.focus_node(node.clone())
.into_widget(),
}
});
tester.pump_widget(widget.into_widget());
let mut app = tester.cell.borrow_mut();
let outer = node
.parent(&app)
.expect("the node hangs under the outer Focus");
assert!(node.ancestors(&mut app).contains(&outer));
layout.set_value(&mut app, 1);
drop(app);
tester.pump();
let app = tester.cell.borrow();
assert_eq!(node.parent(&app), None);
drop(app);
tester.cell.checkpoint();
let mut app = tester.cell.borrow_mut();
assert!(!app.contains(outer));
layout.set_value(&mut app, 2);
drop(app);
tester.pump();
let mut app = tester.cell.borrow_mut();
assert!(!node.skip_traversal(&mut app));
assert!(!node.ancestors(&mut app).contains(&outer));
});
}
#[test]
fn autofocus_gives_the_focus_widgets_node_the_primary_focus() {
test_widgets(|tester| {
let app = tester.cell.borrow();
let captured: Captured = Rc::default();
drop(app);
tester.pump_widget(Focus::new(probe(&captured)).autofocus(true).into_widget());
let mut app = tester.cell.borrow_mut();
let node = captured.get().expect("Focus.of found the node");
assert!(node.has_primary_focus(&app));
let manager = FocusManager::instance(&mut app);
assert_eq!(manager.primary_focus(&app), Some(node));
});
}
#[test]
fn focus_of_reports_has_focus_on_the_ancestor_and_primary_focus_on_the_leaf() {
test_widgets(|tester| {
let app = tester.cell.borrow();
let outer: Captured = Rc::default();
let inner: Captured = Rc::default();
let inner_sink = Rc::clone(&inner);
let outer_sink = Rc::clone(&outer);
drop(app);
tester.pump_widget(
Focus::new(Builder::new(move |app, context| {
outer_sink.set(Focus::maybe_of(app, context, false, true));
Focus::new(probe(&inner_sink)).autofocus(true).into_widget()
}))
.debug_label("outer")
.into_widget(),
);
let mut app = tester.cell.borrow_mut();
let outer = outer.get().expect("the outer Focus.of found nothing");
let inner = inner.get().expect("the inner Focus.of found nothing");
assert_ne!(outer, inner);
assert_eq!(inner.parent(&app), Some(outer));
assert!(inner.has_primary_focus(&app));
assert!(inner.has_focus(&mut app));
assert!(outer.has_focus(&mut app));
assert!(!outer.has_primary_focus(&app));
assert_eq!(outer.debug_label(&app).as_deref(), Some("outer"));
});
}
#[test]
fn focus_scope_of_returns_the_enclosing_scope() {
test_widgets(|tester| {
let app = tester.cell.borrow();
let scope_node = Rc::new(Cell::new(None));
let sink = Rc::clone(&scope_node);
drop(app);
tester.pump_widget(
Builder::new(move |app, context| {
sink.set(Some(FocusScope::of(app, context, true)));
SizedBox::shrink().into_widget()
})
.into_widget(),
);
let mut app = tester.cell.borrow_mut();
let manager = FocusManager::instance(&mut app);
let view_scope = scope_node.get().expect("FocusScope.of ran");
assert_ne!(view_scope, manager.root_scope(&app).handle());
assert_eq!(view_scope.debug_label(&app).as_deref(), Some("View Scope"));
assert_eq!(
view_scope.enclosing_scope(&mut app),
Some(manager.root_scope(&app).handle())
);
});
test_widgets(|tester| {
let app = tester.cell.borrow();
let scope_node = Rc::new(Cell::new(None));
let sink = Rc::clone(&scope_node);
drop(app);
tester.pump_widget(
FocusScope::new(Builder::new(move |app, context| {
sink.set(Some(FocusScope::of(app, context, true)));
SizedBox::shrink().into_widget()
}))
.debug_label("scope")
.into_widget(),
);
let mut app = tester.cell.borrow_mut();
let manager = FocusManager::instance(&mut app);
let scope = scope_node.get().expect("FocusScope.of ran");
assert_ne!(scope, manager.root_scope(&app).handle());
assert_eq!(scope.debug_label(&app).as_deref(), Some("scope"));
assert_eq!(
scope
.enclosing_scope(&mut app)
.and_then(|scope| scope.debug_label(&app)),
Some("View Scope".to_string())
);
});
}
#[test]
fn a_focus_widgets_on_key_event_receives_events_addressed_to_its_node() {
test_widgets(|tester| {
use std::time::Duration;
use waft_services::{
HardwareKeyboard, KeyDownEvent, KeyEvent, LogicalKeyboardKey, PhysicalKeyboardKey,
};
let app = tester.cell.borrow();
let seen: Rc<RefCell<Vec<&'static str>>> = Rc::default();
let inner_seen = Rc::clone(&seen);
let outer_seen = Rc::clone(&seen);
drop(app);
tester.pump_widget(
Focus::new(
Focus::new(SizedBox::shrink())
.autofocus(true)
.on_key_event(Rc::new(move |_app, _node, _event| {
inner_seen.borrow_mut().push("inner");
KeyEventResult::Ignored
})),
)
.on_key_event(Rc::new(move |_app, _node, _event| {
outer_seen.borrow_mut().push("outer");
KeyEventResult::Handled
}))
.into_widget(),
);
let mut app = tester.cell.borrow_mut();
let event = KeyEvent::Down(KeyDownEvent::new(
PhysicalKeyboardKey::KEY_A,
LogicalKeyboardKey::KEY_A,
Duration::ZERO,
));
let handled = HardwareKeyboard::instance(&mut app).handle_key_event(&mut app, &event);
assert!(handled);
assert_eq!(*seen.borrow(), vec!["inner", "outer"]);
});
}
#[test]
fn moving_a_focus_widget_by_global_key_keeps_its_node_and_its_focus() {
test_widgets(|tester| {
let app = tester.cell.borrow();
let captured: Captured = Rc::default();
let key = GlobalKey::new();
drop(app);
tester.pump_widget(
Padding::new(waft_painting::EdgeInsetsGeometry::all(4.0))
.child(
Focus::new(probe(&captured))
.key(key.clone().into())
.autofocus(true),
)
.into_widget(),
);
let app = tester.cell.borrow();
let node = captured.get().expect("Focus.of found the node");
assert!(node.has_primary_focus(&app));
drop(app);
tester.pump_widget(
Center::new()
.child(Focus::new(probe(&captured)).key(key.clone().into()))
.into_widget(),
);
let app = tester.cell.borrow();
assert_eq!(captured.get(), Some(node));
assert!(node.has_primary_focus(&app));
});
}
#[test]
fn exclude_focus_blocks_the_descendants() {
test_widgets(|tester| {
let app = tester.cell.borrow();
let captured: Captured = Rc::default();
drop(app);
tester.pump_widget(ExcludeFocus::new(Focus::new(probe(&captured))).into_widget());
let mut app = tester.cell.borrow_mut();
let node = captured.get().expect("Focus.of found the node");
assert!(!node.can_request_focus(&mut app));
node.request_focus(&mut app, None);
app.drain_microtasks();
assert!(!node.has_primary_focus(&app));
});
}
}