[iOS] getAssistedNodeInformation crashes getting the bounding box if it doesn't have...
[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     bool 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 = nullptr;
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 nullptr;
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         if (!eventPath.updateTouchLists(*toTouchEvent(event.get())))
344             return true;
345     }
346 #endif
347
348     ChildNodesLazySnapshot::takeChildNodesLazySnapshot();
349
350     event->setTarget(&eventTargetRespectingTargetRules(*node));
351     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
352     ASSERT(event->target());
353     WindowEventContext windowEventContext(node.get(), eventPath.lastContextIfExists());
354
355     InputElementClickState clickHandlingState;
356     if (isHTMLInputElement(node.get()))
357         toHTMLInputElement(*node).willDispatchEvent(*event, clickHandlingState);
358
359     if (!event->propagationStopped() && !eventPath.isEmpty())
360         dispatchEventInDOM(*event, eventPath, windowEventContext);
361
362     event->setTarget(&eventTargetRespectingTargetRules(*node));
363     event->setCurrentTarget(0);
364     event->setEventPhase(0);
365
366     if (clickHandlingState.stateful)
367         toHTMLInputElement(*node).didDispatchClickEvent(*event, clickHandlingState);
368
369     // Call default event handlers. While the DOM does have a concept of preventing
370     // default handling, the detail of which handlers are called is an internal
371     // implementation detail and not part of the DOM.
372     if (!event->defaultPrevented() && !event->defaultHandled())
373         callDefaultEventHandlersInTheBubblingOrder(*event, eventPath);
374
375     // Ensure that after event dispatch, the event's target object is the
376     // outermost shadow DOM boundary.
377     event->setTarget(windowEventContext.target());
378     event->setCurrentTarget(0);
379
380     return !event->defaultPrevented();
381 }
382
383 static inline bool shouldEventCrossShadowBoundary(Event& event, ShadowRoot& shadowRoot, EventTarget& target)
384 {
385     Node* targetNode = target.toNode();
386 #if ENABLE(FULLSCREEN_API) && ENABLE(VIDEO)
387     // Video-only full screen is a mode where we use the shadow DOM as an implementation
388     // detail that should not be detectable by the web content.
389     if (targetNode) {
390         if (Element* element = targetNode->document().webkitCurrentFullScreenElement()) {
391             // FIXME: We assume that if the full screen element is a media element that it's
392             // the video-only full screen. Both here and elsewhere. But that is probably wrong.
393             if (element->isMediaElement() && shadowRoot.hostElement() == element)
394                 return false;
395         }
396     }
397 #endif
398
399     // WebKit never allowed selectstart event to cross the the shadow DOM boundary.
400     // Changing this breaks existing sites.
401     // See https://bugs.webkit.org/show_bug.cgi?id=52195 for details.
402     const AtomicString& eventType = event.type();
403     bool targetIsInShadowRoot = targetNode && &targetNode->treeScope().rootNode() == &shadowRoot;
404     return !targetIsInShadowRoot
405         || !(eventType == eventNames().abortEvent
406             || eventType == eventNames().changeEvent
407             || eventType == eventNames().errorEvent
408             || eventType == eventNames().loadEvent
409             || eventType == eventNames().resetEvent
410             || eventType == eventNames().resizeEvent
411             || eventType == eventNames().scrollEvent
412             || eventType == eventNames().selectEvent
413             || eventType == eventNames().selectstartEvent);
414 }
415
416 static Node* nodeOrHostIfPseudoElement(Node* node)
417 {
418     return node->isPseudoElement() ? toPseudoElement(node)->hostElement() : node;
419 }
420
421 EventPath::EventPath(Node& targetNode, Event& event)
422 {
423     bool inDocument = targetNode.inDocument();
424     bool isSVGElement = targetNode.isSVGElement();
425     bool isMouseOrFocusEvent = event.isMouseEvent() || event.isFocusEvent();
426 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
427     bool isTouchEvent = event.isTouchEvent();
428 #endif
429     EventTarget* target = 0;
430
431     Node* node = nodeOrHostIfPseudoElement(&targetNode);
432     while (node) {
433         if (!target || !isSVGElement) // FIXME: This code doesn't make sense once we've climbed out of the SVG subtree in a HTML document.
434             target = &eventTargetRespectingTargetRules(*node);
435         for (; node; node = node->parentNode()) {
436             EventTarget& currentTarget = eventTargetRespectingTargetRules(*node);
437             if (isMouseOrFocusEvent)
438                 m_path.append(std::make_unique<MouseOrFocusEventContext>(node, &currentTarget, target));
439 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
440             else if (isTouchEvent)
441                 m_path.append(std::make_unique<TouchEventContext>(node, &currentTarget, target));
442 #endif
443             else
444                 m_path.append(std::make_unique<EventContext>(node, &currentTarget, target));
445             if (!inDocument)
446                 return;
447             if (node->isShadowRoot())
448                 break;
449         }
450         if (!node || !shouldEventCrossShadowBoundary(event, *toShadowRoot(node), *target))
451             return;
452         node = toShadowRoot(node)->hostElement();
453     }
454 }
455
456 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
457 static void addRelatedNodeResolversForTouchList(Vector<EventRelatedNodeResolver, 16>& touchTargetResolvers, TouchList* touchList, TouchEventContext::TouchListType type)
458 {
459     const size_t touchListSize = touchList->length();
460     for (size_t i = 0; i < touchListSize; ++i)
461         touchTargetResolvers.append(EventRelatedNodeResolver(*touchList->item(i), type));
462 }
463
464 bool EventPath::updateTouchLists(const TouchEvent& touchEvent)
465 {
466     if (!touchEvent.touches() || !touchEvent.targetTouches() || !touchEvent.changedTouches())
467         return false;
468     
469     Vector<EventRelatedNodeResolver, 16> touchTargetResolvers;
470     const size_t touchNodeCount = touchEvent.touches()->length() + touchEvent.targetTouches()->length() + touchEvent.changedTouches()->length();
471     touchTargetResolvers.reserveInitialCapacity(touchNodeCount);
472
473     addRelatedNodeResolversForTouchList(touchTargetResolvers, touchEvent.touches(), TouchEventContext::Touches);
474     addRelatedNodeResolversForTouchList(touchTargetResolvers, touchEvent.targetTouches(), TouchEventContext::TargetTouches);
475     addRelatedNodeResolversForTouchList(touchTargetResolvers, touchEvent.changedTouches(), TouchEventContext::ChangedTouches);
476
477     ASSERT(touchTargetResolvers.size() == touchNodeCount);
478     size_t eventPathSize = m_path.size();
479     for (size_t i = 0; i < eventPathSize; ++i) {
480         TouchEventContext& context = toTouchEventContext(*m_path[i]);
481         Node& nodeToMoveTo = *context.node();
482         for (size_t resolverIndex = 0; resolverIndex < touchNodeCount; ++resolverIndex) {
483             EventRelatedNodeResolver& currentResolver = touchTargetResolvers[resolverIndex];
484             Node* nodeInCurrentTreeScope = currentResolver.moveToParentOrShadowHost(nodeToMoveTo);
485             ASSERT(currentResolver.touch());
486             context.touchList(currentResolver.touchListType())->append(currentResolver.touch()->cloneWithNewTarget(nodeInCurrentTreeScope));
487         }
488     }
489     return true;
490 }
491 #endif
492
493 void EventPath::setRelatedTarget(Node& origin, EventTarget& relatedTarget)
494 {
495     Node* relatedNode = relatedTarget.toNode();
496     if (!relatedNode)
497         return;
498
499     EventRelatedNodeResolver resolver(*relatedNode);
500
501     bool originIsRelatedTarget = &origin == relatedNode;
502     Node& rootNodeInOriginTreeScope = origin.treeScope().rootNode();
503
504     size_t eventPathSize = m_path.size();
505     size_t i = 0;
506     while (i < eventPathSize) {
507         Node* contextNode = m_path[i]->node();
508         Node* currentRelatedNode = resolver.moveToParentOrShadowHost(*contextNode);
509         if (!originIsRelatedTarget && m_path[i]->target() == currentRelatedNode)
510             break;
511         toMouseOrFocusEventContext(*m_path[i]).setRelatedTarget(currentRelatedNode);
512         i++;
513         if (originIsRelatedTarget && &rootNodeInOriginTreeScope == contextNode)
514             break;
515     }
516     m_path.shrink(i);
517 }
518
519 bool EventPath::hasEventListeners(const AtomicString& eventType) const
520 {
521     for (size_t i = 0; i < m_path.size(); i++) {
522         if (m_path[i]->node()->hasEventListeners(eventType))
523             return true;
524     }
525
526     return false;
527 }
528
529 }