Inline dom::eventdispatcher into dom::event

This commit is contained in:
Anthony Ramine 2017-01-21 15:28:49 +01:00
parent 7aea6e6ea3
commit 7dd5945237
8 changed files with 283 additions and 301 deletions

View file

@ -2,103 +2,29 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use devtools_traits::{TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::ExceptionHandling;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventBinding;
use dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods};
use dom::bindings::error::Fallible;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root, RootedReference};
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::eventdispatcher::EventStatus;
use dom::eventtarget::EventTarget;
use dom::document::Document;
use dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase};
use dom::globalscope::GlobalScope;
use dom::node::Node;
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use script_thread::Runnable;
use servo_atoms::Atom;
use std::cell::Cell;
use std::default::Default;
use time;
#[derive(JSTraceable, Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u16)]
#[derive(HeapSizeOf)]
pub enum EventPhase {
None = EventConstants::NONE,
Capturing = EventConstants::CAPTURING_PHASE,
AtTarget = EventConstants::AT_TARGET,
Bubbling = EventConstants::BUBBLING_PHASE,
}
#[derive(PartialEq, HeapSizeOf, Copy, Clone)]
pub enum EventBubbles {
Bubbles,
DoesNotBubble
}
impl From<EventBubbles> for bool {
fn from(bubbles: EventBubbles) -> Self {
match bubbles {
EventBubbles::Bubbles => true,
EventBubbles::DoesNotBubble => false
}
}
}
impl From<bool> for EventBubbles {
fn from(boolean: bool) -> Self {
match boolean {
true => EventBubbles::Bubbles,
false => EventBubbles::DoesNotBubble
}
}
}
#[derive(PartialEq, HeapSizeOf, Copy, Clone)]
pub enum EventCancelable {
Cancelable,
NotCancelable
}
impl From<EventCancelable> for bool {
fn from(bubbles: EventCancelable) -> Self {
match bubbles {
EventCancelable::Cancelable => true,
EventCancelable::NotCancelable => false
}
}
}
impl From<bool> for EventCancelable {
fn from(boolean: bool) -> Self {
match boolean {
true => EventCancelable::Cancelable,
false => EventCancelable::NotCancelable
}
}
}
/// An enum to indicate whether the default action of an event is allowed.
///
/// This should've been a bool. Instead, it's an enum, because, aside from the allowed/canceled
/// states, we also need something to stop the event from being handled again (without cancelling
/// the event entirely). For example, an Up/Down `KeyEvent` inside a `textarea` element will
/// trigger the cursor to go up/down if the text inside the element spans multiple lines. This enum
/// helps us to prevent such events from being [sent to the constellation][msg] where it will be
/// handled once again for page scrolling (which is definitely not what we'd want).
///
/// [msg]: https://doc.servo.org/script_traits/enum.ConstellationMsg.html#variant.KeyEvent
///
#[derive(JSTraceable, HeapSizeOf, Copy, Clone, PartialEq)]
pub enum EventDefault {
/// The default action of the event is allowed (constructor's default)
Allowed,
/// The default action has been prevented by calling `PreventDefault`
Prevented,
/// The event has been handled somewhere in the DOM, and it should be prevented from being
/// re-handled elsewhere. This doesn't affect the judgement of `DefaultPrevented`
Handled,
}
#[dom_struct]
pub struct Event {
reflector_: Reflector,
@ -176,6 +102,69 @@ impl Event {
self.cancelable.set(cancelable);
}
// https://dom.spec.whatwg.org/#concept-event-dispatch
pub fn dispatch(&self,
target: &EventTarget,
target_override: Option<&EventTarget>)
-> EventStatus {
assert!(!self.dispatching());
assert!(self.initialized());
assert_eq!(self.phase(), EventPhase::None);
assert!(self.GetCurrentTarget().is_none());
// Step 1.
self.mark_as_dispatching();
// Step 2.
self.set_target(target_override.unwrap_or(target));
if self.stop_propagation() {
// If the event's stop propagation flag is set, we can skip everything because
// it prevents the calls of the invoke algorithm in the spec.
// Step 10-12.
self.clear_dispatching_flags();
// Step 14.
return self.status();
}
// Step 3. The "invoke" algorithm is only used on `target` separately,
// so we don't put it in the path.
rooted_vec!(let mut event_path);
// Step 4.
if let Some(target_node) = target.downcast::<Node>() {
for ancestor in target_node.ancestors() {
event_path.push(JS::from_ref(ancestor.upcast::<EventTarget>()));
}
let top_most_ancestor_or_target =
Root::from_ref(event_path.r().last().cloned().unwrap_or(target));
if let Some(document) = Root::downcast::<Document>(top_most_ancestor_or_target) {
if self.type_() != atom!("load") && document.browsing_context().is_some() {
event_path.push(JS::from_ref(document.window().upcast()));
}
}
}
// Steps 5-9. In a separate function to short-circuit various things easily.
dispatch_to_listeners(self, target, event_path.r());
// Default action.
if let Some(target) = self.GetTarget() {
if let Some(node) = target.downcast::<Node>() {
let vtable = vtable_for(&node);
vtable.handle_event(self);
}
}
// Step 10-12.
self.clear_dispatching_flags();
// Step 14.
self.status()
}
pub fn status(&self) -> EventStatus {
match self.DefaultPrevented() {
true => EventStatus::Canceled,
@ -261,6 +250,16 @@ impl Event {
pub fn get_cancel_state(&self) -> EventDefault {
self.canceled.get()
}
pub fn set_trusted(&self, trusted: bool) {
self.trusted.set(trusted);
}
// https://html.spec.whatwg.org/multipage/#fire-a-simple-event
pub fn fire(&self, target: &EventTarget) -> EventStatus {
self.set_trusted(true);
target.dispatch_event(self)
}
}
impl EventMethods for Event {
@ -336,19 +335,92 @@ impl EventMethods for Event {
}
}
#[derive(PartialEq, HeapSizeOf, Copy, Clone)]
pub enum EventBubbles {
Bubbles,
DoesNotBubble
}
impl Event {
pub fn set_trusted(&self, trusted: bool) {
self.trusted.set(trusted);
impl From<bool> for EventBubbles {
fn from(boolean: bool) -> Self {
match boolean {
true => EventBubbles::Bubbles,
false => EventBubbles::DoesNotBubble
}
}
}
// https://html.spec.whatwg.org/multipage/#fire-a-simple-event
pub fn fire(&self, target: &EventTarget) -> EventStatus {
self.set_trusted(true);
target.dispatch_event(self)
impl From<EventBubbles> for bool {
fn from(bubbles: EventBubbles) -> Self {
match bubbles {
EventBubbles::Bubbles => true,
EventBubbles::DoesNotBubble => false
}
}
}
#[derive(PartialEq, HeapSizeOf, Copy, Clone)]
pub enum EventCancelable {
Cancelable,
NotCancelable
}
impl From<bool> for EventCancelable {
fn from(boolean: bool) -> Self {
match boolean {
true => EventCancelable::Cancelable,
false => EventCancelable::NotCancelable
}
}
}
impl From<EventCancelable> for bool {
fn from(bubbles: EventCancelable) -> Self {
match bubbles {
EventCancelable::Cancelable => true,
EventCancelable::NotCancelable => false
}
}
}
#[derive(JSTraceable, Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u16)]
#[derive(HeapSizeOf)]
pub enum EventPhase {
None = EventConstants::NONE,
Capturing = EventConstants::CAPTURING_PHASE,
AtTarget = EventConstants::AT_TARGET,
Bubbling = EventConstants::BUBBLING_PHASE,
}
/// An enum to indicate whether the default action of an event is allowed.
///
/// This should've been a bool. Instead, it's an enum, because, aside from the allowed/canceled
/// states, we also need something to stop the event from being handled again (without cancelling
/// the event entirely). For example, an Up/Down `KeyEvent` inside a `textarea` element will
/// trigger the cursor to go up/down if the text inside the element spans multiple lines. This enum
/// helps us to prevent such events from being [sent to the constellation][msg] where it will be
/// handled once again for page scrolling (which is definitely not what we'd want).
///
/// [msg]: https://doc.servo.org/script_traits/enum.ConstellationMsg.html#variant.KeyEvent
///
#[derive(JSTraceable, HeapSizeOf, Copy, Clone, PartialEq)]
pub enum EventDefault {
/// The default action of the event is allowed (constructor's default)
Allowed,
/// The default action has been prevented by calling `PreventDefault`
Prevented,
/// The event has been handled somewhere in the DOM, and it should be prevented from being
/// re-handled elsewhere. This doesn't affect the judgement of `DefaultPrevented`
Handled,
}
#[derive(PartialEq)]
pub enum EventStatus {
Canceled,
NotCanceled
}
// https://dom.spec.whatwg.org/#concept-event-fire
pub struct EventRunnable {
pub target: Trusted<EventTarget>,
@ -382,3 +454,116 @@ impl Runnable for SimpleEventRunnable {
target.fire_event(self.name);
}
}
// See dispatch_event.
// https://dom.spec.whatwg.org/#concept-event-dispatch
fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&EventTarget]) {
assert!(!event.stop_propagation());
assert!(!event.stop_immediate());
let window = match Root::downcast::<Window>(target.global()) {
Some(window) => {
if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) {
Some(window)
} else {
None
}
},
_ => None,
};
// Step 5.
event.set_phase(EventPhase::Capturing);
// Step 6.
for object in event_path.iter().rev() {
invoke(window.r(), object, event, Some(ListenerPhase::Capturing));
if event.stop_propagation() {
return;
}
}
assert!(!event.stop_propagation());
assert!(!event.stop_immediate());
// Step 7.
event.set_phase(EventPhase::AtTarget);
// Step 8.
invoke(window.r(), target, event, None);
if event.stop_propagation() {
return;
}
assert!(!event.stop_propagation());
assert!(!event.stop_immediate());
if !event.bubbles() {
return;
}
// Step 9.1.
event.set_phase(EventPhase::Bubbling);
// Step 9.2.
for object in event_path {
invoke(window.r(), object, event, Some(ListenerPhase::Bubbling));
if event.stop_propagation() {
return;
}
}
}
// https://dom.spec.whatwg.org/#concept-event-listener-invoke
fn invoke(window: Option<&Window>,
object: &EventTarget,
event: &Event,
specific_listener_phase: Option<ListenerPhase>) {
// Step 1.
assert!(!event.stop_propagation());
// Steps 2-3.
let listeners = object.get_listeners_for(&event.type_(), specific_listener_phase);
// Step 4.
event.set_current_target(object);
// Step 5.
inner_invoke(window, object, event, &listeners);
// TODO: step 6.
}
// https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
fn inner_invoke(window: Option<&Window>,
object: &EventTarget,
event: &Event,
listeners: &[CompiledEventListener])
-> bool {
// Step 1.
let mut found = false;
// Step 2.
for listener in listeners {
// Steps 2.1 and 2.3-2.4 are not done because `listeners` contain only the
// relevant ones for this invoke call during the dispatch algorithm.
// Step 2.2.
found = true;
// TODO: step 2.5.
// Step 2.6.
let marker = TimelineMarker::start("DOMEvent".to_owned());
listener.call_or_handle_event(object, event, ExceptionHandling::Report);
if let Some(window) = window {
window.emit_timeline_marker(marker.end());
}
if event.stop_immediate() {
return found;
}
// TODO: step 2.7.
}
// Step 3.
found
}