1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
//! App event and commands API.
use std::{
any::Any,
fmt,
marker::PhantomData,
mem,
ops::Deref,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Instant,
};
mod args;
pub use args::*;
mod command;
pub use command::*;
mod events;
pub use events::*;
mod channel;
pub use channel::*;
use crate::{
handler::{AppHandler, AppHandlerArgs},
update::{EventUpdate, UpdateDeliveryList, UpdateSubscribers},
widget::WidgetId,
};
use parking_lot::Mutex;
use zng_app_context::AppLocal;
use zng_clone_move::clmv;
use zng_unique_id::{IdEntry, IdMap, IdSet};
///<span data-del-macro-root></span> Declares new [`Event<A>`] static items.
///
/// Event static items represent external, app or widget events. You can also use [`command!`]
/// to declare events specialized for commanding widgets and services.
///
/// [`AppExtension`]: crate::AppExtension
///
/// # Conventions
///
/// Command events have the `_EVENT` suffix, for example an event representing a click is called `CLICK_EVENT`.
///
/// # Properties
///
/// If the event targets widgets you can use `event_property!` to declare properties that setup event handlers for the event.
///
/// # Examples
///
/// The example defines two events with the same arguments type.
///
/// ```
/// # use zng_app::event::*;
/// # event_args! { pub struct ClickArgs { .. fn delivery_list(&self, _l: &mut UpdateDeliveryList) { } } }
/// event! {
/// /// Event docs.
/// pub static CLICK_EVENT: ClickArgs;
///
/// /// Other event docs.
/// pub static DOUBLE_CLICK_EVENT: ClickArgs;
/// }
/// ```
#[macro_export]
macro_rules! event_macro {
($(
$(#[$attr:meta])*
$vis:vis static $EVENT:ident: $Args:path;
)+) => {
$(
$(#[$attr])*
$vis static $EVENT: $crate::event::Event<$Args> = {
$crate::event::app_local! {
static LOCAL: $crate::event::EventData = const { $crate::event::EventData::new(std::stringify!($EVENT)) };
}
$crate::event::Event::new(&LOCAL)
};
)+
}
}
#[doc(inline)]
pub use crate::event_macro as event;
#[doc(hidden)]
pub struct EventData {
name: &'static str,
widget_subs: IdMap<WidgetId, EventHandle>,
hooks: Vec<EventHook>,
}
impl EventData {
#[doc(hidden)]
pub const fn new(name: &'static str) -> Self {
EventData {
name,
widget_subs: IdMap::new(),
hooks: vec![],
}
}
}
/// Represents an event.
///
/// Use the [`event!`] macro to declare events.
pub struct Event<A: EventArgs> {
local: &'static AppLocal<EventData>,
_args: PhantomData<fn(A)>,
}
impl<A: EventArgs> fmt::Debug for Event<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write!(f, "Event({})", self.name())
} else {
write!(f, "{}", self.name())
}
}
}
impl<A: EventArgs> Event<A> {
#[doc(hidden)]
pub const fn new(local: &'static AppLocal<EventData>) -> Self {
Event { local, _args: PhantomData }
}
/// Gets the event without the args type.
pub fn as_any(&self) -> AnyEvent {
AnyEvent { local: self.local }
}
/// Register the widget to receive targeted events from this event.
///
/// Widgets only receive events if they are in the delivery list generated by the event args and are
/// subscribers to the event. App extensions receive all events.
pub fn subscribe(&self, widget_id: WidgetId) -> EventHandle {
self.as_any().subscribe(widget_id)
}
/// Returns `true` if the widget is subscribed to this event.
pub fn is_subscriber(&self, widget_id: WidgetId) -> bool {
self.as_any().is_subscriber(widget_id)
}
/// Returns `true` if at least one widget is subscribed to this event.
pub fn has_subscribers(&self) -> bool {
self.as_any().has_subscribers()
}
/// Calls `visit` for each widget subscribed to this event.
///
/// Note that trying to subscribe or add hook inside `visit` will deadlock. Inside `visit` you can notify the event and
/// generate event updates.
pub fn visit_subscribers(&self, visit: impl FnMut(WidgetId)) {
self.as_any().visit_subscribers(visit)
}
/// Name of the event static item.
pub fn name(&self) -> &'static str {
self.local.read().name
}
/// Returns `true` if the update is for this event.
pub fn has(&self, update: &EventUpdate) -> bool {
*self == update.event
}
/// Get the event update args if the update is for this event.
pub fn on<'a>(&self, update: &'a EventUpdate) -> Option<&'a A> {
if *self == update.event {
update.args.as_any().downcast_ref()
} else {
None
}
}
/// Get the event update args if the update is for this event and propagation is not stopped.
pub fn on_unhandled<'a>(&self, update: &'a EventUpdate) -> Option<&'a A> {
self.on(update).filter(|a| !a.propagation().is_stopped())
}
/// Calls `handler` if the update is for this event and propagation is not stopped, after the handler is called propagation is stopped.
pub fn handle<R>(&self, update: &EventUpdate, handler: impl FnOnce(&A) -> R) -> Option<R> {
if let Some(args) = self.on(update) {
args.handle(handler)
} else {
None
}
}
/// Create an event update for this event with delivery list filtered by the event subscribers.
pub fn new_update(&self, args: A) -> EventUpdate {
self.new_update_custom(args, UpdateDeliveryList::new(Box::new(self.as_any())))
}
/// Create and event update for this event with a custom delivery list.
pub fn new_update_custom(&self, args: A, mut delivery_list: UpdateDeliveryList) -> EventUpdate {
args.delivery_list(&mut delivery_list);
EventUpdate {
event: self.as_any(),
delivery_list,
args: Box::new(args),
pre_actions: Mutex::new(vec![]),
pos_actions: Mutex::new(vec![]),
}
}
/// Schedule an event update.
pub fn notify(&self, args: A) {
let update = self.new_update(args);
EVENTS.notify(update);
}
/// Creates a preview event handler.
///
/// The event `handler` is called for every update that has not stopped [`propagation`](AnyEventArgs::propagation).
/// The handler is called before widget handlers and [`on_event`](Self::on_event) handlers. The handler is called
/// after all previous registered preview handlers.
///
/// Returns an [`EventHandle`] that can be dropped to unsubscribe, you can also unsubscribe from inside the handler by calling
/// [`unsubscribe`](crate::handler::AppWeakHandle::unsubscribe) in the third parameter of [`app_hn!`] or [`async_app_hn!`].
///
/// # Examples
///
/// ```
/// # use zng_app::event::*;
/// # use zng_app::APP;
/// # use zng_app::handler::app_hn;
/// # event_args! { pub struct FocusChangedArgs { pub new_focus: bool, .. fn delivery_list(&self, _l: &mut UpdateDeliveryList) {} } }
/// # event! { pub static FOCUS_CHANGED_EVENT: FocusChangedArgs; }
/// # let _scope = APP.minimal();
/// let handle = FOCUS_CHANGED_EVENT.on_pre_event(app_hn!(|args: &FocusChangedArgs, _| {
/// println!("focused: {:?}", args.new_focus);
/// }));
/// ```
/// The example listens to all `FOCUS_CHANGED_EVENT` events, independent of widget context and before all UI handlers.
///
/// # Handlers
///
/// the event handler can be any type that implements [`AppHandler`], there are multiple flavors of handlers, including
/// async handlers that allow calling `.await`. The handler closures can be declared using [`app_hn!`], [`async_app_hn!`],
/// [`app_hn_once!`] and [`async_app_hn_once!`].
///
/// ## Async
///
/// Note that for async handlers only the code before the first `.await` is called in the *preview* moment, code after runs in
/// subsequent event updates, after the event has already propagated, so stopping [`propagation`](AnyEventArgs::propagation)
/// only causes the desired effect before the first `.await`.
///
/// [`app_hn!`]: crate::handler::app_hn!
/// [`async_app_hn!`]: crate::handler::async_app_hn!
/// [`app_hn_once!`]: crate::handler::app_hn_once!
/// [`async_app_hn_once!`]: crate::handler::async_app_hn_once!
pub fn on_pre_event<H>(&self, handler: H) -> EventHandle
where
H: AppHandler<A>,
{
self.on_event_impl(handler, true)
}
/// Creates an event handler.
///
/// The event `handler` is called for every update that has not stopped [`propagation`](AnyEventArgs::propagation).
/// The handler is called after all [`on_pre_event`](Self::on_pre_event) all widget handlers and all [`on_event`](Self::on_event)
/// handlers registered before this one.
///
/// Returns an [`EventHandle`] that can be dropped to unsubscribe, you can also unsubscribe from inside the handler by calling
/// [`unsubscribe`](crate::handler::AppWeakHandle::unsubscribe) in the third parameter of [`app_hn!`] or [`async_app_hn!`].
///
/// # Examples
///
/// ```
/// # use zng_app::event::*;
/// # use zng_app::APP;
/// # use zng_app::handler::app_hn;
/// # event_args! { pub struct FocusChangedArgs { pub new_focus: bool, .. fn delivery_list(&self, _l: &mut UpdateDeliveryList) {} } }
/// # event! { pub static FOCUS_CHANGED_EVENT: FocusChangedArgs; }
/// # let _scope = APP.minimal();
/// let handle = FOCUS_CHANGED_EVENT.on_event(app_hn!(|args: &FocusChangedArgs, _| {
/// println!("focused: {:?}", args.new_focus);
/// }));
/// ```
/// The example listens to all `FOCUS_CHANGED_EVENT` events, independent of widget context, after the UI was notified.
///
/// # Handlers
///
/// the event handler can be any type that implements [`AppHandler`], there are multiple flavors of handlers, including
/// async handlers that allow calling `.await`. The handler closures can be declared using [`app_hn!`], [`async_app_hn!`],
/// [`app_hn_once!`] and [`async_app_hn_once!`].
///
/// ## Async
///
/// Note that for async handlers only the code before the first `.await` is called in the *preview* moment, code after runs in
/// subsequent event updates, after the event has already propagated, so stopping [`propagation`](AnyEventArgs::propagation)
/// only causes the desired effect before the first `.await`.
///
/// [`app_hn!`]: crate::handler::app_hn!
/// [`async_app_hn!`]: crate::handler::async_app_hn!
/// [`app_hn_once!`]: crate::handler::app_hn_once!
/// [`async_app_hn_once!`]: crate::handler::async_app_hn_once!
pub fn on_event(&self, handler: impl AppHandler<A>) -> EventHandle {
self.on_event_impl(handler, false)
}
fn on_event_impl(&self, handler: impl AppHandler<A>, is_preview: bool) -> EventHandle {
let handler = Arc::new(Mutex::new(handler));
let (inner_handle_owner, inner_handle) = zng_handle::Handle::new(());
self.as_any().hook(move |update| {
if inner_handle_owner.is_dropped() {
return false;
}
let handle = inner_handle.downgrade();
update.push_once_action(
Box::new(clmv!(handler, |update| {
let args = update.args().as_any().downcast_ref::<A>().unwrap();
if !args.propagation().is_stopped() {
handler.lock().event(
args,
&AppHandlerArgs {
handle: &handle,
is_preview,
},
);
}
})),
is_preview,
);
true
})
}
/// Creates a receiver channel for the event. The event updates are send on hook, before even preview handlers.
/// The receiver is unbounded, it will fill indefinitely if not drained. The receiver can be used in any thread,
/// including non-app threads.
///
/// Drop the receiver to stop listening.
pub fn receiver(&self) -> EventReceiver<A>
where
A: Send,
{
let (sender, receiver) = flume::unbounded();
self.as_any()
.hook(move |update| sender.send(update.args().as_any().downcast_ref::<A>().unwrap().clone()).is_ok())
.perm();
EventReceiver { receiver, event: *self }
}
/// Creates a sender channel that can notify the event.
///
/// Events can notify from any app thread, this sender can notify other threads too.
pub fn sender(&self) -> EventSender<A>
where
A: Send,
{
EVENTS_SV.write().sender(*self)
}
/// Returns `true` if any app level callback is registered for this event.
///
/// This includes [`AnyEvent::hook`], [`Event::on_pre_event`], [`Event::on_event`] and [`Event::receiver`].
pub fn has_hooks(&self) -> bool {
self.as_any().has_hooks()
}
}
impl<A: EventArgs> Clone for Event<A> {
fn clone(&self) -> Self {
*self
}
}
impl<A: EventArgs> Copy for Event<A> {}
impl<A: EventArgs> PartialEq for Event<A> {
fn eq(&self, other: &Self) -> bool {
self.local == other.local
}
}
impl<A: EventArgs> Eq for Event<A> {}
/// Represents an [`Event`] without the args type.
#[derive(Clone, Copy)]
pub struct AnyEvent {
local: &'static AppLocal<EventData>,
}
impl fmt::Debug for AnyEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write!(f, "AnyEvent({})", self.name())
} else {
write!(f, "{}", self.name())
}
}
}
impl AnyEvent {
/// Name of the event static item.
pub fn name(&self) -> &'static str {
self.local.read().name
}
/// Returns `true` if `self` is the type erased `event`.
pub fn is<A: EventArgs>(&self, event: &Event<A>) -> bool {
self == event
}
/// Returns `true` if the update is for this event.
pub fn has(&self, update: &EventUpdate) -> bool {
*self == update.event
}
/// Register a callback that is called just before an event begins notifying.
pub fn hook(&self, hook: impl Fn(&mut EventUpdate) -> bool + Send + Sync + 'static) -> EventHandle {
self.hook_impl(Box::new(hook))
}
fn hook_impl(&self, hook: Box<dyn Fn(&mut EventUpdate) -> bool + Send + Sync>) -> EventHandle {
let (handle, hook) = EventHandle::new(hook);
self.local.write().hooks.push(hook);
handle
}
/// Register the widget to receive targeted events from this event.
///
/// Widgets only receive events if they are in the delivery list generated by the event args and are
/// subscribers to the event. App extensions receive all events.
pub fn subscribe(&self, widget_id: WidgetId) -> EventHandle {
self.local
.write()
.widget_subs
.entry(widget_id)
.or_insert_with(EventHandle::new_none)
.clone()
}
/// Returns `true` if the widget is subscribed to this event.
pub fn is_subscriber(&self, widget_id: WidgetId) -> bool {
self.local.read().widget_subs.contains_key(&widget_id)
}
/// Returns `true` if at least one widget is subscribed to this event.
pub fn has_subscribers(&self) -> bool {
!self.local.read().widget_subs.is_empty()
}
/// Calls `visit` for each widget subscribed to this event.
///
/// Note that trying to subscribe or add hook inside `visit` will deadlock. Inside `visit` you can notify the event and
/// generate event updates.
pub fn visit_subscribers(&self, mut visit: impl FnMut(WidgetId)) {
for sub in self.local.read().widget_subs.keys() {
visit(*sub);
}
}
/// Returns `true` if any app level callback is registered for this event.
///
/// This includes [`AnyEvent::hook`], [`Event::on_pre_event`], [`Event::on_event`] and [`Event::receiver`].
pub fn has_hooks(&self) -> bool {
!self.local.read().hooks.is_empty()
}
pub(crate) fn on_update(&self, update: &mut EventUpdate) {
let mut hooks = mem::take(&mut self.local.write().hooks);
hooks.retain(|h| h.call(update));
let mut write = self.local.write();
hooks.append(&mut write.hooks);
write.hooks = hooks;
}
}
impl PartialEq for AnyEvent {
fn eq(&self, other: &Self) -> bool {
self.local == other.local
}
}
impl Eq for AnyEvent {}
impl std::hash::Hash for AnyEvent {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::hash::Hash::hash(self.local, state)
}
}
impl<A: EventArgs> PartialEq<AnyEvent> for Event<A> {
fn eq(&self, other: &AnyEvent) -> bool {
self.local == other.local
}
}
impl<A: EventArgs> PartialEq<Event<A>> for AnyEvent {
fn eq(&self, other: &Event<A>) -> bool {
self.local == other.local
}
}
impl UpdateSubscribers for AnyEvent {
fn contains(&self, widget_id: WidgetId) -> bool {
if let Some(mut write) = self.local.try_write() {
match write.widget_subs.entry(widget_id) {
IdEntry::Occupied(e) => {
let t = e.get().retain();
if !t {
let _ = e.remove();
}
t
}
IdEntry::Vacant(_) => false,
}
} else {
// fallback without cleanup
match self.local.read().widget_subs.get(&widget_id) {
Some(e) => e.retain(),
None => false,
}
}
}
fn to_set(&self) -> IdSet<WidgetId> {
self.local.read().widget_subs.keys().copied().collect()
}
}
/// Represents a collection of event handles.
#[must_use = "the event subscriptions or handlers are dropped if the handle is dropped"]
#[derive(Clone, Default)]
pub struct EventHandles(pub Vec<EventHandle>);
impl EventHandles {
/// Empty collection.
pub const fn dummy() -> Self {
EventHandles(vec![])
}
/// Returns `true` if empty or all handles are dummy.
pub fn is_dummy(&self) -> bool {
self.0.is_empty() || self.0.iter().all(EventHandle::is_dummy)
}
/// Drop all handles without stopping their behavior.
pub fn perm(self) {
for handle in self.0 {
handle.perm()
}
}
/// Add `other` handle to the collection.
pub fn push(&mut self, other: EventHandle) -> &mut Self {
if !other.is_dummy() {
self.0.push(other);
}
self
}
/// Drop all handles.
pub fn clear(&mut self) {
self.0.clear();
}
}
impl FromIterator<EventHandle> for EventHandles {
fn from_iter<T: IntoIterator<Item = EventHandle>>(iter: T) -> Self {
EventHandles(iter.into_iter().filter(|h| !h.is_dummy()).collect())
}
}
impl<const N: usize> From<[EventHandle; N]> for EventHandles {
fn from(handles: [EventHandle; N]) -> Self {
handles.into_iter().filter(|h| !h.is_dummy()).collect()
}
}
impl Extend<EventHandle> for EventHandles {
fn extend<T: IntoIterator<Item = EventHandle>>(&mut self, iter: T) {
for handle in iter {
self.push(handle);
}
}
}
impl IntoIterator for EventHandles {
type Item = EventHandle;
type IntoIter = std::vec::IntoIter<EventHandle>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
struct EventHandleData {
perm: AtomicBool,
hook: Option<Box<dyn Fn(&mut EventUpdate) -> bool + Send + Sync>>,
}
/// Represents an event widget subscription, handler callback or hook.
#[derive(Clone)]
#[must_use = "the event subscription or handler is dropped if the handle is dropped"]
pub struct EventHandle(Option<Arc<EventHandleData>>);
impl PartialEq for EventHandle {
fn eq(&self, other: &Self) -> bool {
match (&self.0, &other.0) {
(None, None) => true,
(None, Some(_)) | (Some(_), None) => false,
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
}
}
}
impl Eq for EventHandle {}
impl std::hash::Hash for EventHandle {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let i = match &self.0 {
Some(rc) => Arc::as_ptr(rc) as usize,
None => 0,
};
state.write_usize(i);
}
}
impl fmt::Debug for EventHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let i = match &self.0 {
Some(rc) => Arc::as_ptr(rc) as usize,
None => 0,
};
f.debug_tuple("EventHandle").field(&i).finish()
}
}
/// Dummy
impl Default for EventHandle {
fn default() -> Self {
Self::dummy()
}
}
impl EventHandle {
fn new(hook: Box<dyn Fn(&mut EventUpdate) -> bool + Send + Sync>) -> (Self, EventHook) {
let rc = Arc::new(EventHandleData {
perm: AtomicBool::new(false),
hook: Some(hook),
});
(Self(Some(rc.clone())), EventHook(rc))
}
fn new_none() -> Self {
Self(Some(Arc::new(EventHandleData {
perm: AtomicBool::new(false),
hook: None,
})))
}
/// Handle to no event.
pub fn dummy() -> Self {
EventHandle(None)
}
/// If the handle is not actually registered in an event.
pub fn is_dummy(&self) -> bool {
self.0.is_none()
}
/// Drop the handle without un-registering it, the resource it represents will remain registered in the event for the duration of
/// the process.
pub fn perm(self) {
if let Some(rc) = self.0 {
rc.perm.store(true, Ordering::Relaxed);
}
}
/// Create an [`EventHandles`] collection with `self` and `other`.
pub fn with(self, other: Self) -> EventHandles {
[self, other].into()
}
fn retain(&self) -> bool {
let rc = self.0.as_ref().unwrap();
Arc::strong_count(rc) > 1 || rc.perm.load(Ordering::Relaxed)
}
}
struct EventHook(Arc<EventHandleData>);
impl EventHook {
/// Callback, returns `true` if the handle must be retained.
fn call(&self, update: &mut EventUpdate) -> bool {
(Arc::strong_count(&self.0) > 1 || self.0.perm.load(Ordering::Relaxed)) && (self.0.hook.as_ref().unwrap())(update)
}
}