f0a28c1331c5bb3088d53e7243dbaf4eeb63e7bd
[WebKit-https.git] / Source / WebCore / inspector / agents / InspectorDOMAgent.cpp
1 /*
2  * Copyright (C) 2009-2017 Apple Inc. All rights reserved.
3  * Copyright (C) 2011 Google Inc. All rights reserved.
4  * Copyright (C) 2009 Joseph Pecoraro
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer.
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "InspectorDOMAgent.h"
33
34 #include "AXObjectCache.h"
35 #include "AccessibilityNodeObject.h"
36 #include "Attr.h"
37 #include "CSSComputedStyleDeclaration.h"
38 #include "CSSPropertyNames.h"
39 #include "CSSPropertySourceData.h"
40 #include "CSSRule.h"
41 #include "CSSRuleList.h"
42 #include "CSSStyleRule.h"
43 #include "CSSStyleSheet.h"
44 #include "CharacterData.h"
45 #include "CommandLineAPIHost.h"
46 #include "ContainerNode.h"
47 #include "Cookie.h"
48 #include "CookieJar.h"
49 #include "DOMEditor.h"
50 #include "DOMException.h"
51 #include "DOMPatchSupport.h"
52 #include "DOMWindow.h"
53 #include "Document.h"
54 #include "DocumentType.h"
55 #include "Editing.h"
56 #include "Element.h"
57 #include "Event.h"
58 #include "EventListener.h"
59 #include "EventNames.h"
60 #include "Frame.h"
61 #include "FrameTree.h"
62 #include "FrameView.h"
63 #include "FullscreenManager.h"
64 #include "HTMLElement.h"
65 #include "HTMLFrameOwnerElement.h"
66 #include "HTMLMediaElement.h"
67 #include "HTMLNames.h"
68 #include "HTMLParserIdioms.h"
69 #include "HTMLScriptElement.h"
70 #include "HTMLStyleElement.h"
71 #include "HTMLTemplateElement.h"
72 #include "HTMLVideoElement.h"
73 #include "HitTestResult.h"
74 #include "InspectorCSSAgent.h"
75 #include "InspectorClient.h"
76 #include "InspectorController.h"
77 #include "InspectorHistory.h"
78 #include "InspectorNodeFinder.h"
79 #include "InspectorOverlay.h"
80 #include "InspectorPageAgent.h"
81 #include "InstrumentingAgents.h"
82 #include "IntRect.h"
83 #include "JSDOMBindingSecurity.h"
84 #include "JSEventListener.h"
85 #include "JSNode.h"
86 #include "MutationEvent.h"
87 #include "Node.h"
88 #include "NodeList.h"
89 #include "Page.h"
90 #include "Pasteboard.h"
91 #include "PseudoElement.h"
92 #include "RenderStyle.h"
93 #include "RenderStyleConstants.h"
94 #include "ScriptState.h"
95 #include "ShadowRoot.h"
96 #include "StaticNodeList.h"
97 #include "StyleProperties.h"
98 #include "StyleResolver.h"
99 #include "StyleSheetList.h"
100 #include "Text.h"
101 #include "TextNodeTraversal.h"
102 #include "Timer.h"
103 #include "VideoPlaybackQuality.h"
104 #include "WebInjectedScriptManager.h"
105 #include "XPathResult.h"
106 #include "markup.h"
107 #include <JavaScriptCore/IdentifiersFactory.h>
108 #include <JavaScriptCore/InjectedScript.h>
109 #include <JavaScriptCore/InjectedScriptManager.h>
110 #include <JavaScriptCore/JSCInlines.h>
111 #include <pal/crypto/CryptoDigest.h>
112 #include <wtf/text/Base64.h>
113 #include <wtf/text/CString.h>
114 #include <wtf/text/WTFString.h>
115
116 namespace WebCore {
117
118 using namespace Inspector;
119
120 using namespace HTMLNames;
121
122 static const size_t maxTextSize = 10000;
123 static const UChar ellipsisUChar[] = { 0x2026, 0 };
124
125 static Color parseColor(const JSON::Object* colorObject)
126 {
127     if (!colorObject)
128         return Color::transparent;
129
130     int r = 0;
131     int g = 0;
132     int b = 0;
133     if (!colorObject->getInteger("r", r) || !colorObject->getInteger("g", g) || !colorObject->getInteger("b", b))
134         return Color::transparent;
135
136     double a = 1.0;
137     if (!colorObject->getDouble("a", a))
138         return Color(r, g, b);
139
140     // Clamp alpha to the [0..1] range.
141     if (a < 0)
142         a = 0;
143     else if (a > 1)
144         a = 1;
145
146     return Color(r, g, b, static_cast<int>(a * 255));
147 }
148
149 static Color parseConfigColor(const String& fieldName, const JSON::Object* configObject)
150 {
151     RefPtr<JSON::Object> colorObject;
152     configObject->getObject(fieldName, colorObject);
153
154     return parseColor(colorObject.get());
155 }
156
157 static bool parseQuad(const JSON::Array& quadArray, FloatQuad* quad)
158 {
159     const size_t coordinatesInQuad = 8;
160     double coordinates[coordinatesInQuad];
161     if (quadArray.length() != coordinatesInQuad)
162         return false;
163     for (size_t i = 0; i < coordinatesInQuad; ++i) {
164         if (!quadArray.get(i)->asDouble(*(coordinates + i)))
165             return false;
166     }
167     quad->setP1(FloatPoint(coordinates[0], coordinates[1]));
168     quad->setP2(FloatPoint(coordinates[2], coordinates[3]));
169     quad->setP3(FloatPoint(coordinates[4], coordinates[5]));
170     quad->setP4(FloatPoint(coordinates[6], coordinates[7]));
171
172     return true;
173 }
174
175 class RevalidateStyleAttributeTask {
176     WTF_MAKE_FAST_ALLOCATED;
177 public:
178     RevalidateStyleAttributeTask(InspectorDOMAgent*);
179     void scheduleFor(Element*);
180     void reset() { m_timer.stop(); }
181     void timerFired();
182
183 private:
184     InspectorDOMAgent* m_domAgent;
185     Timer m_timer;
186     HashSet<RefPtr<Element>> m_elements;
187 };
188
189 RevalidateStyleAttributeTask::RevalidateStyleAttributeTask(InspectorDOMAgent* domAgent)
190     : m_domAgent(domAgent)
191     , m_timer(*this, &RevalidateStyleAttributeTask::timerFired)
192 {
193 }
194
195 void RevalidateStyleAttributeTask::scheduleFor(Element* element)
196 {
197     m_elements.add(element);
198     if (!m_timer.isActive())
199         m_timer.startOneShot(0_s);
200 }
201
202 void RevalidateStyleAttributeTask::timerFired()
203 {
204     // The timer is stopped on m_domAgent destruction, so this method will never be called after m_domAgent has been destroyed.
205     Vector<Element*> elements;
206     for (auto& element : m_elements)
207         elements.append(element.get());
208     m_domAgent->styleAttributeInvalidated(elements);
209
210     m_elements.clear();
211 }
212
213 class InspectableNode final : public CommandLineAPIHost::InspectableObject {
214 public:
215     explicit InspectableNode(Node* node)
216         : m_node(node)
217     {
218     }
219
220     JSC::JSValue get(JSC::ExecState& state) final
221     {
222         return InspectorDOMAgent::nodeAsScriptValue(state, m_node.get());
223     }
224 private:
225     RefPtr<Node> m_node;
226 };
227
228 class EventFiredCallback final : public EventListener {
229 public:
230     static Ref<EventFiredCallback> create(InspectorDOMAgent& domAgent)
231     {
232         return adoptRef(*new EventFiredCallback(domAgent));
233     }
234
235     bool operator==(const EventListener& other) const final
236     {
237         return this == &other;
238     }
239
240     void handleEvent(ScriptExecutionContext&, Event& event) final
241     {
242         if (!is<Node>(event.target()) || m_domAgent.m_dispatchedEvents.contains(&event))
243             return;
244
245         auto* node = downcast<Node>(event.target());
246         int nodeId = m_domAgent.pushNodePathToFrontend(node);
247         if (!nodeId)
248             return;
249
250         m_domAgent.m_dispatchedEvents.add(&event);
251
252         RefPtr<JSON::Object> data = JSON::Object::create();
253
254 #if ENABLE(FULLSCREEN_API)
255         if (event.type() == eventNames().webkitfullscreenchangeEvent)
256             data->setBoolean("enabled"_s, !!node->document().fullscreenManager().fullscreenElement());
257 #endif // ENABLE(FULLSCREEN_API)
258
259         auto timestamp = m_domAgent.m_environment.executionStopwatch()->elapsedTime().seconds();
260         m_domAgent.m_frontendDispatcher->didFireEvent(nodeId, event.type(), timestamp, data->size() ? WTFMove(data) : nullptr);
261     }
262
263 private:
264     EventFiredCallback(InspectorDOMAgent& domAgent)
265         : EventListener(EventListener::CPPEventListenerType)
266         , m_domAgent(domAgent)
267     {
268     }
269
270     InspectorDOMAgent& m_domAgent;
271 };
272
273 String InspectorDOMAgent::toErrorString(ExceptionCode ec)
274 {
275     return ec ? String(DOMException::name(ec)) : emptyString();
276 }
277
278 String InspectorDOMAgent::toErrorString(Exception&& exception)
279 {
280     return DOMException::name(exception.code());
281 }
282
283 InspectorDOMAgent::InspectorDOMAgent(PageAgentContext& context, InspectorOverlay* overlay)
284     : InspectorAgentBase("DOM"_s, context)
285     , m_injectedScriptManager(context.injectedScriptManager)
286     , m_frontendDispatcher(makeUnique<Inspector::DOMFrontendDispatcher>(context.frontendRouter))
287     , m_backendDispatcher(Inspector::DOMBackendDispatcher::create(context.backendDispatcher, this))
288     , m_inspectedPage(context.inspectedPage)
289     , m_overlay(overlay)
290 #if ENABLE(VIDEO)
291     , m_mediaMetricsTimer(*this, &InspectorDOMAgent::mediaMetricsTimerFired)
292 #endif
293 {
294 }
295
296 InspectorDOMAgent::~InspectorDOMAgent()
297 {
298     reset();
299     ASSERT(!m_searchingForNode);
300 }
301
302 void InspectorDOMAgent::didCreateFrontendAndBackend(Inspector::FrontendRouter*, Inspector::BackendDispatcher*)
303 {
304     m_history = makeUnique<InspectorHistory>();
305     m_domEditor = makeUnique<DOMEditor>(*m_history);
306
307     m_instrumentingAgents.setInspectorDOMAgent(this);
308     m_document = m_inspectedPage.mainFrame().document();
309
310 #if ENABLE(VIDEO)
311     if (m_document)
312         addEventListenersToNode(*m_document);
313
314     for (auto* mediaElement : HTMLMediaElement::allMediaElements())
315         addEventListenersToNode(*mediaElement);
316 #endif
317 }
318
319 void InspectorDOMAgent::willDestroyFrontendAndBackend(Inspector::DisconnectReason)
320 {
321     m_history.reset();
322     m_domEditor.reset();
323     m_nodeToFocus = nullptr;
324     m_mousedOverNode = nullptr;
325     m_inspectedNode = nullptr;
326
327     ErrorString unused;
328     setSearchingForNode(unused, false, nullptr, false);
329     hideHighlight(unused);
330
331     m_instrumentingAgents.setInspectorDOMAgent(nullptr);
332     m_documentRequested = false;
333     reset();
334 }
335
336 Vector<Document*> InspectorDOMAgent::documents()
337 {
338     Vector<Document*> result;
339     for (Frame* frame = m_document->frame(); frame; frame = frame->tree().traverseNext()) {
340         Document* document = frame->document();
341         if (!document)
342             continue;
343         result.append(document);
344     }
345     return result;
346 }
347
348 void InspectorDOMAgent::reset()
349 {
350     if (m_history)
351         m_history->reset();
352     m_searchResults.clear();
353     discardBindings();
354     if (m_revalidateStyleAttrTask)
355         m_revalidateStyleAttrTask->reset();
356     m_document = nullptr;
357 }
358
359 void InspectorDOMAgent::setDocument(Document* document)
360 {
361     if (document == m_document.get())
362         return;
363
364     reset();
365
366     m_document = document;
367
368     if (!m_documentRequested)
369         return;
370
371     // Immediately communicate null document or document that has finished loading.
372     if (!document || !document->parsing())
373         m_frontendDispatcher->documentUpdated();
374 }
375
376 void InspectorDOMAgent::releaseDanglingNodes()
377 {
378     m_danglingNodeToIdMaps.clear();
379 }
380
381 int InspectorDOMAgent::bind(Node* node, NodeToIdMap* nodesMap)
382 {
383     int id = nodesMap->get(node);
384     if (id)
385         return id;
386     id = m_lastNodeId++;
387     nodesMap->set(node, id);
388     m_idToNode.set(id, node);
389     m_idToNodesMap.set(id, nodesMap);
390     return id;
391 }
392
393 void InspectorDOMAgent::unbind(Node* node, NodeToIdMap* nodesMap)
394 {
395     int id = nodesMap->get(node);
396     if (!id)
397         return;
398
399     m_idToNode.remove(id);
400
401     if (node->isFrameOwnerElement()) {
402         const HTMLFrameOwnerElement* frameOwner = static_cast<const HTMLFrameOwnerElement*>(node);
403         if (Document* contentDocument = frameOwner->contentDocument())
404             unbind(contentDocument, nodesMap);
405     }
406
407     if (is<Element>(*node)) {
408         Element& element = downcast<Element>(*node);
409         if (ShadowRoot* root = element.shadowRoot())
410             unbind(root, nodesMap);
411         if (PseudoElement* beforeElement = element.beforePseudoElement())
412             unbind(beforeElement, nodesMap);
413         if (PseudoElement* afterElement = element.afterPseudoElement())
414             unbind(afterElement, nodesMap);
415     }
416
417     nodesMap->remove(node);
418
419     if (auto* cssAgent = m_instrumentingAgents.inspectorCSSAgent())
420         cssAgent->didRemoveDOMNode(*node, id);
421
422     if (m_childrenRequested.remove(id)) {
423         // FIXME: Would be better to do this iteratively rather than recursively.
424         for (Node* child = innerFirstChild(node); child; child = innerNextSibling(child))
425             unbind(child, nodesMap);
426     }
427 }
428
429 Node* InspectorDOMAgent::assertNode(ErrorString& errorString, int nodeId)
430 {
431     Node* node = nodeForId(nodeId);
432     if (!node) {
433         errorString = "Could not find node with given id"_s;
434         return nullptr;
435     }
436     return node;
437 }
438
439 Document* InspectorDOMAgent::assertDocument(ErrorString& errorString, int nodeId)
440 {
441     Node* node = assertNode(errorString, nodeId);
442     if (!node)
443         return nullptr;
444     if (!is<Document>(*node)) {
445         errorString = "Document is not available"_s;
446         return nullptr;
447     }
448     return downcast<Document>(node);
449 }
450
451 Element* InspectorDOMAgent::assertElement(ErrorString& errorString, int nodeId)
452 {
453     Node* node = assertNode(errorString, nodeId);
454     if (!node)
455         return nullptr;
456     if (!is<Element>(*node)) {
457         errorString = "Node is not an Element"_s;
458         return nullptr;
459     }
460     return downcast<Element>(node);
461 }
462
463 Node* InspectorDOMAgent::assertEditableNode(ErrorString& errorString, int nodeId)
464 {
465     Node* node = assertNode(errorString, nodeId);
466     if (!node)
467         return nullptr;
468     if (node->isInUserAgentShadowTree()) {
469         errorString = "Cannot edit nodes in user agent shadow trees"_s;
470         return nullptr;
471     }
472     if (node->isPseudoElement()) {
473         errorString = "Cannot edit pseudo elements"_s;
474         return nullptr;
475     }
476     return node;
477 }
478
479 Element* InspectorDOMAgent::assertEditableElement(ErrorString& errorString, int nodeId)
480 {
481     Element* element = assertElement(errorString, nodeId);
482     if (!element)
483         return nullptr;
484     if (element->isInUserAgentShadowTree()) {
485         errorString = "Cannot edit elements in user agent shadow trees"_s;
486         return nullptr;
487     }
488     if (element->isPseudoElement()) {
489         errorString = "Cannot edit pseudo elements"_s;
490         return nullptr;
491     }
492     return element;
493 }
494
495 void InspectorDOMAgent::getDocument(ErrorString& errorString, RefPtr<Inspector::Protocol::DOM::Node>& root)
496 {
497     m_documentRequested = true;
498
499     if (!m_document) {
500         errorString = "Document is not available"_s;
501         return;
502     }
503
504     // Reset backend state.
505     RefPtr<Document> document = m_document;
506     reset();
507     m_document = document;
508
509     root = buildObjectForNode(m_document.get(), 2, &m_documentNodeToIdMap);
510
511     if (m_nodeToFocus)
512         focusNode();
513 }
514
515 void InspectorDOMAgent::pushChildNodesToFrontend(int nodeId, int depth)
516 {
517     Node* node = nodeForId(nodeId);
518     if (!node || (node->nodeType() != Node::ELEMENT_NODE && node->nodeType() != Node::DOCUMENT_NODE && node->nodeType() != Node::DOCUMENT_FRAGMENT_NODE))
519         return;
520
521     NodeToIdMap* nodeMap = m_idToNodesMap.get(nodeId);
522
523     if (m_childrenRequested.contains(nodeId)) {
524         if (depth <= 1)
525             return;
526
527         depth--;
528
529         for (node = innerFirstChild(node); node; node = innerNextSibling(node)) {
530             int childNodeId = nodeMap->get(node);
531             ASSERT(childNodeId);
532             pushChildNodesToFrontend(childNodeId, depth);
533         }
534
535         return;
536     }
537
538     auto children = buildArrayForContainerChildren(node, depth, nodeMap);
539     m_frontendDispatcher->setChildNodes(nodeId, WTFMove(children));
540 }
541
542 void InspectorDOMAgent::discardBindings()
543 {
544     m_documentNodeToIdMap.clear();
545     m_idToNode.clear();
546     m_dispatchedEvents.clear();
547     m_eventListenerEntries.clear();
548     releaseDanglingNodes();
549     m_childrenRequested.clear();
550 }
551
552 int InspectorDOMAgent::pushNodeToFrontend(ErrorString& errorString, int documentNodeId, Node* nodeToPush)
553 {
554     Document* document = assertDocument(errorString, documentNodeId);
555     if (!document)
556         return 0;
557     if (&nodeToPush->document() != document) {
558         errorString = "Node is not part of the document with given id"_s;
559         return 0;
560     }
561
562     return pushNodePathToFrontend(nodeToPush);
563 }
564
565 Node* InspectorDOMAgent::nodeForId(int id)
566 {
567     if (!m_idToNode.isValidKey(id))
568         return nullptr;
569
570     return m_idToNode.get(id);
571 }
572
573 void InspectorDOMAgent::requestChildNodes(ErrorString& errorString, int nodeId, const int* depth)
574 {
575     int sanitizedDepth;
576
577     if (!depth)
578         sanitizedDepth = 1;
579     else if (*depth == -1)
580         sanitizedDepth = INT_MAX;
581     else if (*depth > 0)
582         sanitizedDepth = *depth;
583     else {
584         errorString = "Please provide a positive integer as a depth or -1 for entire subtree"_s;
585         return;
586     }
587
588     pushChildNodesToFrontend(nodeId, sanitizedDepth);
589 }
590
591 void InspectorDOMAgent::querySelector(ErrorString& errorString, int nodeId, const String& selectors, int* elementId)
592 {
593     *elementId = 0;
594     Node* node = assertNode(errorString, nodeId);
595     if (!node)
596         return;
597     if (!is<ContainerNode>(*node)) {
598         assertElement(errorString, nodeId);
599         return;
600     }
601
602     auto queryResult = downcast<ContainerNode>(*node).querySelector(selectors);
603     if (queryResult.hasException()) {
604         errorString = "DOM Error while querying"_s;
605         return;
606     }
607
608     if (auto* element = queryResult.releaseReturnValue())
609         *elementId = pushNodePathToFrontend(element);
610 }
611
612 void InspectorDOMAgent::querySelectorAll(ErrorString& errorString, int nodeId, const String& selectors, RefPtr<JSON::ArrayOf<int>>& result)
613 {
614     Node* node = assertNode(errorString, nodeId);
615     if (!node)
616         return;
617     if (!is<ContainerNode>(*node)) {
618         assertElement(errorString, nodeId);
619         return;
620     }
621
622     auto queryResult = downcast<ContainerNode>(*node).querySelectorAll(selectors);
623     if (queryResult.hasException()) {
624         errorString = "DOM Error while querying"_s;
625         return;
626     }
627
628     auto nodes = queryResult.releaseReturnValue();
629     result = JSON::ArrayOf<int>::create();
630     for (unsigned i = 0; i < nodes->length(); ++i)
631         result->addItem(pushNodePathToFrontend(nodes->item(i)));
632 }
633
634 int InspectorDOMAgent::pushNodePathToFrontend(Node* nodeToPush)
635 {
636     ASSERT(nodeToPush);  // Invalid input
637
638     if (!m_document)
639         return 0;
640     if (!m_documentNodeToIdMap.contains(m_document))
641         return 0;
642
643     // Return id in case the node is known.
644     int result = m_documentNodeToIdMap.get(nodeToPush);
645     if (result)
646         return result;
647
648     Node* node = nodeToPush;
649     Vector<Node*> path;
650     NodeToIdMap* danglingMap = 0;
651
652     while (true) {
653         Node* parent = innerParentNode(node);
654         if (!parent) {
655             // Node being pushed is detached -> push subtree root.
656             auto newMap = makeUnique<NodeToIdMap>();
657             danglingMap = newMap.get();
658             m_danglingNodeToIdMaps.append(newMap.release());
659             auto children = JSON::ArrayOf<Inspector::Protocol::DOM::Node>::create();
660             children->addItem(buildObjectForNode(node, 0, danglingMap));
661             m_frontendDispatcher->setChildNodes(0, WTFMove(children));
662             break;
663         } else {
664             path.append(parent);
665             if (m_documentNodeToIdMap.get(parent))
666                 break;
667             else
668                 node = parent;
669         }
670     }
671
672     NodeToIdMap* map = danglingMap ? danglingMap : &m_documentNodeToIdMap;
673     for (int i = path.size() - 1; i >= 0; --i) {
674         int nodeId = map->get(path.at(i));
675         ASSERT(nodeId);
676         pushChildNodesToFrontend(nodeId);
677     }
678     return map->get(nodeToPush);
679 }
680
681 int InspectorDOMAgent::boundNodeId(const Node* node)
682 {
683     return m_documentNodeToIdMap.get(const_cast<Node*>(node));
684 }
685
686 void InspectorDOMAgent::setAttributeValue(ErrorString& errorString, int elementId, const String& name, const String& value)
687 {
688     Element* element = assertEditableElement(errorString, elementId);
689     if (!element)
690         return;
691
692     m_domEditor->setAttribute(*element, name, value, errorString);
693 }
694
695 void InspectorDOMAgent::setAttributesAsText(ErrorString& errorString, int elementId, const String& text, const String* name)
696 {
697     Element* element = assertEditableElement(errorString, elementId);
698     if (!element)
699         return;
700
701     auto parsedElement = createHTMLElement(element->document(), spanTag);
702     auto result = parsedElement.get().setInnerHTML("<span " + text + "></span>");
703     if (result.hasException()) {
704         errorString = toErrorString(result.releaseException());
705         return;
706     }
707
708     Node* child = parsedElement->firstChild();
709     if (!child) {
710         errorString = "Could not parse value as attributes"_s;
711         return;
712     }
713
714     Element* childElement = downcast<Element>(child);
715     if (!childElement->hasAttributes() && name) {
716         m_domEditor->removeAttribute(*element, *name, errorString);
717         return;
718     }
719
720     bool foundOriginalAttribute = false;
721     for (const Attribute& attribute : childElement->attributesIterator()) {
722         // Add attribute pair
723         foundOriginalAttribute = foundOriginalAttribute || (name && attribute.name().toString() == *name);
724         if (!m_domEditor->setAttribute(*element, attribute.name().toString(), attribute.value(), errorString))
725             return;
726     }
727
728     if (!foundOriginalAttribute && name && !name->stripWhiteSpace().isEmpty())
729         m_domEditor->removeAttribute(*element, *name, errorString);
730 }
731
732 void InspectorDOMAgent::removeAttribute(ErrorString& errorString, int elementId, const String& name)
733 {
734     Element* element = assertEditableElement(errorString, elementId);
735     if (!element)
736         return;
737
738     m_domEditor->removeAttribute(*element, name, errorString);
739 }
740
741 void InspectorDOMAgent::removeNode(ErrorString& errorString, int nodeId)
742 {
743     Node* node = assertEditableNode(errorString, nodeId);
744     if (!node)
745         return;
746
747     ContainerNode* parentNode = node->parentNode();
748     if (!parentNode) {
749         errorString = "Cannot remove detached node"_s;
750         return;
751     }
752
753     m_domEditor->removeChild(*parentNode, *node, errorString);
754 }
755
756 void InspectorDOMAgent::setNodeName(ErrorString& errorString, int nodeId, const String& tagName, int* newId)
757 {
758     *newId = 0;
759
760     RefPtr<Node> oldNode = nodeForId(nodeId);
761     if (!is<Element>(oldNode))
762         return;
763
764     auto createElementResult = oldNode->document().createElementForBindings(tagName);
765     if (createElementResult.hasException())
766         return;
767     auto newElement = createElementResult.releaseReturnValue();
768
769     // Copy over the original node's attributes.
770     newElement->cloneAttributesFromElement(downcast<Element>(*oldNode));
771
772     // Copy over the original node's children.
773     RefPtr<Node> child;
774     while ((child = oldNode->firstChild())) {
775         if (!m_domEditor->insertBefore(newElement, *child, 0, errorString))
776             return;
777     }
778
779     // Replace the old node with the new node
780     RefPtr<ContainerNode> parent = oldNode->parentNode();
781     if (!m_domEditor->insertBefore(*parent, newElement.copyRef(), oldNode->nextSibling(), errorString))
782         return;
783     if (!m_domEditor->removeChild(*parent, *oldNode, errorString))
784         return;
785
786     *newId = pushNodePathToFrontend(newElement.ptr());
787     if (m_childrenRequested.contains(nodeId))
788         pushChildNodesToFrontend(*newId);
789 }
790
791 void InspectorDOMAgent::getOuterHTML(ErrorString& errorString, int nodeId, WTF::String* outerHTML)
792 {
793     Node* node = assertNode(errorString, nodeId);
794     if (!node)
795         return;
796
797     *outerHTML = serializeFragment(*node, SerializedNodes::SubtreeIncludingNode);
798 }
799
800 void InspectorDOMAgent::setOuterHTML(ErrorString& errorString, int nodeId, const String& outerHTML)
801 {
802     if (!nodeId) {
803         DOMPatchSupport { *m_domEditor, *m_document }.patchDocument(outerHTML);
804         return;
805     }
806
807     Node* node = assertEditableNode(errorString, nodeId);
808     if (!node)
809         return;
810
811     Document& document = node->document();
812     if (!document.isHTMLDocument() && !document.isXMLDocument()) {
813         errorString = "Not an HTML/XML document"_s;
814         return;
815     }
816
817     Node* newNode = nullptr;
818     if (!m_domEditor->setOuterHTML(*node, outerHTML, newNode, errorString))
819         return;
820
821     if (!newNode) {
822         // The only child node has been deleted.
823         return;
824     }
825
826     int newId = pushNodePathToFrontend(newNode);
827
828     bool childrenRequested = m_childrenRequested.contains(nodeId);
829     if (childrenRequested)
830         pushChildNodesToFrontend(newId);
831 }
832
833 void InspectorDOMAgent::insertAdjacentHTML(ErrorString& errorString, int nodeId, const String& position, const String& html)
834 {
835     Node* node = assertEditableNode(errorString, nodeId);
836     if (!node)
837         return;
838
839     if (!is<Element>(node)) {
840         errorString = "Can only call insertAdjacentHTML on Elements."_s;
841         return;
842     }
843
844     m_domEditor->insertAdjacentHTML(downcast<Element>(*node), position, html, errorString);
845 }
846
847 void InspectorDOMAgent::setNodeValue(ErrorString& errorString, int nodeId, const String& value)
848 {
849     Node* node = assertEditableNode(errorString, nodeId);
850     if (!node)
851         return;
852
853     if (!is<Text>(*node)) {
854         errorString = "Can only set value of text nodes"_s;
855         return;
856     }
857
858     m_domEditor->replaceWholeText(downcast<Text>(*node), value, errorString);
859 }
860
861 void InspectorDOMAgent::getSupportedEventNames(ErrorString&, RefPtr<JSON::ArrayOf<String>>& eventNames)
862 {
863     eventNames = JSON::ArrayOf<String>::create();
864
865 #define DOM_EVENT_NAMES_ADD(name) eventNames->addItem(#name);
866     DOM_EVENT_NAMES_FOR_EACH(DOM_EVENT_NAMES_ADD)
867 #undef DOM_EVENT_NAMES_ADD
868 }
869
870 void InspectorDOMAgent::getDataBindingsForNode(ErrorString& errorString, int /* nodeId */, RefPtr<JSON::ArrayOf<Inspector::Protocol::DOM::DataBinding>>& /* dataBindings */)
871 {
872     errorString = "Not supported"_s;
873 }
874
875 void InspectorDOMAgent::getAssociatedDataForNode(ErrorString& errorString, int /* nodeId */, Optional<String>& /* associatedData */)
876 {
877     errorString = "Not supported"_s;
878 }
879
880 void InspectorDOMAgent::getEventListenersForNode(ErrorString& errorString, int nodeId, RefPtr<JSON::ArrayOf<Inspector::Protocol::DOM::EventListener>>& listenersArray)
881 {
882     listenersArray = JSON::ArrayOf<Inspector::Protocol::DOM::EventListener>::create();
883
884     auto* node = assertNode(errorString, nodeId);
885     if (!node)
886         return;
887
888     Vector<RefPtr<EventTarget>> ancestors;
889     ancestors.append(node);
890     for (auto* ancestor = node->parentOrShadowHostNode(); ancestor; ancestor = ancestor->parentOrShadowHostNode())
891         ancestors.append(ancestor);
892     if (auto* window = node->document().domWindow())
893         ancestors.append(window);
894
895     struct EventListenerInfo {
896         RefPtr<EventTarget> eventTarget;
897         const AtomString eventType;
898         const EventListenerVector eventListeners;
899     };
900
901     Vector<EventListenerInfo> eventInformation;
902     for (size_t i = ancestors.size(); i; --i) {
903         auto& ancestor = ancestors[i - 1];
904         for (auto& eventType : ancestor->eventTypes()) {
905             EventListenerVector filteredListeners;
906             for (auto& listener : ancestor->eventListeners(eventType)) {
907                 if (listener->callback().type() == EventListener::JSEventListenerType)
908                     filteredListeners.append(listener);
909             }
910             if (!filteredListeners.isEmpty())
911                 eventInformation.append({ ancestor, eventType, WTFMove(filteredListeners) });
912         }
913     }
914
915     auto addListener = [&] (RegisteredEventListener& listener, const EventListenerInfo& info) {
916         int identifier = 0;
917         bool disabled = false;
918         bool hasBreakpoint = false;
919
920         for (auto& inspectorEventListener : m_eventListenerEntries.values()) {
921             if (inspectorEventListener.matches(*info.eventTarget, info.eventType, listener.callback(), listener.useCapture())) {
922                 identifier = inspectorEventListener.identifier;
923                 disabled = inspectorEventListener.disabled;
924                 hasBreakpoint = inspectorEventListener.hasBreakpoint;
925                 break;
926             }
927         }
928
929         if (!identifier) {
930             InspectorEventListener inspectorEventListener(m_lastEventListenerId++, *info.eventTarget, info.eventType, listener.callback(), listener.useCapture());
931
932             identifier = inspectorEventListener.identifier;
933             disabled = inspectorEventListener.disabled;
934             hasBreakpoint = inspectorEventListener.hasBreakpoint;
935
936             m_eventListenerEntries.add(identifier, inspectorEventListener);
937         }
938
939         listenersArray->addItem(buildObjectForEventListener(listener, identifier, *info.eventTarget, info.eventType, disabled, hasBreakpoint));
940     };
941
942     // Get Capturing Listeners (in this order)
943     size_t eventInformationLength = eventInformation.size();
944     for (auto& info : eventInformation) {
945         for (auto& listener : info.eventListeners) {
946             if (listener->useCapture())
947                 addListener(*listener, info);
948         }
949     }
950
951     // Get Bubbling Listeners (reverse order)
952     for (size_t i = eventInformationLength; i; --i) {
953         const EventListenerInfo& info = eventInformation[i - 1];
954         for (auto& listener : info.eventListeners) {
955             if (!listener->useCapture())
956                 addListener(*listener, info);
957         }
958     }
959
960     if (m_inspectedNode == node)
961         m_suppressEventListenerChangedEvent = false;
962 }
963
964 void InspectorDOMAgent::setEventListenerDisabled(ErrorString& errorString, int eventListenerId, bool disabled)
965 {
966     auto it = m_eventListenerEntries.find(eventListenerId);
967     if (it == m_eventListenerEntries.end()) {
968         errorString = "No event listener for given identifier."_s;
969         return;
970     }
971
972     it->value.disabled = disabled;
973 }
974
975 void InspectorDOMAgent::setBreakpointForEventListener(ErrorString& errorString, int eventListenerId)
976 {
977     auto it = m_eventListenerEntries.find(eventListenerId);
978     if (it == m_eventListenerEntries.end()) {
979         errorString = "No event listener for given identifier."_s;
980         return;
981     }
982
983     it->value.hasBreakpoint = true;
984 }
985
986 void InspectorDOMAgent::removeBreakpointForEventListener(ErrorString& errorString, int eventListenerId)
987 {
988     auto it = m_eventListenerEntries.find(eventListenerId);
989     if (it == m_eventListenerEntries.end()) {
990         errorString = "No event listener for given identifier."_s;
991         return;
992     }
993
994     it->value.hasBreakpoint = false;
995 }
996
997 void InspectorDOMAgent::getAccessibilityPropertiesForNode(ErrorString& errorString, int nodeId, RefPtr<Inspector::Protocol::DOM::AccessibilityProperties>& axProperties)
998 {
999     Node* node = assertNode(errorString, nodeId);
1000     if (!node)
1001         return;
1002
1003     axProperties = buildObjectForAccessibilityProperties(node);
1004 }
1005
1006 void InspectorDOMAgent::performSearch(ErrorString& errorString, const String& query, const JSON::Array* nodeIds, const bool* caseSensitive, String* searchId, int* resultCount)
1007 {
1008     // FIXME: Search works with node granularity - number of matches within node is not calculated.
1009     InspectorNodeFinder finder(query, caseSensitive && *caseSensitive);
1010
1011     if (nodeIds) {
1012         for (auto& nodeValue : *nodeIds) {
1013             if (!nodeValue) {
1014                 errorString = "Invalid nodeIds item."_s;
1015                 return;
1016             }
1017             int nodeId = 0;
1018             if (!nodeValue->asInteger(nodeId)) {
1019                 errorString = "Invalid nodeIds item type. Expecting integer types."_s;
1020                 return;
1021             }
1022             Node* node = assertNode(errorString, nodeId);
1023             if (!node) {
1024                 // assertNode should have filled the errorString for us.
1025                 ASSERT(errorString.length());
1026                 return;
1027             }
1028             finder.performSearch(node);
1029         }
1030     } else {
1031         // There's no need to iterate the frames tree because
1032         // the search helper will go inside the frame owner elements.
1033         finder.performSearch(m_document.get());
1034     }
1035
1036     *searchId = IdentifiersFactory::createIdentifier();
1037
1038     auto& resultsVector = m_searchResults.add(*searchId, Vector<RefPtr<Node>>()).iterator->value;
1039     for (auto& result : finder.results())
1040         resultsVector.append(result);
1041
1042     *resultCount = resultsVector.size();
1043 }
1044
1045 void InspectorDOMAgent::getSearchResults(ErrorString& errorString, const String& searchId, int fromIndex, int toIndex, RefPtr<JSON::ArrayOf<int>>& nodeIds)
1046 {
1047     SearchResults::iterator it = m_searchResults.find(searchId);
1048     if (it == m_searchResults.end()) {
1049         errorString = "No search session with given id found"_s;
1050         return;
1051     }
1052
1053     int size = it->value.size();
1054     if (fromIndex < 0 || toIndex > size || fromIndex >= toIndex) {
1055         errorString = "Invalid search result range"_s;
1056         return;
1057     }
1058
1059     nodeIds = JSON::ArrayOf<int>::create();
1060     for (int i = fromIndex; i < toIndex; ++i)
1061         nodeIds->addItem(pushNodePathToFrontend((it->value)[i].get()));
1062 }
1063
1064 void InspectorDOMAgent::discardSearchResults(ErrorString&, const String& searchId)
1065 {
1066     m_searchResults.remove(searchId);
1067 }
1068
1069 bool InspectorDOMAgent::handleMousePress()
1070 {
1071     if (!m_searchingForNode)
1072         return false;
1073
1074     if (Node* node = m_overlay->highlightedNode()) {
1075         inspect(node);
1076         return true;
1077     }
1078     return false;
1079 }
1080
1081 bool InspectorDOMAgent::handleTouchEvent(Node& node)
1082 {
1083     if (!m_searchingForNode)
1084         return false;
1085     if (m_inspectModeHighlightConfig) {
1086         m_overlay->highlightNode(&node, *m_inspectModeHighlightConfig);
1087         inspect(&node);
1088         return true;
1089     }
1090     return false;
1091 }
1092
1093 void InspectorDOMAgent::inspect(Node* inspectedNode)
1094 {
1095     ErrorString unused;
1096     RefPtr<Node> node = inspectedNode;
1097     setSearchingForNode(unused, false, nullptr, false);
1098
1099     if (node->nodeType() != Node::ELEMENT_NODE && node->nodeType() != Node::DOCUMENT_NODE)
1100         node = node->parentNode();
1101     m_nodeToFocus = node;
1102
1103     if (!m_nodeToFocus)
1104         return;
1105
1106     focusNode();
1107 }
1108
1109 void InspectorDOMAgent::focusNode()
1110 {
1111     if (!m_documentRequested)
1112         return;
1113
1114     ASSERT(m_nodeToFocus);
1115
1116     RefPtr<Node> node = m_nodeToFocus.get();
1117     m_nodeToFocus = nullptr;
1118
1119     Frame* frame = node->document().frame();
1120     if (!frame)
1121         return;
1122
1123     JSC::ExecState* scriptState = mainWorldExecState(frame);
1124     InjectedScript injectedScript = m_injectedScriptManager.injectedScriptFor(scriptState);
1125     if (injectedScript.hasNoValue())
1126         return;
1127
1128     injectedScript.inspectObject(nodeAsScriptValue(*scriptState, node.get()));
1129 }
1130
1131 void InspectorDOMAgent::mouseDidMoveOverElement(const HitTestResult& result, unsigned)
1132 {
1133     m_mousedOverNode = result.innerNode();
1134
1135     if (!m_searchingForNode)
1136         return;
1137
1138     highlightMousedOverNode();
1139 }
1140
1141 void InspectorDOMAgent::highlightMousedOverNode()
1142 {
1143     Node* node = m_mousedOverNode.get();
1144     while (node && node->nodeType() == Node::TEXT_NODE)
1145         node = node->parentNode();
1146     if (node && m_inspectModeHighlightConfig)
1147         m_overlay->highlightNode(node, *m_inspectModeHighlightConfig);
1148 }
1149
1150 void InspectorDOMAgent::setSearchingForNode(ErrorString& errorString, bool enabled, const JSON::Object* highlightInspectorObject, bool showRulers)
1151 {
1152     if (m_searchingForNode == enabled)
1153         return;
1154
1155     m_searchingForNode = enabled;
1156
1157     m_overlay->setShowRulersDuringElementSelection(m_searchingForNode && showRulers);
1158
1159     if (m_searchingForNode) {
1160         m_inspectModeHighlightConfig = highlightConfigFromInspectorObject(errorString, highlightInspectorObject);
1161         if (!m_inspectModeHighlightConfig)
1162             return;
1163         highlightMousedOverNode();
1164     } else
1165         hideHighlight(errorString);
1166
1167     m_overlay->didSetSearchingForNode(m_searchingForNode);
1168
1169     if (InspectorClient* client = m_inspectedPage.inspectorController().inspectorClient())
1170         client->elementSelectionChanged(m_searchingForNode);
1171 }
1172
1173 std::unique_ptr<HighlightConfig> InspectorDOMAgent::highlightConfigFromInspectorObject(ErrorString& errorString, const JSON::Object* highlightInspectorObject)
1174 {
1175     if (!highlightInspectorObject) {
1176         errorString = "Internal error: highlight configuration parameter is missing"_s;
1177         return nullptr;
1178     }
1179
1180     auto highlightConfig = makeUnique<HighlightConfig>();
1181     bool showInfo = false; // Default: false (do not show a tooltip).
1182     highlightInspectorObject->getBoolean("showInfo", showInfo);
1183     highlightConfig->showInfo = showInfo;
1184     highlightConfig->content = parseConfigColor("contentColor", highlightInspectorObject);
1185     highlightConfig->contentOutline = parseConfigColor("contentOutlineColor", highlightInspectorObject);
1186     highlightConfig->padding = parseConfigColor("paddingColor", highlightInspectorObject);
1187     highlightConfig->border = parseConfigColor("borderColor", highlightInspectorObject);
1188     highlightConfig->margin = parseConfigColor("marginColor", highlightInspectorObject);
1189     return highlightConfig;
1190 }
1191
1192 void InspectorDOMAgent::setInspectModeEnabled(ErrorString& errorString, bool enabled, const JSON::Object* highlightConfig, const bool* showRulers)
1193 {
1194     setSearchingForNode(errorString, enabled, highlightConfig ? highlightConfig : nullptr, showRulers && *showRulers);
1195 }
1196
1197 void InspectorDOMAgent::highlightRect(ErrorString&, int x, int y, int width, int height, const JSON::Object* color, const JSON::Object* outlineColor, const bool* usePageCoordinates)
1198 {
1199     auto quad = makeUnique<FloatQuad>(FloatRect(x, y, width, height));
1200     innerHighlightQuad(WTFMove(quad), color, outlineColor, usePageCoordinates);
1201 }
1202
1203 void InspectorDOMAgent::highlightQuad(ErrorString& errorString, const JSON::Array& quadArray, const JSON::Object* color, const JSON::Object* outlineColor, const bool* usePageCoordinates)
1204 {
1205     auto quad = makeUnique<FloatQuad>();
1206     if (!parseQuad(quadArray, quad.get())) {
1207         errorString = "Invalid Quad format"_s;
1208         return;
1209     }
1210     innerHighlightQuad(WTFMove(quad), color, outlineColor, usePageCoordinates);
1211 }
1212
1213 void InspectorDOMAgent::innerHighlightQuad(std::unique_ptr<FloatQuad> quad, const JSON::Object* color, const JSON::Object* outlineColor, const bool* usePageCoordinates)
1214 {
1215     auto highlightConfig = makeUnique<HighlightConfig>();
1216     highlightConfig->content = parseColor(color);
1217     highlightConfig->contentOutline = parseColor(outlineColor);
1218     highlightConfig->usePageCoordinates = usePageCoordinates ? *usePageCoordinates : false;
1219     m_overlay->highlightQuad(WTFMove(quad), *highlightConfig);
1220 }
1221
1222 void InspectorDOMAgent::highlightSelector(ErrorString& errorString, const JSON::Object& highlightInspectorObject, const String& selectorString, const String* frameId)
1223 {
1224     RefPtr<Document> document;
1225
1226     if (frameId) {
1227         Frame* frame = m_instrumentingAgents.inspectorPageAgent()->frameForId(*frameId);
1228         if (!frame) {
1229             errorString = "No frame for given id found"_s;
1230             return;
1231         }
1232
1233         document = frame->document();
1234     } else
1235         document = m_document;
1236
1237     if (!document) {
1238         errorString = "Document could not be found"_s;
1239         return;
1240     }
1241
1242     auto queryResult = document->querySelectorAll(selectorString);
1243     // FIXME: <https://webkit.org/b/146161> Web Inspector: DOM.highlightSelector should work for "a:visited"
1244     if (queryResult.hasException()) {
1245         errorString = "DOM Error while querying"_s;
1246         return;
1247     }
1248
1249     auto highlightConfig = highlightConfigFromInspectorObject(errorString, &highlightInspectorObject);
1250     if (!highlightConfig)
1251         return;
1252
1253     m_overlay->highlightNodeList(queryResult.releaseReturnValue(), *highlightConfig);
1254 }
1255
1256 void InspectorDOMAgent::highlightNode(ErrorString& errorString, const JSON::Object& highlightInspectorObject, const int* nodeId, const String* objectId)
1257 {
1258     Node* node = nullptr;
1259     if (nodeId)
1260         node = assertNode(errorString, *nodeId);
1261     else if (objectId) {
1262         node = nodeForObjectId(*objectId);
1263         if (!node)
1264             errorString = "Node for given objectId not found"_s;
1265     } else
1266         errorString = "Either nodeId or objectId must be specified"_s;
1267
1268     if (!node)
1269         return;
1270
1271     std::unique_ptr<HighlightConfig> highlightConfig = highlightConfigFromInspectorObject(errorString, &highlightInspectorObject);
1272     if (!highlightConfig)
1273         return;
1274
1275     m_overlay->highlightNode(node, *highlightConfig);
1276 }
1277
1278 void InspectorDOMAgent::highlightNodeList(ErrorString& errorString, const JSON::Array& nodeIds, const JSON::Object& highlightInspectorObject)
1279 {
1280     Vector<Ref<Node>> nodes;
1281     for (auto& nodeValue : nodeIds) {
1282         if (!nodeValue) {
1283             errorString = "Invalid nodeIds item."_s;
1284             return;
1285         }
1286
1287         int nodeId = 0;
1288         if (!nodeValue->asInteger(nodeId)) {
1289             errorString = "Invalid nodeIds item type. Expecting integer types."_s;
1290             return;
1291         }
1292
1293         // In the case that a node is removed in the time between when highlightNodeList is invoked
1294         // by the frontend and it is executed by the backend, we should still attempt to highlight
1295         // as many nodes as possible. As such, we should ignore any errors generated when attempting
1296         // to get a Node from a given nodeId. 
1297         ErrorString ignored;
1298         Node* node = assertNode(ignored, nodeId);
1299         if (!node)
1300             continue;
1301
1302         nodes.append(*node);
1303     }
1304
1305     std::unique_ptr<HighlightConfig> highlightConfig = highlightConfigFromInspectorObject(errorString, &highlightInspectorObject);
1306     if (!highlightConfig)
1307         return;
1308
1309     m_overlay->highlightNodeList(StaticNodeList::create(WTFMove(nodes)), *highlightConfig);
1310 }
1311
1312 void InspectorDOMAgent::highlightFrame(ErrorString& errorString, const String& frameId, const JSON::Object* color, const JSON::Object* outlineColor)
1313 {
1314     Frame* frame = m_instrumentingAgents.inspectorPageAgent()->assertFrame(errorString, frameId);
1315     if (!frame)
1316         return;
1317
1318     if (frame->ownerElement()) {
1319         auto highlightConfig = makeUnique<HighlightConfig>();
1320         highlightConfig->showInfo = true; // Always show tooltips for frames.
1321         highlightConfig->content = parseColor(color);
1322         highlightConfig->contentOutline = parseColor(outlineColor);
1323         m_overlay->highlightNode(frame->ownerElement(), *highlightConfig);
1324     }
1325 }
1326
1327 void InspectorDOMAgent::hideHighlight(ErrorString&)
1328 {
1329     m_overlay->hideHighlight();
1330 }
1331
1332 void InspectorDOMAgent::moveTo(ErrorString& errorString, int nodeId, int targetElementId, const int* anchorNodeId, int* newNodeId)
1333 {
1334     Node* node = assertEditableNode(errorString, nodeId);
1335     if (!node)
1336         return;
1337
1338     Element* targetElement = assertEditableElement(errorString, targetElementId);
1339     if (!targetElement)
1340         return;
1341
1342     Node* anchorNode = 0;
1343     if (anchorNodeId && *anchorNodeId) {
1344         anchorNode = assertEditableNode(errorString, *anchorNodeId);
1345         if (!anchorNode)
1346             return;
1347         if (anchorNode->parentNode() != targetElement) {
1348             errorString = "Anchor node must be child of the target element"_s;
1349             return;
1350         }
1351     }
1352
1353     if (!m_domEditor->insertBefore(*targetElement, *node, anchorNode, errorString))
1354         return;
1355
1356     *newNodeId = pushNodePathToFrontend(node);
1357 }
1358
1359 void InspectorDOMAgent::undo(ErrorString& errorString)
1360 {
1361     auto result = m_history->undo();
1362     if (result.hasException())
1363         errorString = toErrorString(result.releaseException());
1364 }
1365
1366 void InspectorDOMAgent::redo(ErrorString& errorString)
1367 {
1368     auto result = m_history->redo();
1369     if (result.hasException())
1370         errorString = toErrorString(result.releaseException());
1371 }
1372
1373 void InspectorDOMAgent::markUndoableState(ErrorString&)
1374 {
1375     m_history->markUndoableState();
1376 }
1377
1378 void InspectorDOMAgent::focus(ErrorString& errorString, int nodeId)
1379 {
1380     Element* element = assertElement(errorString, nodeId);
1381     if (!element)
1382         return;
1383     if (!element->isFocusable()) {
1384         errorString = "Element is not focusable"_s;
1385         return;
1386     }
1387     element->focus();
1388 }
1389
1390 void InspectorDOMAgent::setInspectedNode(ErrorString& errorString, int nodeId)
1391 {
1392     Node* node = nodeForId(nodeId);
1393     if (!node || node->isInUserAgentShadowTree()) {
1394         errorString = "No node with given id found"_s;
1395         return;
1396     }
1397
1398     m_inspectedNode = node;
1399
1400     if (auto& commandLineAPIHost = static_cast<WebInjectedScriptManager&>(m_injectedScriptManager).commandLineAPIHost())
1401         commandLineAPIHost->addInspectedObject(makeUnique<InspectableNode>(node));
1402
1403     m_suppressEventListenerChangedEvent = false;
1404 }
1405
1406 void InspectorDOMAgent::resolveNode(ErrorString& errorString, int nodeId, const String* objectGroup, RefPtr<Inspector::Protocol::Runtime::RemoteObject>& result)
1407 {
1408     String objectGroupName = objectGroup ? *objectGroup : emptyString();
1409     Node* node = nodeForId(nodeId);
1410     if (!node) {
1411         errorString = "No node with given id found"_s;
1412         return;
1413     }
1414     RefPtr<Inspector::Protocol::Runtime::RemoteObject> object = resolveNode(node, objectGroupName);
1415     if (!object) {
1416         errorString = "Node with given id does not belong to the document"_s;
1417         return;
1418     }
1419     result = object;
1420 }
1421
1422 void InspectorDOMAgent::getAttributes(ErrorString& errorString, int nodeId, RefPtr<JSON::ArrayOf<String>>& result)
1423 {
1424     Element* element = assertElement(errorString, nodeId);
1425     if (!element)
1426         return;
1427
1428     result = buildArrayForElementAttributes(element);
1429 }
1430
1431 void InspectorDOMAgent::requestNode(ErrorString&, const String& objectId, int* nodeId)
1432 {
1433     Node* node = nodeForObjectId(objectId);
1434     if (node)
1435         *nodeId = pushNodePathToFrontend(node);
1436     else
1437         *nodeId = 0;
1438 }
1439
1440 String InspectorDOMAgent::documentURLString(Document* document)
1441 {
1442     if (!document || document->url().isNull())
1443         return emptyString();
1444     return document->url().string();
1445 }
1446
1447 static String documentBaseURLString(Document* document)
1448 {
1449     return document->completeURL(emptyString()).string();
1450 }
1451
1452 static bool pseudoElementType(PseudoId pseudoId, Inspector::Protocol::DOM::PseudoType* type)
1453 {
1454     switch (pseudoId) {
1455     case PseudoId::Before:
1456         *type = Inspector::Protocol::DOM::PseudoType::Before;
1457         return true;
1458     case PseudoId::After:
1459         *type = Inspector::Protocol::DOM::PseudoType::After;
1460         return true;
1461     default:
1462         return false;
1463     }
1464 }
1465
1466 static Inspector::Protocol::DOM::ShadowRootType shadowRootType(ShadowRootMode mode)
1467 {
1468     switch (mode) {
1469     case ShadowRootMode::UserAgent:
1470         return Inspector::Protocol::DOM::ShadowRootType::UserAgent;
1471     case ShadowRootMode::Closed:
1472         return Inspector::Protocol::DOM::ShadowRootType::Closed;
1473     case ShadowRootMode::Open:
1474         return Inspector::Protocol::DOM::ShadowRootType::Open;
1475     }
1476
1477     ASSERT_NOT_REACHED();
1478     return Inspector::Protocol::DOM::ShadowRootType::UserAgent;
1479 }
1480
1481 static Inspector::Protocol::DOM::CustomElementState customElementState(const Element& element)
1482 {
1483     if (element.isDefinedCustomElement())
1484         return Inspector::Protocol::DOM::CustomElementState::Custom;
1485     if (element.isFailedCustomElement())
1486         return Inspector::Protocol::DOM::CustomElementState::Failed;
1487     if (element.isUndefinedCustomElement() || element.isCustomElementUpgradeCandidate())
1488         return Inspector::Protocol::DOM::CustomElementState::Waiting;
1489     return Inspector::Protocol::DOM::CustomElementState::Builtin;
1490 }
1491
1492 static String computeContentSecurityPolicySHA256Hash(const Element& element)
1493 {
1494     // FIXME: Compute the digest with respect to the raw bytes received from the page.
1495     // See <https://bugs.webkit.org/show_bug.cgi?id=155184>.
1496     TextEncoding documentEncoding = element.document().textEncoding();
1497     const TextEncoding& encodingToUse = documentEncoding.isValid() ? documentEncoding : UTF8Encoding();
1498     auto content = encodingToUse.encode(TextNodeTraversal::contentsAsString(element), UnencodableHandling::Entities);
1499     auto cryptoDigest = PAL::CryptoDigest::create(PAL::CryptoDigest::Algorithm::SHA_256);
1500     cryptoDigest->addBytes(content.data(), content.size());
1501     auto digest = cryptoDigest->computeHash();
1502     return makeString("sha256-", base64Encode(digest.data(), digest.size()));
1503 }
1504
1505 Ref<Inspector::Protocol::DOM::Node> InspectorDOMAgent::buildObjectForNode(Node* node, int depth, NodeToIdMap* nodesMap)
1506 {
1507     int id = bind(node, nodesMap);
1508     String nodeName;
1509     String localName;
1510     String nodeValue;
1511
1512     switch (node->nodeType()) {
1513     case Node::PROCESSING_INSTRUCTION_NODE:
1514         nodeName = node->nodeName();
1515         localName = node->localName();
1516         FALLTHROUGH;
1517     case Node::TEXT_NODE:
1518     case Node::COMMENT_NODE:
1519     case Node::CDATA_SECTION_NODE:
1520         nodeValue = node->nodeValue();
1521         if (nodeValue.length() > maxTextSize) {
1522             nodeValue = nodeValue.left(maxTextSize);
1523             nodeValue.append(ellipsisUChar);
1524         }
1525         break;
1526     case Node::ATTRIBUTE_NODE:
1527         localName = node->localName();
1528         break;
1529     case Node::DOCUMENT_FRAGMENT_NODE:
1530     case Node::DOCUMENT_NODE:
1531     case Node::ELEMENT_NODE:
1532     default:
1533         nodeName = node->nodeName();
1534         localName = node->localName();
1535         break;
1536     }
1537
1538     auto value = Inspector::Protocol::DOM::Node::create()
1539         .setNodeId(id)
1540         .setNodeType(static_cast<int>(node->nodeType()))
1541         .setNodeName(nodeName)
1542         .setLocalName(localName)
1543         .setNodeValue(nodeValue)
1544         .release();
1545
1546     if (node->isContainerNode()) {
1547         int nodeCount = innerChildNodeCount(node);
1548         value->setChildNodeCount(nodeCount);
1549         Ref<JSON::ArrayOf<Inspector::Protocol::DOM::Node>> children = buildArrayForContainerChildren(node, depth, nodesMap);
1550         if (children->length() > 0)
1551             value->setChildren(WTFMove(children));
1552     }
1553
1554     if (auto* frameView = node->document().view())
1555         value->setFrameId(m_instrumentingAgents.inspectorPageAgent()->frameId(&frameView->frame()));
1556
1557     if (is<Element>(*node)) {
1558         Element& element = downcast<Element>(*node);
1559         value->setAttributes(buildArrayForElementAttributes(&element));
1560         if (is<HTMLFrameOwnerElement>(element)) {
1561             if (auto* document = downcast<HTMLFrameOwnerElement>(element).contentDocument())
1562                 value->setContentDocument(buildObjectForNode(document, 0, nodesMap));
1563         }
1564
1565         if (ShadowRoot* root = element.shadowRoot()) {
1566             auto shadowRoots = JSON::ArrayOf<Inspector::Protocol::DOM::Node>::create();
1567             shadowRoots->addItem(buildObjectForNode(root, 0, nodesMap));
1568             value->setShadowRoots(WTFMove(shadowRoots));
1569         }
1570
1571         if (is<HTMLTemplateElement>(element))
1572             value->setTemplateContent(buildObjectForNode(&downcast<HTMLTemplateElement>(element).content(), 0, nodesMap));
1573
1574         if (is<HTMLStyleElement>(element) || (is<HTMLScriptElement>(element) && !element.hasAttributeWithoutSynchronization(HTMLNames::srcAttr)))
1575             value->setContentSecurityPolicyHash(computeContentSecurityPolicySHA256Hash(element));
1576
1577         auto state = customElementState(element);
1578         if (state != Inspector::Protocol::DOM::CustomElementState::Builtin)
1579             value->setCustomElementState(state);
1580
1581         if (element.pseudoId() != PseudoId::None) {
1582             Inspector::Protocol::DOM::PseudoType pseudoType;
1583             if (pseudoElementType(element.pseudoId(), &pseudoType))
1584                 value->setPseudoType(pseudoType);
1585         } else {
1586             if (auto pseudoElements = buildArrayForPseudoElements(element, nodesMap))
1587                 value->setPseudoElements(WTFMove(pseudoElements));
1588         }
1589     } else if (is<Document>(*node)) {
1590         Document& document = downcast<Document>(*node);
1591         value->setFrameId(m_instrumentingAgents.inspectorPageAgent()->frameId(document.frame()));
1592         value->setDocumentURL(documentURLString(&document));
1593         value->setBaseURL(documentBaseURLString(&document));
1594         value->setXmlVersion(document.xmlVersion());
1595     } else if (is<DocumentType>(*node)) {
1596         DocumentType& docType = downcast<DocumentType>(*node);
1597         value->setPublicId(docType.publicId());
1598         value->setSystemId(docType.systemId());
1599     } else if (is<Attr>(*node)) {
1600         Attr& attribute = downcast<Attr>(*node);
1601         value->setName(attribute.name());
1602         value->setValue(attribute.value());
1603     } else if (is<ShadowRoot>(*node)) {
1604         ShadowRoot& shadowRoot = downcast<ShadowRoot>(*node);
1605         value->setShadowRootType(shadowRootType(shadowRoot.mode()));
1606     }
1607
1608     return value;
1609 }
1610
1611 Ref<JSON::ArrayOf<String>> InspectorDOMAgent::buildArrayForElementAttributes(Element* element)
1612 {
1613     auto attributesValue = JSON::ArrayOf<String>::create();
1614     // Go through all attributes and serialize them.
1615     if (!element->hasAttributes())
1616         return attributesValue;
1617     for (const Attribute& attribute : element->attributesIterator()) {
1618         // Add attribute pair
1619         attributesValue->addItem(attribute.name().toString());
1620         attributesValue->addItem(attribute.value());
1621     }
1622     return attributesValue;
1623 }
1624
1625 Ref<JSON::ArrayOf<Inspector::Protocol::DOM::Node>> InspectorDOMAgent::buildArrayForContainerChildren(Node* container, int depth, NodeToIdMap* nodesMap)
1626 {
1627     auto children = JSON::ArrayOf<Inspector::Protocol::DOM::Node>::create();
1628     if (depth == 0) {
1629         // Special-case the only text child - pretend that container's children have been requested.
1630         Node* firstChild = container->firstChild();
1631         if (firstChild && firstChild->nodeType() == Node::TEXT_NODE && !firstChild->nextSibling()) {
1632             children->addItem(buildObjectForNode(firstChild, 0, nodesMap));
1633             m_childrenRequested.add(bind(container, nodesMap));
1634         }
1635         return children;
1636     }
1637
1638     Node* child = innerFirstChild(container);
1639     depth--;
1640     m_childrenRequested.add(bind(container, nodesMap));
1641
1642     while (child) {
1643         children->addItem(buildObjectForNode(child, depth, nodesMap));
1644         child = innerNextSibling(child);
1645     }
1646     return children;
1647 }
1648
1649 RefPtr<JSON::ArrayOf<Inspector::Protocol::DOM::Node>> InspectorDOMAgent::buildArrayForPseudoElements(const Element& element, NodeToIdMap* nodesMap)
1650 {
1651     PseudoElement* beforeElement = element.beforePseudoElement();
1652     PseudoElement* afterElement = element.afterPseudoElement();
1653     if (!beforeElement && !afterElement)
1654         return nullptr;
1655
1656     auto pseudoElements = JSON::ArrayOf<Inspector::Protocol::DOM::Node>::create();
1657     if (beforeElement)
1658         pseudoElements->addItem(buildObjectForNode(beforeElement, 0, nodesMap));
1659     if (afterElement)
1660         pseudoElements->addItem(buildObjectForNode(afterElement, 0, nodesMap));
1661     return pseudoElements;
1662 }
1663
1664 Ref<Inspector::Protocol::DOM::EventListener> InspectorDOMAgent::buildObjectForEventListener(const RegisteredEventListener& registeredEventListener, int identifier, EventTarget& eventTarget, const AtomString& eventType, bool disabled, bool hasBreakpoint)
1665 {
1666     Ref<EventListener> eventListener = registeredEventListener.callback();
1667
1668     String handlerName;
1669     int lineNumber = 0;
1670     int columnNumber = 0;
1671     String scriptID;
1672     if (is<JSEventListener>(eventListener.get())) {
1673         auto& scriptListener = downcast<JSEventListener>(eventListener.get());
1674
1675         Document* document = nullptr;
1676         if (auto* scriptExecutionContext = eventTarget.scriptExecutionContext()) {
1677             if (is<Document>(scriptExecutionContext))
1678                 document = downcast<Document>(scriptExecutionContext);
1679         } else if (is<Node>(eventTarget))
1680             document = &downcast<Node>(eventTarget).document();
1681
1682         JSC::JSObject* handlerObject = nullptr;
1683         JSC::ExecState* exec = nullptr;
1684
1685         JSC::JSLockHolder lock(scriptListener.isolatedWorld().vm());
1686
1687         if (document) {
1688             handlerObject = scriptListener.jsFunction(*document);
1689             exec = execStateFromNode(scriptListener.isolatedWorld(), document);
1690         }
1691
1692         if (handlerObject && exec) {
1693             JSC::JSFunction* handlerFunction = JSC::jsDynamicCast<JSC::JSFunction*>(exec->vm(), handlerObject);
1694
1695             if (!handlerFunction) {
1696                 auto scope = DECLARE_CATCH_SCOPE(exec->vm());
1697
1698                 // If the handler is not actually a function, see if it implements the EventListener interface and use that.
1699                 auto handleEventValue = handlerObject->get(exec, JSC::Identifier::fromString(exec, "handleEvent"));
1700
1701                 if (UNLIKELY(scope.exception()))
1702                     scope.clearException();
1703
1704                 if (handleEventValue)
1705                     handlerFunction = JSC::jsDynamicCast<JSC::JSFunction*>(exec->vm(), handleEventValue);
1706             }
1707
1708             if (handlerFunction && !handlerFunction->isHostOrBuiltinFunction()) {
1709                 // If the listener implements the EventListener interface, use the class name instead of
1710                 // "handleEvent", unless it is a plain object.
1711                 if (handlerFunction != handlerObject)
1712                     handlerName = JSC::JSObject::calculatedClassName(handlerObject);
1713                 if (handlerName.isEmpty() || handlerName == "Object"_s)
1714                     handlerName = handlerFunction->calculatedDisplayName(exec->vm());
1715
1716                 if (auto executable = handlerFunction->jsExecutable()) {
1717                     lineNumber = executable->firstLine() - 1;
1718                     columnNumber = executable->startColumn() - 1;
1719                     scriptID = executable->sourceID() == JSC::SourceProvider::nullID ? emptyString() : String::number(executable->sourceID());
1720                 }
1721             }
1722         }
1723     }
1724
1725     auto value = Inspector::Protocol::DOM::EventListener::create()
1726         .setEventListenerId(identifier)
1727         .setType(eventType)
1728         .setUseCapture(registeredEventListener.useCapture())
1729         .setIsAttribute(eventListener->isAttribute())
1730         .release();
1731     if (is<Node>(eventTarget))
1732         value->setNodeId(pushNodePathToFrontend(&downcast<Node>(eventTarget)));
1733     else if (is<DOMWindow>(eventTarget))
1734         value->setOnWindow(true);
1735     if (!scriptID.isNull()) {
1736         auto location = Inspector::Protocol::Debugger::Location::create()
1737             .setScriptId(scriptID)
1738             .setLineNumber(lineNumber)
1739             .release();
1740         location->setColumnNumber(columnNumber);
1741         value->setLocation(WTFMove(location));
1742     }
1743     if (!handlerName.isEmpty())
1744         value->setHandlerName(handlerName);
1745     if (registeredEventListener.isPassive())
1746         value->setPassive(true);
1747     if (registeredEventListener.isOnce())
1748         value->setOnce(true);
1749     if (disabled)
1750         value->setDisabled(disabled);
1751     if (hasBreakpoint)
1752         value->setHasBreakpoint(hasBreakpoint);
1753     return value;
1754 }
1755
1756 void InspectorDOMAgent::processAccessibilityChildren(AccessibilityObject& axObject, JSON::ArrayOf<int>& childNodeIds)
1757 {
1758     const auto& children = axObject.children();
1759     if (!children.size())
1760         return;
1761
1762     for (const auto& childObject : children) {
1763         if (Node* childNode = childObject->node())
1764             childNodeIds.addItem(pushNodePathToFrontend(childNode));
1765         else
1766             processAccessibilityChildren(*childObject, childNodeIds);
1767     }
1768 }
1769     
1770 RefPtr<Inspector::Protocol::DOM::AccessibilityProperties> InspectorDOMAgent::buildObjectForAccessibilityProperties(Node* node)
1771 {
1772     ASSERT(node);
1773     if (!node)
1774         return nullptr;
1775
1776     if (!WebCore::AXObjectCache::accessibilityEnabled())
1777         WebCore::AXObjectCache::enableAccessibility();
1778
1779     Node* activeDescendantNode = nullptr;
1780     bool busy = false;
1781     auto checked = Inspector::Protocol::DOM::AccessibilityProperties::Checked::False;
1782     RefPtr<JSON::ArrayOf<int>> childNodeIds;
1783     RefPtr<JSON::ArrayOf<int>> controlledNodeIds;
1784     auto currentState = Inspector::Protocol::DOM::AccessibilityProperties::Current::False;
1785     bool exists = false;
1786     bool expanded = false;
1787     bool disabled = false;
1788     RefPtr<JSON::ArrayOf<int>> flowedNodeIds;
1789     bool focused = false;
1790     bool ignored = true;
1791     bool ignoredByDefault = false;
1792     auto invalid = Inspector::Protocol::DOM::AccessibilityProperties::Invalid::False;
1793     bool hidden = false;
1794     String label;
1795     bool liveRegionAtomic = false;
1796     RefPtr<JSON::ArrayOf<String>> liveRegionRelevant;
1797     auto liveRegionStatus = Inspector::Protocol::DOM::AccessibilityProperties::LiveRegionStatus::Off;
1798     Node* mouseEventNode = nullptr;
1799     RefPtr<JSON::ArrayOf<int>> ownedNodeIds;
1800     Node* parentNode = nullptr;
1801     bool pressed = false;
1802     bool readonly = false;
1803     bool required = false;
1804     String role;
1805     bool selected = false;
1806     RefPtr<JSON::ArrayOf<int>> selectedChildNodeIds;
1807     bool supportsChecked = false;
1808     bool supportsExpanded = false;
1809     bool supportsLiveRegion = false;
1810     bool supportsPressed = false;
1811     bool supportsRequired = false;
1812     bool supportsFocused = false;
1813     bool isPopupButton = false;
1814     int headingLevel = 0;
1815     unsigned hierarchicalLevel = 0;
1816     unsigned level = 0;
1817
1818     if (AXObjectCache* axObjectCache = node->document().axObjectCache()) {
1819         if (AccessibilityObject* axObject = axObjectCache->getOrCreate(node)) {
1820
1821             if (AccessibilityObject* activeDescendant = axObject->activeDescendant())
1822                 activeDescendantNode = activeDescendant->node();
1823
1824             // An AX object is "busy" if it or any ancestor has aria-busy="true" set.
1825             AccessibilityObject* current = axObject;
1826             while (!busy && current) {
1827                 busy = current->isBusy();
1828                 current = current->parentObject();
1829             }
1830
1831             supportsChecked = axObject->supportsChecked();
1832             if (supportsChecked) {
1833                 AccessibilityButtonState checkValue = axObject->checkboxOrRadioValue(); // Element using aria-checked.
1834                 if (checkValue == AccessibilityButtonState::On)
1835                     checked = Inspector::Protocol::DOM::AccessibilityProperties::Checked::True;
1836                 else if (checkValue == AccessibilityButtonState::Mixed)
1837                     checked = Inspector::Protocol::DOM::AccessibilityProperties::Checked::Mixed;
1838                 else if (axObject->isChecked()) // Native checkbox.
1839                     checked = Inspector::Protocol::DOM::AccessibilityProperties::Checked::True;
1840             }
1841             
1842             if (!axObject->children().isEmpty()) {
1843                 childNodeIds = JSON::ArrayOf<int>::create();
1844                 processAccessibilityChildren(*axObject, *childNodeIds);
1845             }
1846             
1847             Vector<Element*> controlledElements;
1848             axObject->elementsFromAttribute(controlledElements, aria_controlsAttr);
1849             if (controlledElements.size()) {
1850                 controlledNodeIds = JSON::ArrayOf<int>::create();
1851                 for (Element* controlledElement : controlledElements)
1852                     controlledNodeIds->addItem(pushNodePathToFrontend(controlledElement));
1853             }
1854             
1855             switch (axObject->currentState()) {
1856             case AccessibilityCurrentState::False:
1857                 currentState = Inspector::Protocol::DOM::AccessibilityProperties::Current::False;
1858                 break;
1859             case AccessibilityCurrentState::Page:
1860                 currentState = Inspector::Protocol::DOM::AccessibilityProperties::Current::Page;
1861                 break;
1862             case AccessibilityCurrentState::Step:
1863                 currentState = Inspector::Protocol::DOM::AccessibilityProperties::Current::Step;
1864                 break;
1865             case AccessibilityCurrentState::Location:
1866                 currentState = Inspector::Protocol::DOM::AccessibilityProperties::Current::Location;
1867                 break;
1868             case AccessibilityCurrentState::Date:
1869                 currentState = Inspector::Protocol::DOM::AccessibilityProperties::Current::Date;
1870                 break;
1871             case AccessibilityCurrentState::Time:
1872                 currentState = Inspector::Protocol::DOM::AccessibilityProperties::Current::Time;
1873                 break;
1874             case AccessibilityCurrentState::True:
1875                 currentState = Inspector::Protocol::DOM::AccessibilityProperties::Current::True;
1876                 break;
1877             }
1878
1879             disabled = !axObject->isEnabled();
1880             exists = true;
1881             
1882             supportsExpanded = axObject->supportsExpanded();
1883             if (supportsExpanded)
1884                 expanded = axObject->isExpanded();
1885
1886             Vector<Element*> flowedElements;
1887             axObject->elementsFromAttribute(flowedElements, aria_flowtoAttr);
1888             if (flowedElements.size()) {
1889                 flowedNodeIds = JSON::ArrayOf<int>::create();
1890                 for (Element* flowedElement : flowedElements)
1891                     flowedNodeIds->addItem(pushNodePathToFrontend(flowedElement));
1892             }
1893             
1894             if (is<Element>(*node)) {
1895                 supportsFocused = axObject->canSetFocusAttribute();
1896                 if (supportsFocused)
1897                     focused = axObject->isFocused();
1898             }
1899
1900             ignored = axObject->accessibilityIsIgnored();
1901             ignoredByDefault = axObject->accessibilityIsIgnoredByDefault();
1902             
1903             String invalidValue = axObject->invalidStatus();
1904             if (invalidValue == "false")
1905                 invalid = Inspector::Protocol::DOM::AccessibilityProperties::Invalid::False;
1906             else if (invalidValue == "grammar")
1907                 invalid = Inspector::Protocol::DOM::AccessibilityProperties::Invalid::Grammar;
1908             else if (invalidValue == "spelling")
1909                 invalid = Inspector::Protocol::DOM::AccessibilityProperties::Invalid::Spelling;
1910             else // Future versions of ARIA may allow additional truthy values. Ex. format, order, or size.
1911                 invalid = Inspector::Protocol::DOM::AccessibilityProperties::Invalid::True;
1912             
1913             if (axObject->isAXHidden() || axObject->isDOMHidden())
1914                 hidden = true;
1915             
1916             label = axObject->computedLabel();
1917
1918             if (axObject->supportsLiveRegion()) {
1919                 supportsLiveRegion = true;
1920                 liveRegionAtomic = axObject->liveRegionAtomic();
1921
1922                 String ariaRelevantAttrValue = axObject->liveRegionRelevant();
1923                 if (!ariaRelevantAttrValue.isEmpty()) {
1924                     // FIXME: Pass enum values rather than strings once unblocked. http://webkit.org/b/133711
1925                     String ariaRelevantAdditions = Inspector::Protocol::InspectorHelpers::getEnumConstantValue(Inspector::Protocol::DOM::LiveRegionRelevant::Additions);
1926                     String ariaRelevantRemovals = Inspector::Protocol::InspectorHelpers::getEnumConstantValue(Inspector::Protocol::DOM::LiveRegionRelevant::Removals);
1927                     String ariaRelevantText = Inspector::Protocol::InspectorHelpers::getEnumConstantValue(Inspector::Protocol::DOM::LiveRegionRelevant::Text);
1928                     liveRegionRelevant = JSON::ArrayOf<String>::create();
1929                     const SpaceSplitString& values = SpaceSplitString(ariaRelevantAttrValue, true);
1930                     // @aria-relevant="all" is exposed as ["additions","removals","text"], in order.
1931                     // This order is controlled in WebCore and expected in WebInspectorUI.
1932                     if (values.contains("all")) {
1933                         liveRegionRelevant->addItem(ariaRelevantAdditions);
1934                         liveRegionRelevant->addItem(ariaRelevantRemovals);
1935                         liveRegionRelevant->addItem(ariaRelevantText);
1936                     } else {
1937                         if (values.contains(ariaRelevantAdditions))
1938                             liveRegionRelevant->addItem(ariaRelevantAdditions);
1939                         if (values.contains(ariaRelevantRemovals))
1940                             liveRegionRelevant->addItem(ariaRelevantRemovals);
1941                         if (values.contains(ariaRelevantText))
1942                             liveRegionRelevant->addItem(ariaRelevantText);
1943                     }
1944                 }
1945
1946                 String ariaLive = axObject->liveRegionStatus();
1947                 if (ariaLive == "assertive")
1948                     liveRegionStatus = Inspector::Protocol::DOM::AccessibilityProperties::LiveRegionStatus::Assertive;
1949                 else if (ariaLive == "polite")
1950                     liveRegionStatus = Inspector::Protocol::DOM::AccessibilityProperties::LiveRegionStatus::Polite;
1951             }
1952
1953             if (is<AccessibilityNodeObject>(*axObject))
1954                 mouseEventNode = downcast<AccessibilityNodeObject>(*axObject).mouseButtonListener(MouseButtonListenerResultFilter::IncludeBodyElement);
1955
1956             if (axObject->supportsARIAOwns()) {
1957                 Vector<Element*> ownedElements;
1958                 axObject->elementsFromAttribute(ownedElements, aria_ownsAttr);
1959                 if (ownedElements.size()) {
1960                     ownedNodeIds = JSON::ArrayOf<int>::create();
1961                     for (Element* ownedElement : ownedElements)
1962                         ownedNodeIds->addItem(pushNodePathToFrontend(ownedElement));
1963                 }
1964             }
1965
1966             if (AccessibilityObject* parentObject = axObject->parentObjectUnignored())
1967                 parentNode = parentObject->node();
1968
1969             supportsPressed = axObject->pressedIsPresent();
1970             if (supportsPressed)
1971                 pressed = axObject->isPressed();
1972             
1973             if (axObject->isTextControl())
1974                 readonly = !axObject->canSetValueAttribute();
1975
1976             supportsRequired = axObject->supportsRequiredAttribute();
1977             if (supportsRequired)
1978                 required = axObject->isRequired();
1979             
1980             role = axObject->computedRoleString();
1981             selected = axObject->isSelected();
1982
1983             AccessibilityObject::AccessibilityChildrenVector selectedChildren;
1984             axObject->selectedChildren(selectedChildren);
1985             if (selectedChildren.size()) {
1986                 selectedChildNodeIds = JSON::ArrayOf<int>::create();
1987                 for (auto& selectedChildObject : selectedChildren) {
1988                     if (Node* selectedChildNode = selectedChildObject->node())
1989                         selectedChildNodeIds->addItem(pushNodePathToFrontend(selectedChildNode));
1990                 }
1991             }
1992             
1993             headingLevel = axObject->headingLevel();
1994             hierarchicalLevel = axObject->hierarchicalLevel();
1995             
1996             level = hierarchicalLevel ? hierarchicalLevel : headingLevel;
1997             isPopupButton = axObject->isPopUpButton() || axObject->hasPopup();
1998         }
1999     }
2000     
2001     Ref<Inspector::Protocol::DOM::AccessibilityProperties> value = Inspector::Protocol::DOM::AccessibilityProperties::create()
2002         .setExists(exists)
2003         .setLabel(label)
2004         .setRole(role)
2005         .setNodeId(pushNodePathToFrontend(node))
2006         .release();
2007
2008     if (exists) {
2009         if (activeDescendantNode)
2010             value->setActiveDescendantNodeId(pushNodePathToFrontend(activeDescendantNode));
2011         if (busy)
2012             value->setBusy(busy);
2013         if (supportsChecked)
2014             value->setChecked(checked);
2015         if (childNodeIds)
2016             value->setChildNodeIds(childNodeIds);
2017         if (controlledNodeIds)
2018             value->setControlledNodeIds(controlledNodeIds);
2019         if (currentState != Inspector::Protocol::DOM::AccessibilityProperties::Current::False)
2020             value->setCurrent(currentState);
2021         if (disabled)
2022             value->setDisabled(disabled);
2023         if (supportsExpanded)
2024             value->setExpanded(expanded);
2025         if (flowedNodeIds)
2026             value->setFlowedNodeIds(flowedNodeIds);
2027         if (supportsFocused)
2028             value->setFocused(focused);
2029         if (ignored)
2030             value->setIgnored(ignored);
2031         if (ignoredByDefault)
2032             value->setIgnoredByDefault(ignoredByDefault);
2033         if (invalid != Inspector::Protocol::DOM::AccessibilityProperties::Invalid::False)
2034             value->setInvalid(invalid);
2035         if (hidden)
2036             value->setHidden(hidden);
2037         if (supportsLiveRegion) {
2038             value->setLiveRegionAtomic(liveRegionAtomic);
2039             if (liveRegionRelevant->length())
2040                 value->setLiveRegionRelevant(liveRegionRelevant);
2041             value->setLiveRegionStatus(liveRegionStatus);
2042         }
2043         if (mouseEventNode)
2044             value->setMouseEventNodeId(pushNodePathToFrontend(mouseEventNode));
2045         if (ownedNodeIds)
2046             value->setOwnedNodeIds(ownedNodeIds);
2047         if (parentNode)
2048             value->setParentNodeId(pushNodePathToFrontend(parentNode));
2049         if (supportsPressed)
2050             value->setPressed(pressed);
2051         if (readonly)
2052             value->setReadonly(readonly);
2053         if (supportsRequired)
2054             value->setRequired(required);
2055         if (selected)
2056             value->setSelected(selected);
2057         if (selectedChildNodeIds)
2058             value->setSelectedChildNodeIds(selectedChildNodeIds);
2059         
2060         // H1 -- H6 always have a headingLevel property that can be complimented by a hierarchicalLevel
2061         // property when aria-level is set on the element, in which case we want to remain calling
2062         // this value the "Heading Level" in the inspector.
2063         // Also, we do not want it to say Hierarchy Level: 0
2064         if (headingLevel)
2065             value->setHeadingLevel(level);
2066         else if (level)
2067             value->setHierarchyLevel(level);
2068         if (isPopupButton)
2069             value->setIsPopUpButton(isPopupButton);
2070     }
2071
2072     return value;
2073 }
2074
2075 static bool containsOnlyHTMLWhitespace(Node* node)
2076 {
2077     // FIXME: Respect ignoreWhitespace setting from inspector front end?
2078     return is<Text>(node) && downcast<Text>(*node).data().isAllSpecialCharacters<isHTMLSpace>();
2079 }
2080
2081 Node* InspectorDOMAgent::innerFirstChild(Node* node)
2082 {
2083     node = node->firstChild();
2084     while (containsOnlyHTMLWhitespace(node))
2085         node = node->nextSibling();
2086     return node;
2087 }
2088
2089 Node* InspectorDOMAgent::innerNextSibling(Node* node)
2090 {
2091     do {
2092         node = node->nextSibling();
2093     } while (containsOnlyHTMLWhitespace(node));
2094     return node;
2095 }
2096
2097 Node* InspectorDOMAgent::innerPreviousSibling(Node* node)
2098 {
2099     do {
2100         node = node->previousSibling();
2101     } while (containsOnlyHTMLWhitespace(node));
2102     return node;
2103 }
2104
2105 unsigned InspectorDOMAgent::innerChildNodeCount(Node* node)
2106 {
2107     unsigned count = 0;
2108     for (Node* child = innerFirstChild(node); child; child = innerNextSibling(child))
2109         ++count;
2110     return count;
2111 }
2112
2113 Node* InspectorDOMAgent::innerParentNode(Node* node)
2114 {
2115     ASSERT(node);
2116     if (is<Document>(*node))
2117         return downcast<Document>(*node).ownerElement();
2118     if (is<ShadowRoot>(*node))
2119         return downcast<ShadowRoot>(*node).host();
2120     return node->parentNode();
2121 }
2122
2123 void InspectorDOMAgent::didCommitLoad(Document* document)
2124 {
2125     if (m_nodeToFocus && &m_nodeToFocus->document() == document)
2126         m_nodeToFocus = nullptr;
2127
2128     if (m_mousedOverNode && &m_mousedOverNode->document() == document)
2129         m_mousedOverNode = nullptr;
2130
2131     if (m_inspectedNode && &m_inspectedNode->document() == document)
2132         m_inspectedNode = nullptr;
2133
2134     RefPtr<Element> frameOwner = document->ownerElement();
2135     if (!frameOwner)
2136         return;
2137
2138     int frameOwnerId = m_documentNodeToIdMap.get(frameOwner);
2139     if (!frameOwnerId)
2140         return;
2141
2142     // Re-add frame owner element together with its new children.
2143     int parentId = m_documentNodeToIdMap.get(innerParentNode(frameOwner.get()));
2144     m_frontendDispatcher->childNodeRemoved(parentId, frameOwnerId);
2145     unbind(frameOwner.get(), &m_documentNodeToIdMap);
2146
2147     Ref<Inspector::Protocol::DOM::Node> value = buildObjectForNode(frameOwner.get(), 0, &m_documentNodeToIdMap);
2148     Node* previousSibling = innerPreviousSibling(frameOwner.get());
2149     int prevId = previousSibling ? m_documentNodeToIdMap.get(previousSibling) : 0;
2150     m_frontendDispatcher->childNodeInserted(parentId, prevId, WTFMove(value));
2151 }
2152
2153 int InspectorDOMAgent::identifierForNode(Node& node)
2154 {
2155     return pushNodePathToFrontend(&node);
2156 }
2157
2158 void InspectorDOMAgent::addEventListenersToNode(Node& node)
2159 {
2160 #if ENABLE(VIDEO)
2161     auto callback = EventFiredCallback::create(*this);
2162
2163     auto createEventListener = [&] (const AtomString& eventName) {
2164         node.addEventListener(eventName, callback.copyRef(), false);
2165     };
2166
2167 #if ENABLE(FULLSCREEN_API)
2168     if (is<Document>(node) || is<HTMLMediaElement>(node))
2169         createEventListener(eventNames().webkitfullscreenchangeEvent);
2170 #endif // ENABLE(FULLSCREEN_API)
2171
2172     if (is<HTMLMediaElement>(node)) {
2173         createEventListener(eventNames().abortEvent);
2174         createEventListener(eventNames().canplayEvent);
2175         createEventListener(eventNames().canplaythroughEvent);
2176         createEventListener(eventNames().emptiedEvent);
2177         createEventListener(eventNames().endedEvent);
2178         createEventListener(eventNames().loadeddataEvent);
2179         createEventListener(eventNames().loadedmetadataEvent);
2180         createEventListener(eventNames().loadstartEvent);
2181         createEventListener(eventNames().pauseEvent);
2182         createEventListener(eventNames().playEvent);
2183         createEventListener(eventNames().playingEvent);
2184         createEventListener(eventNames().seekedEvent);
2185         createEventListener(eventNames().seekingEvent);
2186         createEventListener(eventNames().stalledEvent);
2187         createEventListener(eventNames().suspendEvent);
2188         createEventListener(eventNames().waitingEvent);
2189
2190         if (!m_mediaMetricsTimer.isActive())
2191             m_mediaMetricsTimer.start(0_s, 1_s / 15.);
2192     }
2193 #else
2194     UNUSED_PARAM(node);
2195 #endif // ENABLE(VIDEO)
2196 }
2197
2198 void InspectorDOMAgent::didInsertDOMNode(Node& node)
2199 {
2200     if (containsOnlyHTMLWhitespace(&node))
2201         return;
2202
2203     // We could be attaching existing subtree. Forget the bindings.
2204     unbind(&node, &m_documentNodeToIdMap);
2205
2206     ContainerNode* parent = node.parentNode();
2207     if (!parent)
2208         return;
2209
2210     int parentId = m_documentNodeToIdMap.get(parent);
2211     // Return if parent is not mapped yet.
2212     if (!parentId)
2213         return;
2214
2215     if (!m_childrenRequested.contains(parentId)) {
2216         // No children are mapped yet -> only notify on changes of hasChildren.
2217         m_frontendDispatcher->childNodeCountUpdated(parentId, innerChildNodeCount(parent));
2218     } else {
2219         // Children have been requested -> return value of a new child.
2220         Node* prevSibling = innerPreviousSibling(&node);
2221         int prevId = prevSibling ? m_documentNodeToIdMap.get(prevSibling) : 0;
2222         Ref<Inspector::Protocol::DOM::Node> value = buildObjectForNode(&node, 0, &m_documentNodeToIdMap);
2223         m_frontendDispatcher->childNodeInserted(parentId, prevId, WTFMove(value));
2224     }
2225 }
2226
2227 void InspectorDOMAgent::didRemoveDOMNode(Node& node)
2228 {
2229     if (containsOnlyHTMLWhitespace(&node))
2230         return;
2231
2232     ContainerNode* parent = node.parentNode();
2233
2234     // If parent is not mapped yet -> ignore the event.
2235     if (!m_documentNodeToIdMap.contains(parent))
2236         return;
2237
2238     int parentId = m_documentNodeToIdMap.get(parent);
2239
2240     if (!m_childrenRequested.contains(parentId)) {
2241         // No children are mapped yet -> only notify on changes of hasChildren.
2242         if (innerChildNodeCount(parent) == 1)
2243             m_frontendDispatcher->childNodeCountUpdated(parentId, 0);
2244     } else
2245         m_frontendDispatcher->childNodeRemoved(parentId, m_documentNodeToIdMap.get(&node));
2246     unbind(&node, &m_documentNodeToIdMap);
2247 }
2248
2249 void InspectorDOMAgent::willModifyDOMAttr(Element&, const AtomString& oldValue, const AtomString& newValue)
2250 {
2251     m_suppressAttributeModifiedEvent = (oldValue == newValue);
2252 }
2253
2254 void InspectorDOMAgent::didModifyDOMAttr(Element& element, const AtomString& name, const AtomString& value)
2255 {
2256     bool shouldSuppressEvent = m_suppressAttributeModifiedEvent;
2257     m_suppressAttributeModifiedEvent = false;
2258     if (shouldSuppressEvent)
2259         return;
2260
2261     int id = boundNodeId(&element);
2262     if (!id)
2263         return;
2264
2265     if (auto* cssAgent = m_instrumentingAgents.inspectorCSSAgent())
2266         cssAgent->didModifyDOMAttr(element);
2267
2268     m_frontendDispatcher->attributeModified(id, name, value);
2269 }
2270
2271 void InspectorDOMAgent::didRemoveDOMAttr(Element& element, const AtomString& name)
2272 {
2273     int id = boundNodeId(&element);
2274     if (!id)
2275         return;
2276
2277     if (auto* cssAgent = m_instrumentingAgents.inspectorCSSAgent())
2278         cssAgent->didModifyDOMAttr(element);
2279
2280     m_frontendDispatcher->attributeRemoved(id, name);
2281 }
2282
2283 void InspectorDOMAgent::styleAttributeInvalidated(const Vector<Element*>& elements)
2284 {
2285     auto nodeIds = JSON::ArrayOf<int>::create();
2286     for (auto& element : elements) {
2287         int id = boundNodeId(element);
2288         if (!id)
2289             continue;
2290
2291         if (auto* cssAgent = m_instrumentingAgents.inspectorCSSAgent())
2292             cssAgent->didModifyDOMAttr(*element);
2293
2294         nodeIds->addItem(id);
2295     }
2296     m_frontendDispatcher->inlineStyleInvalidated(WTFMove(nodeIds));
2297 }
2298
2299 void InspectorDOMAgent::characterDataModified(CharacterData& characterData)
2300 {
2301     int id = m_documentNodeToIdMap.get(&characterData);
2302     if (!id) {
2303         // Push text node if it is being created.
2304         didInsertDOMNode(characterData);
2305         return;
2306     }
2307     m_frontendDispatcher->characterDataModified(id, characterData.data());
2308 }
2309
2310 void InspectorDOMAgent::didInvalidateStyleAttr(Element& element)
2311 {
2312     int id = m_documentNodeToIdMap.get(&element);
2313     if (!id)
2314         return;
2315
2316     if (!m_revalidateStyleAttrTask)
2317         m_revalidateStyleAttrTask = makeUnique<RevalidateStyleAttributeTask>(this);
2318     m_revalidateStyleAttrTask->scheduleFor(&element);
2319 }
2320
2321 void InspectorDOMAgent::didPushShadowRoot(Element& host, ShadowRoot& root)
2322 {
2323     int hostId = m_documentNodeToIdMap.get(&host);
2324     if (hostId)
2325         m_frontendDispatcher->shadowRootPushed(hostId, buildObjectForNode(&root, 0, &m_documentNodeToIdMap));
2326 }
2327
2328 void InspectorDOMAgent::willPopShadowRoot(Element& host, ShadowRoot& root)
2329 {
2330     int hostId = m_documentNodeToIdMap.get(&host);
2331     int rootId = m_documentNodeToIdMap.get(&root);
2332     if (hostId && rootId)
2333         m_frontendDispatcher->shadowRootPopped(hostId, rootId);
2334 }
2335
2336 void InspectorDOMAgent::didChangeCustomElementState(Element& element)
2337 {
2338     int elementId = m_documentNodeToIdMap.get(&element);
2339     if (!elementId)
2340         return;
2341
2342     m_frontendDispatcher->customElementStateChanged(elementId, customElementState(element));
2343 }
2344
2345 void InspectorDOMAgent::frameDocumentUpdated(Frame& frame)
2346 {
2347     Document* document = frame.document();
2348     if (!document)
2349         return;
2350
2351     if (!frame.isMainFrame())
2352         return;
2353
2354     // Only update the main frame document, nested frame document updates are not required
2355     // (will be handled by didCommitLoad()).
2356     setDocument(document);
2357 }
2358
2359 void InspectorDOMAgent::pseudoElementCreated(PseudoElement& pseudoElement)
2360 {
2361     Element* parent = pseudoElement.hostElement();
2362     if (!parent)
2363         return;
2364
2365     int parentId = m_documentNodeToIdMap.get(parent);
2366     if (!parentId)
2367         return;
2368
2369     pushChildNodesToFrontend(parentId, 1);
2370     m_frontendDispatcher->pseudoElementAdded(parentId, buildObjectForNode(&pseudoElement, 0, &m_documentNodeToIdMap));
2371 }
2372
2373 void InspectorDOMAgent::pseudoElementDestroyed(PseudoElement& pseudoElement)
2374 {
2375     int pseudoElementId = m_documentNodeToIdMap.get(&pseudoElement);
2376     if (!pseudoElementId)
2377         return;
2378
2379     // If a PseudoElement is bound, its parent element must have been bound.
2380     Element* parent = pseudoElement.hostElement();
2381     ASSERT(parent);
2382     int parentId = m_documentNodeToIdMap.get(parent);
2383     ASSERT(parentId);
2384
2385     unbind(&pseudoElement, &m_documentNodeToIdMap);
2386     m_frontendDispatcher->pseudoElementRemoved(parentId, pseudoElementId);
2387 }
2388
2389 void InspectorDOMAgent::didAddEventListener(EventTarget& target)
2390 {
2391     if (!is<Node>(target))
2392         return;
2393
2394     auto& node = downcast<Node>(target);
2395     if (!node.contains(m_inspectedNode.get()))
2396         return;
2397
2398     int nodeId = boundNodeId(&node);
2399     if (!nodeId)
2400         return;
2401
2402     if (m_suppressEventListenerChangedEvent)
2403         return;
2404
2405     m_suppressEventListenerChangedEvent = true;
2406
2407     m_frontendDispatcher->didAddEventListener(nodeId);
2408 }
2409
2410 void InspectorDOMAgent::willRemoveEventListener(EventTarget& target, const AtomString& eventType, EventListener& listener, bool capture)
2411 {
2412     if (!is<Node>(target))
2413         return;
2414
2415     auto& node = downcast<Node>(target);
2416     if (!node.contains(m_inspectedNode.get()))
2417         return;
2418
2419     int nodeId = boundNodeId(&node);
2420     if (!nodeId)
2421         return;
2422
2423     bool listenerExists = false;
2424     for (auto& item : node.eventListeners(eventType)) {
2425         if (item->callback() == listener && item->useCapture() == capture) {
2426             listenerExists = true;
2427             break;
2428         }
2429     }
2430
2431     if (!listenerExists)
2432         return;
2433
2434     m_eventListenerEntries.removeIf([&] (auto& entry) {
2435         return entry.value.matches(target, eventType, listener, capture);
2436     });
2437
2438     if (m_suppressEventListenerChangedEvent)
2439         return;
2440
2441     m_suppressEventListenerChangedEvent = true;
2442
2443     m_frontendDispatcher->willRemoveEventListener(nodeId);
2444 }
2445
2446 bool InspectorDOMAgent::isEventListenerDisabled(EventTarget& target, const AtomString& eventType, EventListener& listener, bool capture)
2447 {
2448     for (auto& inspectorEventListener : m_eventListenerEntries.values()) {
2449         if (inspectorEventListener.matches(target, eventType, listener, capture))
2450             return inspectorEventListener.disabled;
2451     }
2452     return false;
2453 }
2454
2455 void InspectorDOMAgent::eventDidResetAfterDispatch(const Event& event)
2456 {
2457     m_dispatchedEvents.remove(&event);
2458 }
2459
2460 bool InspectorDOMAgent::hasBreakpointForEventListener(EventTarget& target, const AtomString& eventType, EventListener& listener, bool capture)
2461 {
2462     for (auto& inspectorEventListener : m_eventListenerEntries.values()) {
2463         if (inspectorEventListener.matches(target, eventType, listener, capture))
2464             return inspectorEventListener.hasBreakpoint;
2465     }
2466     return false;
2467 }
2468
2469 int InspectorDOMAgent::idForEventListener(EventTarget& target, const AtomString& eventType, EventListener& listener, bool capture)
2470 {
2471     for (auto& inspectorEventListener : m_eventListenerEntries.values()) {
2472         if (inspectorEventListener.matches(target, eventType, listener, capture))
2473             return inspectorEventListener.identifier;
2474     }
2475     return 0;
2476 }
2477
2478 #if ENABLE(VIDEO)
2479 void InspectorDOMAgent::mediaMetricsTimerFired()
2480 {
2481     // FIXME: remove metrics information for any media element when it's destroyed
2482
2483     if (HTMLMediaElement::allMediaElements().isEmpty()) {
2484         if (m_mediaMetricsTimer.isActive())
2485             m_mediaMetricsTimer.stop();
2486         m_mediaMetrics.clear();
2487         return;
2488     }
2489
2490     for (auto* mediaElement : HTMLMediaElement::allMediaElements()) {
2491         if (!is<HTMLVideoElement>(mediaElement) || !mediaElement->isPlaying())
2492             continue;
2493
2494         auto videoPlaybackQuality = mediaElement->getVideoPlaybackQuality();
2495         unsigned displayCompositedVideoFrames = videoPlaybackQuality->displayCompositedVideoFrames();
2496
2497         auto iterator = m_mediaMetrics.find(mediaElement);
2498         if (iterator == m_mediaMetrics.end()) {
2499             m_mediaMetrics.set(mediaElement, MediaMetrics(displayCompositedVideoFrames));
2500             continue;
2501         }
2502
2503         bool isPowerEfficient = (displayCompositedVideoFrames - iterator->value.displayCompositedFrames) > 0;
2504         if (iterator->value.isPowerEfficient != isPowerEfficient) {
2505             iterator->value.isPowerEfficient = isPowerEfficient;
2506
2507             int nodeId = pushNodePathToFrontend(mediaElement);
2508             if (nodeId) {
2509                 auto timestamp = m_environment.executionStopwatch()->elapsedTime().seconds();
2510                 m_frontendDispatcher->powerEfficientPlaybackStateChanged(nodeId, timestamp, iterator->value.isPowerEfficient);
2511             }
2512         }
2513
2514         iterator->value.displayCompositedFrames = displayCompositedVideoFrames;
2515     }
2516
2517     m_mediaMetrics.removeIf([&] (auto& entry) {
2518         return !HTMLMediaElement::allMediaElements().contains(entry.key);
2519     });
2520 }
2521 #endif
2522
2523 Node* InspectorDOMAgent::nodeForPath(const String& path)
2524 {
2525     // The path is of form "1,HTML,2,BODY,1,DIV"
2526     if (!m_document)
2527         return nullptr;
2528
2529     Node* node = m_document.get();
2530     Vector<String> pathTokens = path.split(',');
2531     if (!pathTokens.size())
2532         return nullptr;
2533
2534     for (size_t i = 0; i < pathTokens.size() - 1; i += 2) {
2535         bool success = true;
2536         unsigned childNumber = pathTokens[i].toUInt(&success);
2537         if (!success)
2538             return nullptr;
2539
2540         Node* child;
2541         if (is<HTMLFrameOwnerElement>(*node)) {
2542             ASSERT(!childNumber);
2543             auto& frameOwner = downcast<HTMLFrameOwnerElement>(*node);
2544             child = frameOwner.contentDocument();
2545         } else {
2546             if (childNumber >= innerChildNodeCount(node))
2547                 return nullptr;
2548
2549             child = innerFirstChild(node);
2550             for (size_t j = 0; child && j < childNumber; ++j)
2551                 child = innerNextSibling(child);
2552         }
2553
2554         const auto& childName = pathTokens[i + 1];
2555         if (!child || child->nodeName() != childName)
2556             return nullptr;
2557         node = child;
2558     }
2559     return node;
2560 }
2561
2562 Node* InspectorDOMAgent::nodeForObjectId(const String& objectId)
2563 {
2564     InjectedScript injectedScript = m_injectedScriptManager.injectedScriptForObjectId(objectId);
2565     if (injectedScript.hasNoValue())
2566         return nullptr;
2567
2568     return scriptValueAsNode(injectedScript.findObjectById(objectId));
2569 }
2570
2571 void InspectorDOMAgent::pushNodeByPathToFrontend(ErrorString& errorString, const String& path, int* nodeId)
2572 {
2573     if (Node* node = nodeForPath(path))
2574         *nodeId = pushNodePathToFrontend(node);
2575     else
2576         errorString = "No node with given path found"_s;
2577 }
2578
2579 RefPtr<Inspector::Protocol::Runtime::RemoteObject> InspectorDOMAgent::resolveNode(Node* node, const String& objectGroup)
2580 {
2581     Document* document = &node->document();
2582     if (auto* templateHost = document->templateDocumentHost())
2583         document = templateHost;
2584     auto* frame =  document->frame();
2585     if (!frame)
2586         return nullptr;
2587
2588     auto& state = *mainWorldExecState(frame);
2589     auto injectedScript = m_injectedScriptManager.injectedScriptFor(&state);
2590     if (injectedScript.hasNoValue())
2591         return nullptr;
2592
2593     return injectedScript.wrapObject(nodeAsScriptValue(state, node), objectGroup);
2594 }
2595
2596 Node* InspectorDOMAgent::scriptValueAsNode(JSC::JSValue value)
2597 {
2598     if (!value || !value.isObject())
2599         return nullptr;
2600     return JSNode::toWrapped(*value.getObject()->vm(), value.getObject());
2601 }
2602
2603 JSC::JSValue InspectorDOMAgent::nodeAsScriptValue(JSC::ExecState& state, Node* node)
2604 {
2605     JSC::JSLockHolder lock(&state);
2606     return toJS(&state, deprecatedGlobalObjectForPrototype(&state), BindingSecurity::checkSecurityForNode(state, node));
2607 }
2608
2609 } // namespace WebCore