REGRESSION (r157328): popover to check into flight ba.com dismisses instantly when...
[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(Node& origin, 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 (&newTreeScope == &m_relatedNodeTreeScope)
152             m_relatedNodeInCurrentTreeScope = &m_relatedNode;
153         else if (m_relatedNodeInCurrentTreeScope) {
154             ASSERT(m_currentTreeScope);
155             m_relatedNodeInCurrentTreeScope = &newTarget;
156         } else {
157             if (!m_currentTreeScope) {
158                 TreeScope* newTreeScopeAncestor = &newTreeScope;
159                 do {
160                     m_relatedNodeInCurrentTreeScope = findHostOfTreeScopeInTargetTreeScope(m_relatedNodeTreeScope, *newTreeScopeAncestor);
161                     newTreeScopeAncestor = newTreeScopeAncestor->parentTreeScope();
162                     if (newTreeScopeAncestor == &m_relatedNodeTreeScope) {
163                         m_relatedNodeInCurrentTreeScope = &m_relatedNode;
164                         break;
165                     }
166                 } while (newTreeScopeAncestor && !m_relatedNodeInCurrentTreeScope);
167             }
168             ASSERT(m_relatedNodeInCurrentTreeScope || findHostOfTreeScopeInTargetTreeScope(newTreeScope, m_relatedNodeTreeScope)
169                 || &newTreeScope.documentScope() != &m_relatedNodeTreeScope.documentScope());
170         }
171
172         m_currentTreeScope = &newTreeScope;
173
174         return m_relatedNodeInCurrentTreeScope;
175     }
176
177     static Node* findHostOfTreeScopeInTargetTreeScope(const TreeScope& startingTreeScope, const TreeScope& targetScope)
178     {
179         ASSERT(&targetScope != &startingTreeScope);
180         Node* previousHost = 0;
181         for (const TreeScope* scope = &startingTreeScope; scope; scope = scope->parentTreeScope()) {
182             if (scope == &targetScope) {
183                 ASSERT(previousHost);
184                 ASSERT_WITH_SECURITY_IMPLICATION(&previousHost->treeScope() == &targetScope);
185                 return previousHost;
186             }
187             if (scope->rootNode().isShadowRoot())
188                 previousHost = toShadowRoot(scope->rootNode()).hostElement();
189             else
190                 ASSERT_WITH_SECURITY_IMPLICATION(!scope->parentTreeScope());
191         }
192         return 0;
193     }
194
195 private:
196     Node& m_relatedNode;
197     const TreeScope& m_relatedNodeTreeScope;
198     Node* m_relatedNodeInCurrentTreeScope;
199     TreeScope* m_currentTreeScope;
200 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
201     Touch* m_touch;
202     TouchEventContext::TouchListType m_touchListType;
203 #endif
204 };
205
206 inline EventTarget& eventTargetRespectingTargetRules(Node& referenceNode)
207 {
208     if (referenceNode.isPseudoElement()) {
209         EventTarget* hostElement = toPseudoElement(referenceNode).hostElement();
210         ASSERT(hostElement);
211         return *hostElement;
212     }
213
214     if (!referenceNode.isSVGElement() || !referenceNode.isInShadowTree())
215         return referenceNode;
216
217     // Spec: The event handling for the non-exposed tree works as if the referenced element had been textually included
218     // as a deeply cloned child of the 'use' element, except that events are dispatched to the SVGElementInstance objects
219     auto& rootNode = referenceNode.treeScope().rootNode();
220     Element* shadowHostElement = rootNode.isShadowRoot() ? toShadowRoot(rootNode).hostElement() : nullptr;
221     // At this time, SVG nodes are not supported in non-<use> shadow trees.
222     if (!shadowHostElement || !shadowHostElement->hasTagName(SVGNames::useTag))
223         return referenceNode;
224     SVGUseElement* useElement = toSVGUseElement(shadowHostElement);
225     if (SVGElementInstance* instance = useElement->instanceForShadowTreeElement(&referenceNode))
226         return *instance;
227
228     return referenceNode;
229 }
230
231 void EventDispatcher::dispatchScopedEvent(Node& node, PassRefPtr<Event> event)
232 {
233     // We need to set the target here because it can go away by the time we actually fire the event.
234     event->setTarget(&eventTargetRespectingTargetRules(node));
235     ScopedEventQueue::instance().enqueueEvent(event);
236 }
237
238 void EventDispatcher::dispatchSimulatedClick(Element* element, Event* underlyingEvent, SimulatedClickMouseEventOptions mouseEventOptions, SimulatedClickVisualOptions visualOptions)
239 {
240     if (element->isDisabledFormControl())
241         return;
242
243     DEPRECATED_DEFINE_STATIC_LOCAL(HashSet<Element*>, elementsDispatchingSimulatedClicks, ());
244     if (!elementsDispatchingSimulatedClicks.add(element).isNewEntry)
245         return;
246
247     if (mouseEventOptions == SendMouseOverUpDownEvents)
248         dispatchEvent(element, SimulatedMouseEvent::create(eventNames().mouseoverEvent, element->document().defaultView(), underlyingEvent, element));
249
250     if (mouseEventOptions != SendNoEvents)
251         dispatchEvent(element, SimulatedMouseEvent::create(eventNames().mousedownEvent, element->document().defaultView(), underlyingEvent, element));
252     element->setActive(true, visualOptions == ShowPressedLook);
253     if (mouseEventOptions != SendNoEvents)
254         dispatchEvent(element, SimulatedMouseEvent::create(eventNames().mouseupEvent, element->document().defaultView(), underlyingEvent, element));
255     element->setActive(false);
256
257     // always send click
258     dispatchEvent(element, SimulatedMouseEvent::create(eventNames().clickEvent, element->document().defaultView(), underlyingEvent, element));
259
260     elementsDispatchingSimulatedClicks.remove(element);
261 }
262
263 static void callDefaultEventHandlersInTheBubblingOrder(Event& event, const EventPath& path)
264 {
265     // Non-bubbling events call only one default event handler, the one for the target.
266     path.contextAt(0).node()->defaultEventHandler(&event);
267     ASSERT(!event.defaultPrevented());
268
269     if (event.defaultHandled() || !event.bubbles())
270         return;
271
272     size_t size = path.size();
273     for (size_t i = 1; i < size; ++i) {
274         path.contextAt(i).node()->defaultEventHandler(&event);
275         ASSERT(!event.defaultPrevented());
276         if (event.defaultHandled())
277             return;
278     }
279 }
280
281 static void dispatchEventInDOM(Event& event, const EventPath& path, WindowEventContext& windowEventContext)
282 {
283     // Trigger capturing event handlers, starting at the top and working our way down.
284     event.setEventPhase(Event::CAPTURING_PHASE);
285
286     // We don't dispatch load events to the window. This quirk was originally
287     // added because Mozilla doesn't propagate load events to the window object.
288     bool shouldFireEventAtWindow = event.type() != eventNames().loadEvent;
289     if (shouldFireEventAtWindow && windowEventContext.handleLocalEvents(event) && event.propagationStopped())
290         return;
291
292     for (size_t i = path.size() - 1; i > 0; --i) {
293         const EventContext& eventContext = path.contextAt(i);
294         if (eventContext.currentTargetSameAsTarget())
295             continue;
296         eventContext.handleLocalEvents(event);
297         if (event.propagationStopped())
298             return;
299     }
300
301     event.setEventPhase(Event::AT_TARGET);
302     path.contextAt(0).handleLocalEvents(event);
303     if (event.propagationStopped())
304         return;
305
306     // Trigger bubbling event handlers, starting at the bottom and working our way up.
307     size_t size = path.size();
308     for (size_t i = 1; i < size; ++i) {
309         const EventContext& eventContext = path.contextAt(i);
310         if (eventContext.currentTargetSameAsTarget())
311             event.setEventPhase(Event::AT_TARGET);
312         else if (event.bubbles() && !event.cancelBubble())
313             event.setEventPhase(Event::BUBBLING_PHASE);
314         else
315             continue;
316         eventContext.handleLocalEvents(event);
317         if (event.propagationStopped())
318             return;
319     }
320     if (event.bubbles() && !event.cancelBubble()) {
321         event.setEventPhase(Event::BUBBLING_PHASE);
322         if (shouldFireEventAtWindow)
323             windowEventContext.handleLocalEvents(event);
324     }
325 }
326
327 bool EventDispatcher::dispatchEvent(Node* origin, PassRefPtr<Event> prpEvent)
328 {
329     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
330     if (!prpEvent)
331         return true;
332
333     ASSERT(origin);
334     RefPtr<Node> node(origin);
335     RefPtr<Event> event(prpEvent);
336     RefPtr<FrameView> view = node->document().view();
337     EventPath eventPath(*node, *event);
338
339     if (EventTarget* relatedTarget = event->relatedTarget())
340         eventPath.setRelatedTarget(*node, *relatedTarget);
341 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
342     if (event->isTouchEvent())
343         eventPath.updateTouchLists(*toTouchEvent(event.get()));
344 #endif
345
346     ChildNodesLazySnapshot::takeChildNodesLazySnapshot();
347
348     event->setTarget(&eventTargetRespectingTargetRules(*node));
349     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
350     ASSERT(event->target());
351     WindowEventContext windowEventContext(node.get(), eventPath.lastContextIfExists());
352
353     InputElementClickState clickHandlingState;
354     if (isHTMLInputElement(node.get()))
355         toHTMLInputElement(*node).willDispatchEvent(*event, clickHandlingState);
356
357     if (!event->propagationStopped() && !eventPath.isEmpty())
358         dispatchEventInDOM(*event, eventPath, windowEventContext);
359
360     event->setTarget(&eventTargetRespectingTargetRules(*node));
361     event->setCurrentTarget(0);
362     event->setEventPhase(0);
363
364     if (clickHandlingState.stateful)
365         toHTMLInputElement(*node).didDispatchClickEvent(*event, clickHandlingState);
366
367     // Call default event handlers. While the DOM does have a concept of preventing
368     // default handling, the detail of which handlers are called is an internal
369     // implementation detail and not part of the DOM.
370     if (!event->defaultPrevented() && !event->defaultHandled())
371         callDefaultEventHandlersInTheBubblingOrder(*event, eventPath);
372
373     // Ensure that after event dispatch, the event's target object is the
374     // outermost shadow DOM boundary.
375     event->setTarget(windowEventContext.target());
376     event->setCurrentTarget(0);
377
378     return !event->defaultPrevented();
379 }
380
381 static inline bool shouldEventCrossShadowBoundary(Event& event, ShadowRoot& shadowRoot, EventTarget& target)
382 {
383     Node* targetNode = target.toNode();
384 #if ENABLE(FULLSCREEN_API) && ENABLE(VIDEO)
385     // Video-only full screen is a mode where we use the shadow DOM as an implementation
386     // detail that should not be detectable by the web content.
387     if (targetNode) {
388         if (Element* element = targetNode->document().webkitCurrentFullScreenElement()) {
389             // FIXME: We assume that if the full screen element is a media element that it's
390             // the video-only full screen. Both here and elsewhere. But that is probably wrong.
391             if (element->isMediaElement() && shadowRoot.hostElement() == element)
392                 return false;
393         }
394     }
395 #endif
396
397     // WebKit never allowed selectstart event to cross the the shadow DOM boundary.
398     // Changing this breaks existing sites.
399     // See https://bugs.webkit.org/show_bug.cgi?id=52195 for details.
400     const AtomicString& eventType = event.type();
401     bool targetIsInShadowRoot = targetNode && &targetNode->treeScope().rootNode() == &shadowRoot;
402     return !targetIsInShadowRoot
403         || !(eventType == eventNames().abortEvent
404             || eventType == eventNames().changeEvent
405             || eventType == eventNames().errorEvent
406             || eventType == eventNames().loadEvent
407             || eventType == eventNames().resetEvent
408             || eventType == eventNames().resizeEvent
409             || eventType == eventNames().scrollEvent
410             || eventType == eventNames().selectEvent
411             || eventType == eventNames().selectstartEvent);
412 }
413
414 static Node* nodeOrHostIfPseudoElement(Node* node)
415 {
416     return node->isPseudoElement() ? toPseudoElement(node)->hostElement() : node;
417 }
418
419 EventPath::EventPath(Node& targetNode, Event& event)
420 {
421     bool inDocument = targetNode.inDocument();
422     bool isSVGElement = targetNode.isSVGElement();
423     bool isMouseOrFocusEvent = event.isMouseEvent() || event.isFocusEvent();
424 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
425     bool isTouchEvent = event.isTouchEvent();
426 #endif
427     EventTarget* target = 0;
428
429     Node* node = nodeOrHostIfPseudoElement(&targetNode);
430     while (node) {
431         if (!target || !isSVGElement) // FIXME: This code doesn't make sense once we've climbed out of the SVG subtree in a HTML document.
432             target = &eventTargetRespectingTargetRules(*node);
433         for (; node; node = node->parentNode()) {
434             EventTarget& currentTarget = eventTargetRespectingTargetRules(*node);
435             if (isMouseOrFocusEvent)
436                 m_path.append(std::make_unique<MouseOrFocusEventContext>(node, &currentTarget, target));
437 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
438             else if (isTouchEvent)
439                 m_path.append(std::make_unique<TouchEventContext>(node, &currentTarget, target));
440 #endif
441             else
442                 m_path.append(std::make_unique<EventContext>(node, &currentTarget, target));
443             if (!inDocument)
444                 return;
445             if (node->isShadowRoot())
446                 break;
447         }
448         if (!node || !shouldEventCrossShadowBoundary(event, *toShadowRoot(node), *target))
449             return;
450         node = toShadowRoot(node)->hostElement();
451     }
452 }
453
454 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
455 static void addRelatedNodeResolversForTouchList(Vector<EventRelatedNodeResolver, 16>& touchTargetResolvers, TouchList* touchList, TouchEventContext::TouchListType type)
456 {
457     const size_t touchListSize = touchList->length();
458     for (size_t i = 0; i < touchListSize; ++i)
459         touchTargetResolvers.append(EventRelatedNodeResolver(*touchList->item(i), type));
460 }
461
462 void EventPath::updateTouchLists(const TouchEvent& touchEvent)
463 {
464     Vector<EventRelatedNodeResolver, 16> touchTargetResolvers;
465     const size_t touchNodeCount = touchEvent.touches()->length() + touchEvent.targetTouches()->length() + touchEvent.changedTouches()->length();
466     touchTargetResolvers.reserveInitialCapacity(touchNodeCount);
467
468     addRelatedNodeResolversForTouchList(touchTargetResolvers, touchEvent.touches(), TouchEventContext::Touches);
469     addRelatedNodeResolversForTouchList(touchTargetResolvers, touchEvent.targetTouches(), TouchEventContext::TargetTouches);
470     addRelatedNodeResolversForTouchList(touchTargetResolvers, touchEvent.changedTouches(), TouchEventContext::ChangedTouches);
471
472     ASSERT(touchTargetResolvers.size() == touchNodeCount);
473     size_t eventPathSize = m_path.size();
474     for (size_t i = 0; i < eventPathSize; ++i) {
475         TouchEventContext& context = toTouchEventContext(*m_path[i]);
476         Node& nodeToMoveTo = *context.node();
477         for (size_t resolverIndex = 0; resolverIndex < touchNodeCount; ++resolverIndex) {
478             EventRelatedNodeResolver& currentResolver = touchTargetResolvers[resolverIndex];
479             Node* nodeInCurrentTreeScope = currentResolver.moveToParentOrShadowHost(nodeToMoveTo);
480             ASSERT(currentResolver.touch());
481             context.touchList(currentResolver.touchListType())->append(currentResolver.touch()->cloneWithNewTarget(nodeInCurrentTreeScope));
482         }
483     }
484 }
485 #endif
486
487 void EventPath::setRelatedTarget(Node& origin, EventTarget& relatedTarget)
488 {
489     Node* relatedNode = relatedTarget.toNode();
490     if (!relatedNode)
491         return;
492
493     EventRelatedNodeResolver resolver(*relatedNode);
494
495     bool originIsRelatedTarget = &origin == relatedNode;
496     Node& rootNodeInOriginTreeScope = origin.treeScope().rootNode();
497
498     size_t eventPathSize = m_path.size();
499     size_t i = 0;
500     while (i < eventPathSize) {
501         Node* contextNode = m_path[i]->node();
502         Node* currentRelatedNode = resolver.moveToParentOrShadowHost(*contextNode);
503         if (!originIsRelatedTarget && m_path[i]->target() == currentRelatedNode)
504             break;
505         toMouseOrFocusEventContext(*m_path[i]).setRelatedTarget(currentRelatedNode);
506         i++;
507         if (originIsRelatedTarget && &rootNodeInOriginTreeScope == contextNode)
508             break;
509     }
510     m_path.shrink(i);
511 }
512
513 bool EventPath::hasEventListeners(const AtomicString& eventType) const
514 {
515     for (size_t i = 0; i < m_path.size(); i++) {
516         if (m_path[i]->node()->hasEventListeners(eventType))
517             return true;
518     }
519
520     return false;
521 }
522
523 }