///|
/// The identity of a handler, with which it is removed. MoonBit functions have no equality, with which WPF does this.
#derive(Eq, Hash, Debug)
pub struct HandlerToken {
priv number : Int32
}
///|
let last_token : Ref[Int32] = Ref(0)
///|
/// A token that is unequal to all others, for a list of handlers in another package.
pub fn HandlerToken::new() -> HandlerToken {
last_token.val += 1
{ number: last_token.val, }
}
///|
priv struct ChangeHandler {
token : HandlerToken
run : (DependencyObject, PropertyInfo, AnyValue, AnyValue) -> Unit raise
}
///|
/// Run `handler` after each change of an effective value of the object, with the object, the property, the old value and
/// the new value. Handlers run in the order in which they were added, after the callbacks of the metadata. An error of a
/// handler reaches the caller that made the change, and the new value stays.
pub fn DependencyObject::add_change_handler(
self : DependencyObject,
handler : (DependencyObject, PropertyInfo, AnyValue, AnyValue) -> Unit raise,
) -> HandlerToken {
let token = HandlerToken::new()
let added = { token, run: handler, }
if self.handlers.is_empty() {
self.handlers = [added]
} else {
self.handlers.push(added)
}
token
}
///|
/// Remove the handler for which `add_change_handler` of this object returned `token`. Returns false when it has no such
/// handler.
pub fn DependencyObject::remove_change_handler(
self : DependencyObject,
token : HandlerToken,
) -> Bool {
let others = self.handlers.filter(handler => handler.token != token)
let removed = others.length() < self.handlers.length()
self.handlers = others
removed
}
///|
/// Change the logical content, run the callbacks of the metadata, base first, and then the handlers. The list of handlers is
/// read after the callbacks, so a handler that a callback adds already runs, and one that a handler adds does not.
fn DependencyObject::notify(
self : DependencyObject,
property : PropertyInfo,
metadata : Metadata,
old : AnyValue,
new : AnyValue,
) -> Unit raise {
let old_content = (metadata.logical_content)(old)
let new_content = (metadata.logical_content)(new)
if old_content != new_content {
self.change_content(old_content, new_content)
}
for changed in metadata.changed {
changed(self, property, old, new)
}
let handlers = self.handlers
// Not to the end of the array, because a handler can add others.
for i in 0..