1use std::sync::{
2 Arc,
3 atomic::{AtomicBool, Ordering},
4};
5
6use zng_ext_input::mouse::{ClickMode, MOUSE_HOVERED_EVENT, WidgetInfoBuilderMouseExt as _};
7use zng_ext_window::WINDOW_Ext as _;
8use zng_wgt::prelude::*;
9
10pub use zng_view_api::window::CursorIcon;
11
12pub use zng_ext_window::CursorSource;
13
14#[cfg(feature = "image")]
15pub use zng_ext_window::CursorImg;
16
17context_local! {
18 static CHILD_SETS_CURSOR: AtomicBool = AtomicBool::new(false);
19}
20
21#[property(CONTEXT, default(CursorIcon::Default))]
28pub fn cursor(child: impl IntoUiNode, cursor: impl IntoVar<CursorSource>) -> UiNode {
29 let cursor = cursor.into_var();
30 let mut binding = None;
31 let mut child_sets_ctx = None::<Arc<AtomicBool>>;
32
33 match_node(child, move |c, op| {
34 let mut unbind_restore = false;
35 match op {
36 UiNodeOp::Init => {
37 WIDGET.sub_event(&MOUSE_HOVERED_EVENT);
38 }
39 UiNodeOp::Deinit => {
40 unbind_restore = true;
41 child_sets_ctx = None;
42 }
43 UiNodeOp::Event { update } => {
44 if let Some(args) = MOUSE_HOVERED_EVENT.on(update) {
45 let mut bind = false;
46 if args.is_over() {
47 if child_sets_ctx.is_none() {
48 child_sets_ctx = Some(Arc::new(AtomicBool::new(false)));
49 }
50
51 CHILD_SETS_CURSOR.with_context(&mut child_sets_ctx, || c.event(update));
53
54 if !child_sets_ctx.as_ref().unwrap().swap(false, Ordering::Relaxed) {
55 bind = true;
57 }
58
59 CHILD_SETS_CURSOR.get().store(true, Ordering::Relaxed);
61 }
62
63 if bind {
64 if binding.is_none() {
65 binding = Some(cursor.set_bind(&WINDOW.vars().cursor()));
67 }
68 } else {
69 unbind_restore = true;
70 }
71 }
72 }
73 _ => {}
74 }
75
76 if unbind_restore && binding.is_some() {
78 binding = None;
79 let value = cursor.get();
80 WINDOW.vars().cursor().modify(move |c| {
81 if c.value() == &value {
82 **c = CursorIcon::Default.into();
83 }
84 });
85 }
86 })
87}
88
89#[property(CONTEXT, default(None))]
96pub fn click_mode(child: impl IntoUiNode, mode: impl IntoVar<Option<ClickMode>>) -> UiNode {
97 let mode = mode.into_var();
98
99 match_node(child, move |_, op| match op {
100 UiNodeOp::Init => {
101 WIDGET.sub_var_info(&mode);
102 }
103 UiNodeOp::Info { info } => {
104 info.set_click_mode(mode.get());
105 }
106 _ => {}
107 })
108}