5ebc38f41eec8b2686fbda95866c1b6cd35acce7
[WebKit-https.git] / Source / WebCore / dom / EventDispatcher.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2001 Dirk Mueller (mueller@kde.org)
5  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2013 Apple Inc. All rights reserved.
6  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
7  * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8  * Copyright (C) 2010, 2011, 2012, 2013 Google Inc. All rights reserved.
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public License
21  * along with this library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  */
25
26 #include "config.h"
27 #include "EventDispatcher.h"
28
29 #include "EventContext.h"
30 #include "FocusEvent.h"
31 #include "FrameView.h"
32 #include "HTMLInputElement.h"
33 #include "HTMLMediaElement.h"
34 #include "InsertionPoint.h"
35 #include "InspectorInstrumentation.h"
36 #include "MouseEvent.h"
37 #include "PseudoElement.h"
38 #include "ScopedEventQueue.h"
39 #include "ShadowRoot.h"
40 #include "SVGElementInstance.h"
41 #include "SVGNames.h"
42 #include "SVGUseElement.h"
43 #include "TouchEvent.h"
44
45 namespace WebCore {
46
47 class WindowEventContext {
48 public:
49     WindowEventContext(PassRefPtr<Node>, const EventContext*);
50
51     DOMWindow* window() const { return m_window.get(); }
52     EventTarget* target() const { return m_target.get(); }
53     bool handleLocalEvents(Event&);
54
55 private:
56     RefPtr<DOMWindow> m_window;
57     RefPtr<EventTarget> m_target;
58 };
59
60 WindowEventContext::WindowEventContext(PassRefPtr<Node> node, const EventContext* topEventContext)
61 {
62     Node* topLevelContainer = topEventContext ? topEventContext->node() : node.get();
63     if (!topLevelContainer->isDocumentNode())
64         return;
65
66     m_window = toDocument(topLevelContainer)->domWindow();
67     m_target = topEventContext ? topEventContext->target() : node.get();
68 }
69
70 bool WindowEventContext::handleLocalEvents(Event& event)
71 {
72     if (!m_window)
73         return false;
74
75     event.setTarget(m_target.get());
76     event.setCurrentTarget(m_window.get());
77     m_window->fireEventListeners(&event);
78     return true;
79 }
80
81 class EventPath {
82 public:
83     EventPath(Node& origin, Event&);
84
85     bool isEmpty() const { return m_path.isEmpty(); }
86     size_t size() const { return m_path.size(); }
87     const EventContext& contextAt(size_t i) const { return *m_path[i]; }
88     EventContext& contextAt(size_t i) { return *m_path[i]; }
89
90 #if ENABLE(TOUCH_EVENTS)
91     void updateTouchLists(const TouchEvent&);
92 #endif
93     void setRelatedTarget(EventTarget&);
94
95     bool hasEventListeners(const AtomicString& eventType) const;
96
97     EventContext* lastContextIfExists() { return m_path.isEmpty() ? 0 : m_path.last().get(); }
98
99 private:
100 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
101     void updateTouchListsInEventPath(const TouchList*, TouchEventContext::TouchListType);
102 #endif
103
104     Vector<std::unique_ptr<EventContext>, 32> m_path;
105 };
106
107 class EventRelatedNodeResolver {
108 public:
109     EventRelatedNodeResolver(Node& relatedNode)
110         : m_relatedNode(relatedNode)
111         , m_relatedNodeTreeScope(relatedNode.treeScope())
112         , m_relatedNodeInCurrentTreeScope(nullptr)
113         , m_currentTreeScope(nullptr)
114 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
115         , m_touch(0)
116         , m_touchListType(TouchEventContext::NotTouchList)
117 #endif
118     {
119     }
120
121 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
122     EventRelatedNodeResolver(Touch& touch, TouchEventContext::TouchListType touchListType)
123         : m_relatedNode(*touch.target()->toNode())
124         , m_relatedNodeTreeScope(m_relatedNode.treeScope())
125         , m_relatedNodeInCurrentTreeScope(nullptr)
126         , m_currentTreeScope(nullptr)
127         , m_touch(&touch)
128         , m_touchListType(touchListType)
129     {
130         ASSERT(touch.target()->toNode());
131     }
132 #endif
133
134 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
135     Touch* touch() const { return m_touch; }
136     TouchEventContext::TouchListType touchListType() const { return m_touchListType; }
137 #endif
138
139     Node* moveToParentOrShadowHost(Node& newTarget)
140     {
141         TreeScope& newTreeScope = newTarget.treeScope();
142         if (&newTreeScope == m_currentTreeScope)
143             return m_relatedNodeInCurrentTreeScope;
144
145         if (m_currentTreeScope) {
146             ASSERT(m_currentTreeScope->rootNode().isShadowRoot());
147             ASSERT(&newTarget == toShadowRoot(m_currentTreeScope->rootNode()).hostElement());
148             ASSERT(m_currentTreeScope->parentTreeScope() == &newTreeScope);
149         }
150
151         if (m_relatedNodeInCurrentTreeScope) { // relatedNode is under the current tree scope
152             ASSERT(m_currentTreeScope);
153             m_relatedNodeInCurrentTreeScope = &newTarget;
154         } else if (&newTreeScope == &m_relatedNodeTreeScope) // relatedNode is in the current tree scope;
155             m_relatedNodeInCurrentTreeScope = &m_relatedNode;
156         // Otherwise, we haven't reached the tree scope that contains relatedNode yet.
157
158         m_currentTreeScope = &newTreeScope;
159
160         return m_relatedNodeInCurrentTreeScope;
161     }
162
163 private:
164     Node& m_relatedNode;
165     const TreeScope& m_relatedNodeTreeScope;
166     Node* m_relatedNodeInCurrentTreeScope;
167     TreeScope* m_currentTreeScope;
168 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
169     Touch* m_touch;
170     TouchEventContext::TouchListType m_touchListType;
171 #endif
172 };
173
174 inline EventTarget& eventTargetRespectingTargetRules(Node& referenceNode)
175 {
176     if (referenceNode.isPseudoElement()) {
177         EventTarget* hostElement = toPseudoElement(referenceNode).hostElement();
178         ASSERT(hostElement);
179         return *hostElement;
180     }
181
182     if (!referenceNode.isSVGElement() || !referenceNode.isInShadowTree())
183         return referenceNode;
184
185     // Spec: The event handling for the non-exposed tree works as if the referenced element had been textually included
186     // as a deeply cloned child of the 'use' element, except that events are dispatched to the SVGElementInstance objects
187     auto& rootNode = referenceNode.treeScope().rootNode();
188     Element* shadowHostElement = rootNode.isShadowRoot() ? toShadowRoot(rootNode).hostElement() : nullptr;
189     // At this time, SVG nodes are not supported in non-<use> shadow trees.
190     if (!shadowHostElement || !shadowHostElement->hasTagName(SVGNames::useTag))
191         return referenceNode;
192     SVGUseElement* useElement = toSVGUseElement(shadowHostElement);
193     if (SVGElementInstance* instance = useElement->instanceForShadowTreeElement(&referenceNode))
194         return *instance;
195
196     return referenceNode;
197 }
198
199 void EventDispatcher::dispatchScopedEvent(Node& node, PassRefPtr<Event> event)
200 {
201     // We need to set the target here because it can go away by the time we actually fire the event.
202     event->setTarget(&eventTargetRespectingTargetRules(node));
203     ScopedEventQueue::instance().enqueueEvent(event);
204 }
205
206 void EventDispatcher::dispatchSimulatedClick(Element* element, Event* underlyingEvent, SimulatedClickMouseEventOptions mouseEventOptions, SimulatedClickVisualOptions visualOptions)
207 {
208     if (element->isDisabledFormControl())
209         return;
210
211     DEPRECATED_DEFINE_STATIC_LOCAL(HashSet<Element*>, elementsDispatchingSimulatedClicks, ());
212     if (!elementsDispatchingSimulatedClicks.add(element).isNewEntry)
213         return;
214
215     if (mouseEventOptions == SendMouseOverUpDownEvents)
216         dispatchEvent(element, SimulatedMouseEvent::create(eventNames().mouseoverEvent, element->document().defaultView(), underlyingEvent, element));
217
218     if (mouseEventOptions != SendNoEvents)
219         dispatchEvent(element, SimulatedMouseEvent::create(eventNames().mousedownEvent, element->document().defaultView(), underlyingEvent, element));
220     element->setActive(true, visualOptions == ShowPressedLook);
221     if (mouseEventOptions != SendNoEvents)
222         dispatchEvent(element, SimulatedMouseEvent::create(eventNames().mouseupEvent, element->document().defaultView(), underlyingEvent, element));
223     element->setActive(false);
224
225     // always send click
226     dispatchEvent(element, SimulatedMouseEvent::create(eventNames().clickEvent, element->document().defaultView(), underlyingEvent, element));
227
228     elementsDispatchingSimulatedClicks.remove(element);
229 }
230
231 static void callDefaultEventHandlersInTheBubblingOrder(Event& event, const EventPath& path)
232 {
233     // Non-bubbling events call only one default event handler, the one for the target.
234     path.contextAt(0).node()->defaultEventHandler(&event);
235     ASSERT(!event.defaultPrevented());
236
237     if (event.defaultHandled() || !event.bubbles())
238         return;
239
240     size_t size = path.size();
241     for (size_t i = 1; i < size; ++i) {
242         path.contextAt(i).node()->defaultEventHandler(&event);
243         ASSERT(!event.defaultPrevented());
244         if (event.defaultHandled())
245             return;
246     }
247 }
248
249 static void dispatchEventInDOM(Event& event, const EventPath& path, WindowEventContext& windowEventContext)
250 {
251     // Trigger capturing event handlers, starting at the top and working our way down.
252     event.setEventPhase(Event::CAPTURING_PHASE);
253
254     // We don't dispatch load events to the window. This quirk was originally
255     // added because Mozilla doesn't propagate load events to the window object.
256     bool shouldFireEventAtWindow = event.type() != eventNames().loadEvent;
257     if (shouldFireEventAtWindow && windowEventContext.handleLocalEvents(event) && event.propagationStopped())
258         return;
259
260     for (size_t i = path.size() - 1; i > 0; --i) {
261         const EventContext& eventContext = path.contextAt(i);
262         if (eventContext.currentTargetSameAsTarget())
263             continue;
264         eventContext.handleLocalEvents(event);
265         if (event.propagationStopped())
266             return;
267     }
268
269     event.setEventPhase(Event::AT_TARGET);
270     path.contextAt(0).handleLocalEvents(event);
271     if (event.propagationStopped())
272         return;
273
274     // Trigger bubbling event handlers, starting at the bottom and working our way up.
275     size_t size = path.size();
276     for (size_t i = 1; i < size; ++i) {
277         const EventContext& eventContext = path.contextAt(i);
278         if (eventContext.currentTargetSameAsTarget())
279             event.setEventPhase(Event::AT_TARGET);
280         else if (event.bubbles() && !event.cancelBubble())
281             event.setEventPhase(Event::BUBBLING_PHASE);
282         else
283             continue;
284         eventContext.handleLocalEvents(event);
285         if (event.propagationStopped())
286             return;
287     }
288     if (event.bubbles() && !event.cancelBubble()) {
289         event.setEventPhase(Event::BUBBLING_PHASE);
290         if (shouldFireEventAtWindow)
291             windowEventContext.handleLocalEvents(event);
292     }
293 }
294
295 bool EventDispatcher::dispatchEvent(Node* origin, PassRefPtr<Event> prpEvent)
296 {
297     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
298     if (!prpEvent)
299         return true;
300
301     ASSERT(origin);
302     RefPtr<Node> node(origin);
303     RefPtr<Event> event(prpEvent);
304     RefPtr<FrameView> view = node->document().view();
305     EventPath eventPath(*node, *event);
306
307     if (EventTarget* relatedTarget = event->relatedTarget())
308         eventPath.setRelatedTarget(*relatedTarget);
309 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
310     if (event->isTouchEvent())
311         eventPath.updateTouchLists(*toTouchEvent(event.get()));
312 #endif
313
314     ChildNodesLazySnapshot::takeChildNodesLazySnapshot();
315
316     event->setTarget(&eventTargetRespectingTargetRules(*node));
317     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
318     ASSERT(event->target());
319     WindowEventContext windowEventContext(node.get(), eventPath.lastContextIfExists());
320
321     InputElementClickState clickHandlingState;
322     if (isHTMLInputElement(node.get()))
323         toHTMLInputElement(*node).willDispatchEvent(*event, clickHandlingState);
324
325     if (!event->propagationStopped() && !eventPath.isEmpty())
326         dispatchEventInDOM(*event, eventPath, windowEventContext);
327
328     event->setTarget(&eventTargetRespectingTargetRules(*node));
329     event->setCurrentTarget(0);
330     event->setEventPhase(0);
331
332     if (clickHandlingState.stateful)
333         toHTMLInputElement(*node).didDispatchClickEvent(*event, clickHandlingState);
334
335     // Call default event handlers. While the DOM does have a concept of preventing
336     // default handling, the detail of which handlers are called is an internal
337     // implementation detail and not part of the DOM.
338     if (!event->defaultPrevented() && !event->defaultHandled())
339         callDefaultEventHandlersInTheBubblingOrder(*event, eventPath);
340
341     // Ensure that after event dispatch, the event's target object is the
342     // outermost shadow DOM boundary.
343     event->setTarget(windowEventContext.target());
344     event->setCurrentTarget(0);
345
346     return !event->defaultPrevented();
347 }
348
349 static inline bool shouldEventCrossShadowBoundary(Event& event, ShadowRoot& shadowRoot, EventTarget& target)
350 {
351     Node* targetNode = target.toNode();
352 #if ENABLE(FULLSCREEN_API) && ENABLE(VIDEO)
353     // Video-only full screen is a mode where we use the shadow DOM as an implementation
354     // detail that should not be detectable by the web content.
355     if (targetNode) {
356         if (Element* element = targetNode->document().webkitCurrentFullScreenElement()) {
357             // FIXME: We assume that if the full screen element is a media element that it's
358             // the video-only full screen. Both here and elsewhere. But that is probably wrong.
359             if (element->isMediaElement() && shadowRoot.hostElement() == element)
360                 return false;
361         }
362     }
363 #endif
364
365     // WebKit never allowed selectstart event to cross the the shadow DOM boundary.
366     // Changing this breaks existing sites.
367     // See https://bugs.webkit.org/show_bug.cgi?id=52195 for details.
368     const AtomicString& eventType = event.type();
369     bool targetIsInShadowRoot = targetNode && &targetNode->treeScope().rootNode() == &shadowRoot;
370     return !targetIsInShadowRoot
371         || !(eventType == eventNames().abortEvent
372             || eventType == eventNames().changeEvent
373             || eventType == eventNames().errorEvent
374             || eventType == eventNames().loadEvent
375             || eventType == eventNames().resetEvent
376             || eventType == eventNames().resizeEvent
377             || eventType == eventNames().scrollEvent
378             || eventType == eventNames().selectEvent
379             || eventType == eventNames().selectstartEvent);
380 }
381
382 static Node* nodeOrHostIfPseudoElement(Node* node)
383 {
384     return node->isPseudoElement() ? toPseudoElement(node)->hostElement() : node;
385 }
386
387 EventPath::EventPath(Node& targetNode, Event& event)
388 {
389     bool inDocument = targetNode.inDocument();
390     bool isSVGElement = targetNode.isSVGElement();
391     bool isMouseOrFocusEvent = event.isMouseEvent() || event.isFocusEvent();
392 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
393     bool isTouchEvent = event.isTouchEvent();
394 #endif
395     EventTarget* target = 0;
396
397     Node* node = nodeOrHostIfPseudoElement(&targetNode);
398     while (node) {
399         if (!target || !isSVGElement) // FIXME: This code doesn't make sense once we've climbed out of the SVG subtree in a HTML document.
400             target = &eventTargetRespectingTargetRules(*node);
401         for (; node; node = node->parentNode()) {
402             EventTarget& currentTarget = eventTargetRespectingTargetRules(*node);
403             if (isMouseOrFocusEvent)
404                 m_path.append(std::make_unique<MouseOrFocusEventContext>(node, &currentTarget, target));
405 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
406             else if (isTouchEvent)
407                 m_path.append(std::make_unique<TouchEventContext>(node, &currentTarget, target));
408 #endif
409             else
410                 m_path.append(std::make_unique<EventContext>(node, &currentTarget, target));
411             if (!inDocument)
412                 return;
413             if (node->isShadowRoot())
414                 break;
415         }
416         if (!node || !shouldEventCrossShadowBoundary(event, *toShadowRoot(node), *target))
417             return;
418         node = toShadowRoot(node)->hostElement();
419     }
420 }
421
422 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
423 static void addRelatedNodeResolversForTouchList(Vector<EventRelatedNodeResolver, 16>& touchTargetResolvers, TouchList* touchList, TouchEventContext::TouchListType type)
424 {
425     const size_t touchListSize = touchList->length();
426     for (size_t i = 0; i < touchListSize; ++i)
427         touchTargetResolvers.append(EventRelatedNodeResolver(*touchList->item(i), type));
428 }
429
430 void EventPath::updateTouchLists(const TouchEvent& touchEvent)
431 {
432     Vector<EventRelatedNodeResolver, 16> touchTargetResolvers;
433     const size_t touchNodeCount = touchEvent.touches()->length() + touchEvent.targetTouches()->length() + touchEvent.changedTouches()->length();
434     touchTargetResolvers.reserveInitialCapacity(touchNodeCount);
435
436     addRelatedNodeResolversForTouchList(touchTargetResolvers, touchEvent.touches(), TouchEventContext::Touches);
437     addRelatedNodeResolversForTouchList(touchTargetResolvers, touchEvent.targetTouches(), TouchEventContext::TargetTouches);
438     addRelatedNodeResolversForTouchList(touchTargetResolvers, touchEvent.changedTouches(), TouchEventContext::ChangedTouches);
439
440     ASSERT(touchTargetResolvers.size() == touchNodeCount);
441     size_t eventPathSize = m_path.size();
442     for (size_t i = 0; i < eventPathSize; ++i) {
443         TouchEventContext& context = toTouchEventContext(*m_path[i]);
444         Node& nodeToMoveTo = *context.node();
445         for (size_t resolverIndex = 0; resolverIndex < touchNodeCount; ++resolverIndex) {
446             EventRelatedNodeResolver& currentResolver = touchTargetResolvers[resolverIndex];
447             Node* nodeInCurrentTreeScope = currentResolver.moveToParentOrShadowHost(nodeToMoveTo);
448             ASSERT(currentResolver.touch());
449             context.touchList(currentResolver.touchListType())->append(currentResolver.touch()->cloneWithNewTarget(nodeInCurrentTreeScope));
450         }
451     }
452 }
453 #endif
454
455 void EventPath::setRelatedTarget(EventTarget& relatedTarget)
456 {
457     Node* relatedNode = relatedTarget.toNode();
458     if (!relatedNode)
459         return;
460
461     EventRelatedNodeResolver resolver(*relatedNode);
462
463     size_t eventPathSize = m_path.size();
464     for (size_t i = 0; i < eventPathSize; i++)
465         toMouseOrFocusEventContext(*m_path[i]).setRelatedTarget(resolver.moveToParentOrShadowHost(*m_path[i]->node()));
466 }
467
468 bool EventPath::hasEventListeners(const AtomicString& eventType) const
469 {
470     for (size_t i = 0; i < m_path.size(); i++) {
471         if (m_path[i]->node()->hasEventListeners(eventType))
472             return true;
473     }
474
475     return false;
476 }
477
478 }