///|
/// How far the root can be from the element that raises an event, as `MAX_ELEMENTS_IN_ROUTE` in WPF.
let max_route : Int32 = 4096

///|
/// 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.
pub fn[A] raise_event(
  sender : @dependency.DependencyObject,
  args : RoutedEventArgs[A],
) -> Unit raise {
  let routing = args.routing
  let label = match routing.event() {
    Some(event) => "\{event}"
    None => "raise_event"
  }
  @dependency.guard_nesting(label, () => routing.raise_on(sender))
}

///|
fn RoutingArgs::raise_on(
  self : RoutingArgs,
  sender : @dependency.DependencyObject,
) -> Unit raise {
  let event = self.need_event()
  event.check_element(sender)
  self.set_source(Some(Object(sender)))
  for entry in event.handlers_from(sender) {
    let (element, handlers) = entry
    for handler in handlers {
      if !self.handled || handler.handled_events_too {
        (handler.run)(element, self)
      }
    }
  }
  self.source = self.original_source
}

///|
/// The elements with handlers for a raise on `sender`, in the order of the route, each with copies of its handlers and those of
/// its types in the order in which they run.
fn RoutedEventInfo::handlers_from(
  self : RoutedEventInfo,
  sender : @dependency.DependencyObject,
) -> Array[(@dependency.DependencyObject, Array[Handler])] raise @dependency.DependencyError {
  let of_types = sender
    .registry()
    .extension(event_table_key)
    .bind(table => table.class_handlers.get(self))
  let found = []
  // Those of the next element that has some.
  let mut handlers = []
  let mut distance = 0
  for next = Some(sender); next is Some(element); {
    if distance > max_route {
      raise TreeLoop(
        "Potential cycle in tree found while building the event route.",
      )
    }
    distance += 1
    if of_types is Some(of_types) {
      for next = Some(element.owner_type()); next is Some(owner); {
        if of_types.get(owner) is Some(of_type) {
          handlers.append(of_type)
        }
        continue owner.base_type()
      }
    }
    if element.extension(handlers_key) is Some(of_element) {
      for handler in of_element {
        if handler.event == self {
          handlers.push(handler)
        }
      }
    }
    if !handlers.is_empty() {
      found.push((element, handlers))
      handlers = []
    }
    continue if self.strategy is Direct { None } else { element.route_parent() }
  }
  if self.strategy is Tunnel {
    found.rev_in_place()
  }
  found
}