#Routed events

    The package moonrockz/dependency-object/events.

    Routed events with the behavior of WPF, for the elements of moonrockz/dependency-object. @events in the examples is this package, and @dependency is moonrockz/dependency-object.

    #A button with an event

    A Click on a button goes up the logical tree, so the panel hears of the clicks of all its buttons:

    ///|
    let button_type : @dependency.OwnerType = try! @dependency.register_owner_type(
    "Button",
    element=true,
    )

    ///|
    let panel_type : @dependency.OwnerType = try! @dependency.register_owner_type(
    "Panel",
    element=true,
    )

    ///|
    let click : @events.RoutedEvent[Unit] = try! @events.register_routed_event(
    "Click",
    Bubble,
    button_type,
    @dependency.unit_key,
    )

    ///|
    /// What a control does when the mouse or a key clicks it.
    fn click_on(button : @dependency.DependencyObject) -> Unit raise {
    @events.raise_event(button, @events.RoutedEventArgs::new((), event=click))
    }

    ///|
    test "a panel hears of the clicks of its buttons" {
    let panel = @dependency.DependencyObject::new(panel_type)
    let ok = @dependency.DependencyObject::new(button_type)
    let cancel = @dependency.DependencyObject::new(button_type)
    let items = @dependency.ElementCollection::new(panel)
    items.add(ok)
    items.add(cancel)
    let log = []
    let token = @events.add_handler(ok, click, (_, args) => {
    log.push("OK")
    args.set_handled(true)
    })
    ignore(
    @events.add_handler(panel, click, (_, args) => {
    if args.source() is Some(Object(button)) && button == cancel {
    log.push("a click on Cancel")
    }
    }),
    )
    click_on(ok)
    click_on(cancel)
    assert_eq(log, ["OK", "a click on Cancel"])
    assert_true(@events.remove_handler(ok, token))
    }

    #Register events

    A program registers each event on the type that raises it, with a routing strategy and the key of its data. An event without data has the key unit_key.

    ///|
    test "look up" {
    let toggle_button = @dependency.register_owner_type(
    "ToggleButton",
    base=button_type,
    )
    guard @events.lookup_routed_event(toggle_button, "Click") is Some(found) else {
    fail("no such event")
    }
    assert_eq(found, click.info())
    inspect(found, content="Button.Click")
    }

    StrategyThe handlers run
    Bubbleon the element that raises the event, and then on its ancestors up to the root
    Tunnelon the root first, and then down to the element
    Directonly on the element

    A RoutedEvent[A] has data of type A. Its info is the event without this type, a RoutedEventInfo, for code that has events of many types. lookup_routed_event gives one too, and its typed gives the RoutedEvent[A] back for the right key. All handles of one event are equal.

    An owner type can have one event with a name. A type that derives from it can use the name for another event, and the lookup gives the event of the nearest type. add_owner makes an event one of another type too, so that the lookup finds it there. When that type has another event of the same name, add_owner is no error, as in WPF, and the lookup goes on to find the first one.

    Events are in the registry of the process, unless you pass another one with registry~. See Registries.

    #Raise events

    raise_event runs the handlers for the event on the elements of its route, and goes on when they have run. It settles which handlers run before the first one does, so a change of the tree or of the handlers is for the next raise.

    All handlers of a raise get the same arguments, and what one changes is there for the next one:

    FunctionWhat it is
    datathe data of the raise, of the type of the event
    eventthe event that is raised
    handled, set_handledwhether a handler has dealt with the event. Then only handlers with handled_events_too still run. A handler can also take this back
    source, set_sourcewhere the event comes from: the element on which it is raised, unless a handler says otherwise
    original_sourcethe first source, which handlers cannot change

    ///|
    priv struct KeyInfo {
    key : Char
    }

    ///|
    let key_info_key : @dependency.ValueKey[KeyInfo] = @dependency.ValueKey::by_identity(
    "KeyInfo",
    )

    ///|
    let key_down : @events.RoutedEvent[KeyInfo] = try! @events.register_routed_event(
    "KeyDown",
    Bubble,
    button_type,
    key_info_key,
    )

    ///|
    test "an event with data" {
    let button = @dependency.DependencyObject::new(button_type)
    let log = []
    ignore(
    @events.add_handler(button, key_down, (_, args) => log.push(args.data.key)),
    )
    @events.raise_event(
    button,
    @events.RoutedEventArgs::new({ key: 'a', }, event=key_down),
    )
    assert_eq(log, ['a'])
    }

    • The source is a dependency object, which does not have to be an element, or an AnyValue. RoutedEventArgs::new can get one with source, such as the part of the button on which the mouse was. It is the original_source of the raise, and also the source after it.
    • Arguments without an event need set_event before anything else. They can get another event later, also from a handler. The raise that runs then goes on with the handlers of its event. All events of one RoutedEventArgs have the same key for their data.
    • A handler can raise events, also with the arguments that it gets. Such a raise is complete when the handler goes on. Raises and changes of properties count together for the nesting_limit.
    • An error of a handler ends the raise and reaches the code that made it. The arguments stay as they are at that moment, and can be raised again.
    • A route can have 4,097 elements, as in WPF. When it gets longer, such as in a tree with a loop, the raise fails before a handler runs.

    #Handlers of elements

    add_handler adds a handler for any event to any element, also when the type of the element has nothing to do with the event, as the panel above. Such an event is an attached event in XAML. The handler gets the element to which it was added and the arguments.

    • Handlers of an element run in the order in which they were added. One that is added twice runs twice.
    • handled_events_too=true is for a handler that also runs when the event is handled.
    • remove_handler removes the handler with the token that add_handler gave. release_handlers removes all of an element, also those that a XAML document has added, for which there is no token.
    • add_routing_handler is for a handler that does not need the data. It can be one of events with data of different types. It gets RoutingArgs, which have everything but the data and set_event.

    ///|
    test "one handler for events with different data" {
    let button = @dependency.DependencyObject::new(button_type)
    let log = []
    for event in [click.info(), key_down.info()] {
    ignore(
    @events.add_routing_handler(button, event, (_, args) => {
    if args.event() is Some(event) {
    log.push(event.name())
    }
    }),
    )
    }
    click_on(button)
    @events.raise_event(
    button,
    @events.RoutedEventArgs::new({ key: 'a', }, event=key_down),
    )
    assert_eq(log, ["Click", "KeyDown"])
    @events.release_handlers(button)
    }

    #Handlers of types

    register_class_handler runs a handler for each element of a type and of the types that derive from it. This is how a control reacts to its own events, before the program that uses it does:

    ///|
    let check_box_type : @dependency.OwnerType = try! @dependency.register_owner_type(
    "CheckBox",
    base=button_type,
    )

    ///|
    let is_checked : @dependency.DependencyProperty[Bool] = try! @dependency.register(
    "IsChecked",
    check_box_type,
    @dependency.bool_key,
    default_value=false,
    )

    ///|
    fn init {
    try! @events.register_class_handler(check_box_type, click, (check_box, _) => {
    check_box.set_value(is_checked, !check_box.get_value(is_checked))
    })
    }

    ///|
    test "a click checks a check box" {
    let check_box = @dependency.DependencyObject::new(check_box_type)
    let log = []
    ignore(
    @events.add_handler(check_box, click, (sender, _) => {
    log.push(sender.get_value(is_checked))
    }),
    )
    click_on(check_box)
    click_on(check_box)
    assert_eq(log, [true, false])
    }

    • On one element, the handlers of its type run first, then those of each base type, the nearest one first, and then those of the element. A tunnel event reverses only the order of the elements.
    • A class handler that handles the event stops the handlers of the element too, unless these have handled_events_too.
    • Only element types have class handlers. They are there from the next raise on, and cannot be removed.
    • register_class_routing_handler is for a handler that does not need the data.

    #Preview events

    WPF has pairs of events such as PreviewKeyDown and KeyDown: one tunnels from the root to the element, and then the other bubbles back. With the first one, a panel can handle a key before the element in it gets it. This is a convention, and not a strategy of its own. The control raises both events with the same arguments, so the second raise starts with the handled of the first one:

    ///|
    let preview_key_down : @events.RoutedEvent[KeyInfo] = try! @events.register_routed_event(
    "PreviewKeyDown",
    Tunnel,
    button_type,
    key_info_key,
    )

    ///|
    fn press(button : @dependency.DependencyObject, key : Char) -> Unit raise {
    let args = @events.RoutedEventArgs::new({ key, }, event=preview_key_down)
    @events.raise_event(button, args)
    args.set_event(key_down)
    @events.raise_event(button, args)
    }

    ///|
    test "a panel that accepts only digits" {
    let panel = @dependency.DependencyObject::new(panel_type)
    let button = @dependency.DependencyObject::new(button_type)
    panel.add_logical_child(button)
    let log = []
    ignore(
    @events.add_handler(panel, preview_key_down, (_, args) => {
    args.set_handled(!args.data.key.is_ascii_digit())
    }),
    )
    ignore(
    @events.add_handler(button, key_down, (_, args) => log.push(args.data.key)),
    )
    press(button, 'a')
    press(button, '1')
    assert_eq(log, ['1'])
    panel.remove_logical_child(button)
    }

    #Memory

    An element holds its handlers, and a handler holds what it uses. js and wasm-gc free both together. native and wasm count references, and never free a handler that uses its own element, or an ancestor of it. Use the element that the handler gets, which is no circle, or call remove_handler or release_handlers before you drop the element.

    Class handlers are in their registry. The registry of the process lives as long as the process. When a class handler uses a registry of your own, call release_class_handlers before you drop the registry.

    #Differences from WPF

    MoonBit forces these:

    1. Handlers are removed with a token. WPF compares the handlers, and functions of MoonBit have no equality. The handlers of a XAML document have no token, so release_handlers removes all handlers of an element.
    2. The arguments have data. In WPF an event has a class of arguments that derives from RoutedEventArgs. Here it has RoutedEventArgs[A], and the key of A stands for the type. RoutingArgs are what all arguments have in common.
    3. A lookup gives an event without the type of its data. typed gives the type back.
    4. A source is an EventSource. In WPF it is an object.
    5. An element is an object of an element type. In WPF it is an object of UIElement, ContentElement or UIElement3D, and only these have AddHandler and RaiseEvent. Here these functions fail for other objects.
    6. A registry is a value, and the events and elements of two registries cannot be used together. release_class_handlers is for a registry of your own.
    7. Raises nest at most nesting_limit levels deep, together with changes of properties. WPF has no limit, and its process ends when the stack is full.

    Avalonia differs from WPF and from this package. There an event can tunnel and bubble in one raise, and a class handler can be removed.

    EventSource

    Where an event comes from.

    RoutedEvent

    pub struct RoutedEvent[A] {
    // private fields
    }

    A routed event with data of type A.

    RoutedEvent::add_owner

    Make the event one of owner too, so that lookup_routed_event finds it there by its name. Returns the same event.

    When owner has another event with this name, this is no error, as in WPF, and the lookup goes on to find the other one.

    RoutedEvent::info

    fn[A] RoutedEvent::info(self : RoutedEvent[A]) -> RoutedEventInfo

    The event without the type of its data.

    RoutedEventArgs

    pub struct RoutedEventArgs[A] {
    data : A
    // private fields
    }

    What the handlers of an event with data of type A get. Handlers share one state, and what one sets is there for the next one.

    RoutedEventArgs::event

    fn[A] RoutedEventArgs::event(self : RoutedEventArgs[A]) -> RoutedEventInfo?

    The event that is raised, or None when the arguments have none yet.

    RoutedEventArgs::handled

    fn[A] RoutedEventArgs::handled(self : RoutedEventArgs[A]) -> Bool

    As RoutingArgs::handled.

    RoutedEventArgs::new

    fn[A] RoutedEventArgs::new(data : A, event? : RoutedEvent[A], source? : EventSource) -> RoutedEventArgs[A]

    Arguments with data for a raise of event. Without event they need set_event before they can be raised. source is the original_source, which else is the element on which the arguments are raised first.

    RoutedEventArgs::original_source

    fn[A] RoutedEventArgs::original_source(self : RoutedEventArgs[A]) -> EventSource?

    As RoutingArgs::original_source.

    RoutedEventArgs::routing

    fn[A] RoutedEventArgs::routing(self : RoutedEventArgs[A]) -> RoutingArgs

    The state without the data, for code that has events of many types.

    RoutedEventArgs::set_event

    Use the arguments for another event, for example to raise the bubble event after its preview event. It is an error when the two events do not have the same key for their data. A raise that is running goes on with the handlers of its event.

    RoutedEventArgs::set_handled

    fn[A] RoutedEventArgs::set_handled(self : RoutedEventArgs[A], handled : Bool) -> Unit raise
    DependencyError

    As RoutingArgs::set_handled.

    RoutedEventArgs::set_source

    As RoutingArgs::set_source.

    RoutedEventArgs::source

    fn[A] RoutedEventArgs::source(self : RoutedEventArgs[A]) -> EventSource?

    As RoutingArgs::source.

    RoutedEventInfo

    pub struct RoutedEventInfo {
    // private fields
    }

    A routed event without the type of its data.

    All handles of one event are equal, also one that lookup_routed_event gives.

    RoutedEventInfo::args_key_id

    The identity of the key that stands for the type of the data.

    RoutedEventInfo::name

    fn RoutedEventInfo::name(self : RoutedEventInfo) -> String

    RoutedEventInfo::owner_type

    The type on which the event was registered, not one that add_owner added.

    RoutedEventInfo::registry_id

    RoutedEventInfo::strategy

    RoutedEventInfo::to_string

    fn RoutedEventInfo::to_string(self : RoutedEventInfo) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    RoutedEventInfo::typed

    The event with the type of its data, which key stands for. It is an error when the event was registered with another key.

    RoutingArgs

    pub struct RoutingArgs {
    // private fields
    }

    The state of the arguments that does not depend on the type of their data, for handlers of every event. All handlers of a raise share it, so what one sets is there for the next one.

    RoutingArgs::event

    The event that is raised, or None when the arguments have none yet.

    RoutingArgs::handled

    fn RoutingArgs::handled(self : RoutingArgs) -> Bool

    Whether a handler has dealt with the event, so that only handlers with handled_events_too still run.

    RoutingArgs::original_source

    fn RoutingArgs::original_source(self : RoutingArgs) -> EventSource?

    The first source that the arguments had, which nothing changes.

    RoutingArgs::set_handled

    fn RoutingArgs::set_handled(self : RoutingArgs, handled : Bool) -> Unit raise
    DependencyError

    Say whether the event is dealt with. The arguments need an event for this.

    RoutingArgs::set_source

    Set the source for the handlers that follow. The first source is also the original_source. The arguments need an event for this.

    RoutingArgs::source

    fn RoutingArgs::source(self : RoutingArgs) -> EventSource?

    The element on which the event is raised, or what a handler has set. After a raise it is the original_source.

    RoutingStrategy

    pub(all) enum RoutingStrategy {
    Bubble
    Tunnel
    Direct
    } derive(Eq, Hash,
    Debug
    )

    On which elements the handlers of an event run. An event has exactly one strategy, as in WPF.

    add_handler

    Run handler on element for each raise of event whose route has the element. It gets element and the arguments of the raise.

    The event can be one of any type, also when the type of element has nothing to do with it. So a panel hears of the clicks of its buttons. Handlers run in the order in which they were added, and one that is added twice runs twice.

    Without handled_events_too the handler does not run when another one has handled the event. An error of a handler ends the raise and reaches the code that made it.

    add_routing_handler

    As add_handler, for a handler that does not need the data and so can be one of events with data of different types.

    lookup_routed_event

    The event with the name name of owner, or else of the nearest type that it derives from.

    raise_event

    fn[A] raise_event(sender :
    DependencyObject
    , args : RoutedEventArgs[A]) -> Unit raise

    Raise the event of args on sender: run the handlers for it on sender and on its ancestors, as the strategy of the event says.

    Which handlers run is settled before the first one runs. A change of the tree or of the handlers is for the next raise.

    The source is sender until a handler sets another one, and after the raise it is the original_source again. An error of a handler ends the raise, and the arguments stay as they are then.

    register_class_handler

    Run handler for event on each element of type owner, or of a type that derives from it, from the next raise on. There is no way to remove it.

    On one element, the handlers of its type run first, then those of each base type, the nearest one first, and then those of the element. The rest is as for add_handler.

    register_class_routing_handler

    As register_class_handler, for a handler that does not need the data and so can be one of events with data of different types.

    register_routed_event

    Register a routed event on owner.

    args_key stands for the type of the data that a raise gives to the handlers. It is the unit_key of moonrockz/dependency-object for an event without data.

    An owner type can have one event with a name. A type that derives from it can use the name for another event. Events and properties do not share their names.

    release_class_handlers

    Release all class handlers of a registry that is no longer needed, so that targets that count references can free it and what the handlers use. The default registry keeps its class handlers, as WPF does.

    release_handlers

    Remove all handlers of element, also those that a XAML document has added, for which there are no tokens.

    remove_handler

    Remove the handler for which add_handler or add_routing_handler returned token for this element. Returns false when the element has no such handler.