Use "= default" to denote default constructor or destructor
[WebKit-https.git] / Source / WebCore / inspector / InspectorOverlay.cpp
1 /*
2  * Copyright (C) 2011 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer.
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "config.h"
30 #include "InspectorOverlay.h"
31
32 #include "CacheStorageProvider.h"
33 #include "DocumentLoader.h"
34 #include "EditorClient.h"
35 #include "Element.h"
36 #include "EmptyClients.h"
37 #include "FrameView.h"
38 #include "GraphicsContext.h"
39 #include "InspectorClient.h"
40 #include "InspectorOverlayPage.h"
41 #include "LibWebRTCProvider.h"
42 #include "MainFrame.h"
43 #include "Node.h"
44 #include "Page.h"
45 #include "PageConfiguration.h"
46 #include "PolygonShape.h"
47 #include "PseudoElement.h"
48 #include "RTCController.h"
49 #include "RectangleShape.h"
50 #include "RenderBoxModelObject.h"
51 #include "RenderElement.h"
52 #include "RenderInline.h"
53 #include "RenderView.h"
54 #include "ScriptController.h"
55 #include "ScriptSourceCode.h"
56 #include "Settings.h"
57 #include "SocketProvider.h"
58 #include "StyledElement.h"
59 #include <inspector/InspectorProtocolObjects.h>
60 #include <inspector/InspectorValues.h>
61
62
63 namespace WebCore {
64 using namespace Inspector;
65 using namespace std::literals::chrono_literals;
66
67 static void contentsQuadToCoordinateSystem(const FrameView* mainView, const FrameView* view, FloatQuad& quad, InspectorOverlay::CoordinateSystem coordinateSystem)
68 {
69     quad.setP1(view->contentsToRootView(roundedIntPoint(quad.p1())));
70     quad.setP2(view->contentsToRootView(roundedIntPoint(quad.p2())));
71     quad.setP3(view->contentsToRootView(roundedIntPoint(quad.p3())));
72     quad.setP4(view->contentsToRootView(roundedIntPoint(quad.p4())));
73
74     if (coordinateSystem == InspectorOverlay::CoordinateSystem::View)
75         quad += toIntSize(mainView->scrollPosition());
76 }
77
78 static void contentsQuadToPage(const FrameView* mainView, const FrameView* view, FloatQuad& quad)
79 {
80     contentsQuadToCoordinateSystem(mainView, view, quad, InspectorOverlay::CoordinateSystem::View);
81 }
82
83 static void buildRendererHighlight(RenderObject* renderer, const HighlightConfig& highlightConfig, Highlight& highlight, InspectorOverlay::CoordinateSystem coordinateSystem)
84 {
85     Frame* containingFrame = renderer->document().frame();
86     if (!containingFrame)
87         return;
88
89     highlight.setDataFromConfig(highlightConfig);
90     FrameView* containingView = containingFrame->view();
91     FrameView* mainView = containingFrame->page()->mainFrame().view();
92
93     // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads().
94     bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot();
95
96     if (isSVGRenderer) {
97         highlight.type = HighlightType::Rects;
98         renderer->absoluteQuads(highlight.quads);
99         for (auto& quad : highlight.quads)
100             contentsQuadToCoordinateSystem(mainView, containingView, quad, coordinateSystem);
101     } else if (is<RenderBox>(*renderer) || is<RenderInline>(*renderer)) {
102         LayoutRect contentBox;
103         LayoutRect paddingBox;
104         LayoutRect borderBox;
105         LayoutRect marginBox;
106
107         if (is<RenderBox>(*renderer)) {
108             auto& renderBox = downcast<RenderBox>(*renderer);
109
110             LayoutBoxExtent margins(renderBox.marginTop(), renderBox.marginRight(), renderBox.marginBottom(), renderBox.marginLeft());
111             paddingBox = renderBox.clientBoxRect();
112             contentBox = LayoutRect(paddingBox.x() + renderBox.paddingLeft(), paddingBox.y() + renderBox.paddingTop(),
113                 paddingBox.width() - renderBox.paddingLeft() - renderBox.paddingRight(), paddingBox.height() - renderBox.paddingTop() - renderBox.paddingBottom());
114             borderBox = LayoutRect(paddingBox.x() - renderBox.borderLeft(), paddingBox.y() - renderBox.borderTop(),
115                 paddingBox.width() + renderBox.borderLeft() + renderBox.borderRight(), paddingBox.height() + renderBox.borderTop() + renderBox.borderBottom());
116             marginBox = LayoutRect(borderBox.x() - margins.left(), borderBox.y() - margins.top(),
117                 borderBox.width() + margins.left() + margins.right(), borderBox.height() + margins.top() + margins.bottom());
118         } else {
119             auto& renderInline = downcast<RenderInline>(*renderer);
120
121             // RenderInline's bounding box includes paddings and borders, excludes margins.
122             borderBox = renderInline.linesBoundingBox();
123             paddingBox = LayoutRect(borderBox.x() + renderInline.borderLeft(), borderBox.y() + renderInline.borderTop(),
124                 borderBox.width() - renderInline.borderLeft() - renderInline.borderRight(), borderBox.height() - renderInline.borderTop() - renderInline.borderBottom());
125             contentBox = LayoutRect(paddingBox.x() + renderInline.paddingLeft(), paddingBox.y() + renderInline.paddingTop(),
126                 paddingBox.width() - renderInline.paddingLeft() - renderInline.paddingRight(), paddingBox.height() - renderInline.paddingTop() - renderInline.paddingBottom());
127             // Ignore marginTop and marginBottom for inlines.
128             marginBox = LayoutRect(borderBox.x() - renderInline.marginLeft(), borderBox.y(),
129                 borderBox.width() + renderInline.horizontalMarginExtent(), borderBox.height());
130         }
131
132         FloatQuad absContentQuad = renderer->localToAbsoluteQuad(FloatRect(contentBox));
133         FloatQuad absPaddingQuad = renderer->localToAbsoluteQuad(FloatRect(paddingBox));
134         FloatQuad absBorderQuad = renderer->localToAbsoluteQuad(FloatRect(borderBox));
135         FloatQuad absMarginQuad = renderer->localToAbsoluteQuad(FloatRect(marginBox));
136
137         contentsQuadToCoordinateSystem(mainView, containingView, absContentQuad, coordinateSystem);
138         contentsQuadToCoordinateSystem(mainView, containingView, absPaddingQuad, coordinateSystem);
139         contentsQuadToCoordinateSystem(mainView, containingView, absBorderQuad, coordinateSystem);
140         contentsQuadToCoordinateSystem(mainView, containingView, absMarginQuad, coordinateSystem);
141
142         highlight.type = HighlightType::Node;
143         highlight.quads.append(absMarginQuad);
144         highlight.quads.append(absBorderQuad);
145         highlight.quads.append(absPaddingQuad);
146         highlight.quads.append(absContentQuad);
147     }
148 }
149
150 static void buildNodeHighlight(Node& node, const HighlightConfig& highlightConfig, Highlight& highlight, InspectorOverlay::CoordinateSystem coordinateSystem)
151 {
152     RenderObject* renderer = node.renderer();
153     if (!renderer)
154         return;
155
156     buildRendererHighlight(renderer, highlightConfig, highlight, coordinateSystem);
157 }
158
159 static void buildQuadHighlight(const FloatQuad& quad, const HighlightConfig& highlightConfig, Highlight& highlight)
160 {
161     highlight.setDataFromConfig(highlightConfig);
162     highlight.type = HighlightType::Rects;
163     highlight.quads.append(quad);
164 }
165
166 InspectorOverlay::InspectorOverlay(Page& page, InspectorClient* client)
167     : m_page(page)
168     , m_client(client)
169     , m_paintRectUpdateTimer(*this, &InspectorOverlay::updatePaintRectsTimerFired)
170 {
171 }
172
173 InspectorOverlay::~InspectorOverlay() = default;
174
175 void InspectorOverlay::paint(GraphicsContext& context)
176 {
177     if (!shouldShowOverlay())
178         return;
179
180     GraphicsContextStateSaver stateSaver(context);
181     FrameView* view = overlayPage()->mainFrame().view();
182     view->updateLayoutAndStyleIfNeededRecursive();
183     view->paint(context, IntRect(0, 0, view->width(), view->height()));
184 }
185
186 void InspectorOverlay::getHighlight(Highlight& highlight, InspectorOverlay::CoordinateSystem coordinateSystem) const
187 {
188     if (!m_highlightNode && !m_highlightQuad && !m_highlightNodeList)
189         return;
190
191     highlight.type = HighlightType::Rects;
192     if (m_highlightNode)
193         buildNodeHighlight(*m_highlightNode, m_nodeHighlightConfig, highlight, coordinateSystem);
194     else if (m_highlightNodeList) {
195         highlight.setDataFromConfig(m_nodeHighlightConfig);
196         for (unsigned i = 0; i < m_highlightNodeList->length(); ++i) {
197             Highlight nodeHighlight;
198             buildNodeHighlight(*(m_highlightNodeList->item(i)), m_nodeHighlightConfig, nodeHighlight, coordinateSystem);
199             if (nodeHighlight.type == HighlightType::Node)
200                 highlight.quads.appendVector(nodeHighlight.quads);
201         }
202         highlight.type = HighlightType::NodeList;
203     } else
204         buildQuadHighlight(*m_highlightQuad, m_quadHighlightConfig, highlight);
205 }
206
207 void InspectorOverlay::setPausedInDebuggerMessage(const String* message)
208 {
209     m_pausedInDebuggerMessage = message ? *message : String();
210     update();
211 }
212
213 void InspectorOverlay::hideHighlight()
214 {
215     m_highlightNode = nullptr;
216     m_highlightNodeList = nullptr;
217     m_highlightQuad = nullptr;
218     update();
219 }
220
221 void InspectorOverlay::highlightNodeList(RefPtr<NodeList>&& nodes, const HighlightConfig& highlightConfig)
222 {
223     m_nodeHighlightConfig = highlightConfig;
224     m_highlightNodeList = WTFMove(nodes);
225     m_highlightNode = nullptr;
226     update();
227 }
228
229 void InspectorOverlay::highlightNode(Node* node, const HighlightConfig& highlightConfig)
230 {
231     m_nodeHighlightConfig = highlightConfig;
232     m_highlightNode = node;
233     m_highlightNodeList = nullptr;
234     update();
235 }
236
237 void InspectorOverlay::highlightQuad(std::unique_ptr<FloatQuad> quad, const HighlightConfig& highlightConfig)
238 {
239     if (highlightConfig.usePageCoordinates)
240         *quad -= toIntSize(m_page.mainFrame().view()->scrollPosition());
241
242     m_quadHighlightConfig = highlightConfig;
243     m_highlightQuad = WTFMove(quad);
244     update();
245 }
246
247 Node* InspectorOverlay::highlightedNode() const
248 {
249     return m_highlightNode.get();
250 }
251
252 void InspectorOverlay::didSetSearchingForNode(bool enabled)
253 {
254     m_client->didSetSearchingForNode(enabled);
255 }
256
257 void InspectorOverlay::setIndicating(bool indicating)
258 {
259     m_indicating = indicating;
260
261     if (m_indicating)
262         evaluateInOverlay(ASCIILiteral("showPageIndication"));
263     else
264         evaluateInOverlay(ASCIILiteral("hidePageIndication"));
265
266     update();
267 }
268
269 bool InspectorOverlay::shouldShowOverlay() const
270 {
271     return m_highlightNode || m_highlightNodeList || m_highlightQuad || m_indicating || m_showingPaintRects || !m_pausedInDebuggerMessage.isNull();
272 }
273
274 void InspectorOverlay::update()
275 {
276     if (!shouldShowOverlay()) {
277         m_client->hideHighlight();
278         return;
279     }
280
281     FrameView* view = m_page.mainFrame().view();
282     if (!view)
283         return;
284
285     FrameView* overlayView = overlayPage()->mainFrame().view();
286     IntSize viewportSize = view->sizeForVisibleContent();
287     IntSize frameViewFullSize = view->sizeForVisibleContent(ScrollableArea::IncludeScrollbars);
288     overlayView->resize(frameViewFullSize);
289
290     // Clear canvas and paint things.
291     // FIXME: Remove extra parameter?
292     reset(viewportSize, IntSize());
293
294     // Include scrollbars to avoid masking them by the gutter.
295     drawGutter();
296     drawNodeHighlight();
297     drawQuadHighlight();
298     drawPausedInDebuggerMessage();
299     drawPaintRects();
300
301     // Position DOM elements.
302     overlayPage()->mainFrame().document()->resolveStyle(Document::ResolveStyleType::Rebuild);
303     if (overlayView->needsLayout())
304         overlayView->layout();
305
306     forcePaint();
307 }
308
309 static Ref<Inspector::Protocol::OverlayTypes::Point> buildObjectForPoint(const FloatPoint& point)
310 {
311     return Inspector::Protocol::OverlayTypes::Point::create()
312         .setX(point.x())
313         .setY(point.y())
314         .release();
315 }
316
317 static Ref<Inspector::Protocol::OverlayTypes::Rect> buildObjectForRect(const FloatRect& rect)
318 {
319     return Inspector::Protocol::OverlayTypes::Rect::create()
320         .setX(rect.x())
321         .setY(rect.y())
322         .setWidth(rect.width())
323         .setHeight(rect.height())
324         .release();
325 }
326
327 static Ref<Inspector::Protocol::OverlayTypes::Quad> buildArrayForQuad(const FloatQuad& quad)
328 {
329     auto array = Inspector::Protocol::OverlayTypes::Quad::create();
330     array->addItem(buildObjectForPoint(quad.p1()));
331     array->addItem(buildObjectForPoint(quad.p2()));
332     array->addItem(buildObjectForPoint(quad.p3()));
333     array->addItem(buildObjectForPoint(quad.p4()));
334     return array;
335 }
336
337 static Ref<Inspector::Protocol::OverlayTypes::FragmentHighlightData> buildObjectForHighlight(const Highlight& highlight)
338 {
339     auto arrayOfQuads = Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::Quad>::create();
340     for (auto& quad : highlight.quads)
341         arrayOfQuads->addItem(buildArrayForQuad(quad));
342
343     return Inspector::Protocol::OverlayTypes::FragmentHighlightData::create()
344         .setQuads(WTFMove(arrayOfQuads))
345         .setContentColor(highlight.contentColor.serialized())
346         .setContentOutlineColor(highlight.contentOutlineColor.serialized())
347         .setPaddingColor(highlight.paddingColor.serialized())
348         .setBorderColor(highlight.borderColor.serialized())
349         .setMarginColor(highlight.marginColor.serialized())
350         .release();
351 }
352
353 static Ref<Inspector::Protocol::OverlayTypes::Size> buildObjectForSize(const IntSize& size)
354 {
355     return Inspector::Protocol::OverlayTypes::Size::create()
356         .setWidth(size.width())
357         .setHeight(size.height())
358         .release();
359 }
360
361 void InspectorOverlay::setShowingPaintRects(bool showingPaintRects)
362 {
363     if (m_showingPaintRects == showingPaintRects)
364         return;
365
366     m_showingPaintRects = showingPaintRects;
367     if (!m_showingPaintRects) {
368         m_paintRects.clear();
369         m_paintRectUpdateTimer.stop();
370         drawPaintRects();
371         forcePaint();
372     }
373 }
374
375 void InspectorOverlay::showPaintRect(const FloatRect& rect)
376 {
377     if (!m_showingPaintRects)
378         return;
379
380     IntRect rootRect = m_page.mainFrame().view()->contentsToRootView(enclosingIntRect(rect));
381
382     const auto removeDelay = 250ms;
383
384     std::chrono::steady_clock::time_point removeTime = std::chrono::steady_clock::now() + removeDelay;
385     m_paintRects.append(TimeRectPair(removeTime, rootRect));
386
387     if (!m_paintRectUpdateTimer.isActive()) {
388         const Seconds paintRectsUpdateInterval { 32_ms };
389         m_paintRectUpdateTimer.startRepeating(paintRectsUpdateInterval);
390     }
391
392     drawPaintRects();
393     forcePaint();
394 }
395
396 void InspectorOverlay::updatePaintRectsTimerFired()
397 {
398     std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
399     bool rectsChanged = false;
400     while (!m_paintRects.isEmpty() && m_paintRects.first().first < now) {
401         m_paintRects.removeFirst();
402         rectsChanged = true;
403     }
404
405     if (m_paintRects.isEmpty())
406         m_paintRectUpdateTimer.stop();
407
408     if (rectsChanged) {
409         drawPaintRects();
410         forcePaint();
411     }
412 }
413
414 void InspectorOverlay::drawPaintRects()
415 {
416     auto arrayOfRects = Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::Rect>::create();
417     for (const auto& pair : m_paintRects)
418         arrayOfRects->addItem(buildObjectForRect(pair.second));
419
420     evaluateInOverlay(ASCIILiteral("updatePaintRects"), WTFMove(arrayOfRects));
421 }
422
423 void InspectorOverlay::drawGutter()
424 {
425     evaluateInOverlay(ASCIILiteral("drawGutter"));
426 }
427
428 static RefPtr<Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::FragmentHighlightData>> buildArrayForRendererFragments(RenderObject* renderer, const HighlightConfig& config)
429 {
430     auto arrayOfFragments = Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::FragmentHighlightData>::create();
431
432     Highlight highlight;
433     buildRendererHighlight(renderer, config, highlight, InspectorOverlay::CoordinateSystem::View);
434     arrayOfFragments->addItem(buildObjectForHighlight(highlight));
435
436     return WTFMove(arrayOfFragments);
437 }
438
439 static FloatPoint localPointToRoot(RenderObject* renderer, const FrameView* mainView, const FrameView* view, const FloatPoint& point)
440 {
441     FloatPoint result = renderer->localToAbsolute(point);
442     result = view->contentsToRootView(roundedIntPoint(result));
443     result += toIntSize(mainView->scrollPosition());
444     return result;
445 }
446
447 struct PathApplyInfo {
448     FrameView* rootView;
449     FrameView* view;
450     Inspector::Protocol::OverlayTypes::DisplayPath* pathArray;
451     RenderObject* renderer;
452     const ShapeOutsideInfo* shapeOutsideInfo;
453 };
454
455 static void appendPathCommandAndPoints(PathApplyInfo& info, const String& command, const FloatPoint points[], unsigned length)
456 {
457     FloatPoint point;
458     info.pathArray->addItem(command);
459     for (unsigned i = 0; i < length; i++) {
460         point = info.shapeOutsideInfo->shapeToRendererPoint(points[i]);
461         point = localPointToRoot(info.renderer, info.rootView, info.view, point);
462         info.pathArray->addItem(point.x());
463         info.pathArray->addItem(point.y());
464     }
465 }
466
467 static void appendPathSegment(PathApplyInfo& pathApplyInfo, const PathElement& pathElement)
468 {
469     FloatPoint point;
470     switch (pathElement.type) {
471     // The points member will contain 1 value.
472     case PathElementMoveToPoint:
473         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("M"), pathElement.points, 1);
474         break;
475     // The points member will contain 1 value.
476     case PathElementAddLineToPoint:
477         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("L"), pathElement.points, 1);
478         break;
479     // The points member will contain 3 values.
480     case PathElementAddCurveToPoint:
481         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("C"), pathElement.points, 3);
482         break;
483     // The points member will contain 2 values.
484     case PathElementAddQuadCurveToPoint:
485         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("Q"), pathElement.points, 2);
486         break;
487     // The points member will contain no values.
488     case PathElementCloseSubpath:
489         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("Z"), nullptr, 0);
490         break;
491     }
492 }
493
494 static RefPtr<Inspector::Protocol::OverlayTypes::ShapeOutsideData> buildObjectForShapeOutside(Frame* containingFrame, RenderBox* renderer)
495 {
496     const ShapeOutsideInfo* shapeOutsideInfo = renderer->shapeOutsideInfo();
497     if (!shapeOutsideInfo)
498         return nullptr;
499
500     LayoutRect shapeBounds = shapeOutsideInfo->computedShapePhysicalBoundingBox();
501     FloatQuad shapeQuad = renderer->localToAbsoluteQuad(FloatRect(shapeBounds));
502     contentsQuadToPage(containingFrame->page()->mainFrame().view(), containingFrame->view(), shapeQuad);
503
504     auto shapeObject = Inspector::Protocol::OverlayTypes::ShapeOutsideData::create()
505         .setBounds(buildArrayForQuad(shapeQuad))
506         .release();
507
508     Shape::DisplayPaths paths;
509     shapeOutsideInfo->computedShape().buildDisplayPaths(paths);
510
511     if (paths.shape.length()) {
512         auto shapePath = Inspector::Protocol::OverlayTypes::DisplayPath::create();
513         PathApplyInfo info;
514         info.rootView = containingFrame->page()->mainFrame().view();
515         info.view = containingFrame->view();
516         info.pathArray = &shapePath.get();
517         info.renderer = renderer;
518         info.shapeOutsideInfo = shapeOutsideInfo;
519
520         paths.shape.apply([&info](const PathElement& pathElement) {
521             appendPathSegment(info, pathElement);
522         });
523
524         shapeObject->setShape(shapePath.copyRef());
525
526         if (paths.marginShape.length()) {
527             auto marginShapePath = Inspector::Protocol::OverlayTypes::DisplayPath::create();
528             info.pathArray = &marginShapePath.get();
529
530             paths.marginShape.apply([&info](const PathElement& pathElement) {
531                 appendPathSegment(info, pathElement);
532             });
533
534             shapeObject->setMarginShape(marginShapePath.copyRef());
535         }
536     }
537
538     return WTFMove(shapeObject);
539 }
540
541 static RefPtr<Inspector::Protocol::OverlayTypes::ElementData> buildObjectForElementData(Node* node, HighlightType)
542 {
543     if (!is<Element>(node) || !node->document().frame())
544         return nullptr;
545
546     Element* effectiveElement = downcast<Element>(node);
547     if (node->isPseudoElement()) {
548         Element* hostElement = downcast<PseudoElement>(*node).hostElement();
549         if (!hostElement)
550             return nullptr;
551         effectiveElement = hostElement;
552     }
553
554     Element& element = *effectiveElement;
555     bool isXHTML = element.document().isXHTMLDocument();
556     auto elementData = Inspector::Protocol::OverlayTypes::ElementData::create()
557         .setTagName(isXHTML ? element.nodeName() : element.nodeName().convertToASCIILowercase())
558         .setIdValue(element.getIdAttribute())
559         .release();
560
561     if (element.hasClass() && is<StyledElement>(element)) {
562         auto classes = Inspector::Protocol::Array<String>::create();
563         HashSet<AtomicString> usedClassNames;
564         const SpaceSplitString& classNamesString = downcast<StyledElement>(element).classNames();
565         for (size_t i = 0; i < classNamesString.size(); ++i) {
566             const AtomicString& className = classNamesString[i];
567             if (usedClassNames.contains(className))
568                 continue;
569
570             usedClassNames.add(className);
571             classes->addItem(className);
572         }
573         elementData->setClasses(WTFMove(classes));
574     }
575
576     if (node->isPseudoElement()) {
577         if (node->pseudoId() == BEFORE)
578             elementData->setPseudoElement("before");
579         else if (node->pseudoId() == AFTER)
580             elementData->setPseudoElement("after");
581     }
582
583     RenderElement* renderer = element.renderer();
584     if (!renderer)
585         return nullptr;
586
587     Frame* containingFrame = node->document().frame();
588     FrameView* containingView = containingFrame->view();
589     IntRect boundingBox = snappedIntRect(containingView->contentsToRootView(renderer->absoluteBoundingBoxRect()));
590     RenderBoxModelObject* modelObject = is<RenderBoxModelObject>(*renderer) ? downcast<RenderBoxModelObject>(renderer) : nullptr;
591     auto sizeObject = Inspector::Protocol::OverlayTypes::Size::create()
592         .setWidth(modelObject ? adjustForAbsoluteZoom(roundToInt(modelObject->offsetWidth()), *modelObject) : boundingBox.width())
593         .setHeight(modelObject ? adjustForAbsoluteZoom(roundToInt(modelObject->offsetHeight()), *modelObject) : boundingBox.height())
594         .release();
595     elementData->setSize(WTFMove(sizeObject));
596
597     if (is<RenderBox>(*renderer)) {
598         auto& renderBox = downcast<RenderBox>(*renderer);
599         if (RefPtr<Inspector::Protocol::OverlayTypes::ShapeOutsideData> shapeObject = buildObjectForShapeOutside(containingFrame, &renderBox))
600             elementData->setShapeOutsideData(WTFMove(shapeObject));
601     }
602
603     // Need to enable AX to get the computed role.
604     if (!WebCore::AXObjectCache::accessibilityEnabled())
605         WebCore::AXObjectCache::enableAccessibility();
606
607     if (AXObjectCache* axObjectCache = node->document().axObjectCache()) {
608         if (AccessibilityObject* axObject = axObjectCache->getOrCreate(node))
609             elementData->setRole(axObject->computedRoleString());
610     }
611
612     return WTFMove(elementData);
613 }
614
615 RefPtr<Inspector::Protocol::OverlayTypes::NodeHighlightData> InspectorOverlay::buildHighlightObjectForNode(Node* node, HighlightType type) const
616 {
617     if (!node)
618         return nullptr;
619
620     RenderObject* renderer = node->renderer();
621     if (!renderer)
622         return nullptr;
623
624     RefPtr<Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::FragmentHighlightData>> arrayOfFragmentHighlights = buildArrayForRendererFragments(renderer, m_nodeHighlightConfig);
625     if (!arrayOfFragmentHighlights)
626         return nullptr;
627
628     // The main view's scroll offset is shared across all quads.
629     FrameView* mainView = m_page.mainFrame().view();
630
631     auto nodeHighlightObject = Inspector::Protocol::OverlayTypes::NodeHighlightData::create()
632         .setScrollOffset(buildObjectForPoint(!mainView->delegatesScrolling() ? mainView->visibleContentRect().location() : FloatPoint()))
633         .setFragments(WTFMove(arrayOfFragmentHighlights))
634         .release();
635
636     if (m_nodeHighlightConfig.showInfo) {
637         if (RefPtr<Inspector::Protocol::OverlayTypes::ElementData> elementData = buildObjectForElementData(node, type))
638             nodeHighlightObject->setElementData(WTFMove(elementData));
639     }
640
641     return WTFMove(nodeHighlightObject);
642 }
643
644 Ref<Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::NodeHighlightData>> InspectorOverlay::buildObjectForHighlightedNodes() const
645 {
646     auto highlights = Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::NodeHighlightData>::create();
647
648     if (m_highlightNode) {
649         if (RefPtr<Inspector::Protocol::OverlayTypes::NodeHighlightData> nodeHighlightData = buildHighlightObjectForNode(m_highlightNode.get(), HighlightType::Node))
650             highlights->addItem(WTFMove(nodeHighlightData));
651     } else if (m_highlightNodeList) {
652         for (unsigned i = 0; i < m_highlightNodeList->length(); ++i) {
653             if (RefPtr<Inspector::Protocol::OverlayTypes::NodeHighlightData> nodeHighlightData = buildHighlightObjectForNode(m_highlightNodeList->item(i), HighlightType::NodeList))
654                 highlights->addItem(WTFMove(nodeHighlightData));
655         }
656     }
657
658     return highlights;
659 }
660
661 void InspectorOverlay::drawNodeHighlight()
662 {
663     if (m_highlightNode || m_highlightNodeList)
664         evaluateInOverlay("drawNodeHighlight", buildObjectForHighlightedNodes());
665 }
666
667 void InspectorOverlay::drawQuadHighlight()
668 {
669     if (!m_highlightQuad)
670         return;
671
672     Highlight highlight;
673     buildQuadHighlight(*m_highlightQuad, m_quadHighlightConfig, highlight);
674     evaluateInOverlay("drawQuadHighlight", buildObjectForHighlight(highlight));
675 }
676
677 void InspectorOverlay::drawPausedInDebuggerMessage()
678 {
679     if (!m_pausedInDebuggerMessage.isNull())
680         evaluateInOverlay("drawPausedInDebuggerMessage", m_pausedInDebuggerMessage);
681 }
682
683 Page* InspectorOverlay::overlayPage()
684 {
685     if (m_overlayPage)
686         return m_overlayPage.get();
687
688     PageConfiguration pageConfiguration(
689         createEmptyEditorClient(),
690         SocketProvider::create(),
691         LibWebRTCProvider::create(),
692         CacheStorageProvider::create()
693     );
694     fillWithEmptyClients(pageConfiguration);
695     m_overlayPage = std::make_unique<Page>(WTFMove(pageConfiguration));
696     m_overlayPage->setDeviceScaleFactor(m_page.deviceScaleFactor());
697
698     Settings& settings = m_page.settings();
699     Settings& overlaySettings = m_overlayPage->settings();
700
701     overlaySettings.setStandardFontFamily(settings.standardFontFamily());
702     overlaySettings.setSerifFontFamily(settings.serifFontFamily());
703     overlaySettings.setSansSerifFontFamily(settings.sansSerifFontFamily());
704     overlaySettings.setCursiveFontFamily(settings.cursiveFontFamily());
705     overlaySettings.setFantasyFontFamily(settings.fantasyFontFamily());
706     overlaySettings.setPictographFontFamily(settings.pictographFontFamily());
707     overlaySettings.setMinimumFontSize(settings.minimumFontSize());
708     overlaySettings.setMinimumLogicalFontSize(settings.minimumLogicalFontSize());
709     overlaySettings.setMediaEnabled(false);
710     overlaySettings.setScriptEnabled(true);
711     overlaySettings.setPluginsEnabled(false);
712
713     Frame& frame = m_overlayPage->mainFrame();
714     frame.setView(FrameView::create(frame));
715     frame.init();
716     FrameLoader& loader = frame.loader();
717     frame.view()->setCanHaveScrollbars(false);
718     frame.view()->setTransparent(true);
719     ASSERT(loader.activeDocumentLoader());
720     loader.activeDocumentLoader()->writer().setMIMEType("text/html");
721     loader.activeDocumentLoader()->writer().begin();
722     loader.activeDocumentLoader()->writer().addData(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
723     loader.activeDocumentLoader()->writer().end();
724
725 #if OS(WINDOWS)
726     evaluateInOverlay("setPlatform", "windows");
727 #elif OS(MAC_OS_X)
728     evaluateInOverlay("setPlatform", "mac");
729 #elif OS(UNIX)
730     evaluateInOverlay("setPlatform", "linux");
731 #endif
732
733     return m_overlayPage.get();
734 }
735
736 void InspectorOverlay::forcePaint()
737 {
738     // This overlay page is very weird and doesn't automatically paint. We have to force paints manually.
739     m_client->highlight();
740 }
741
742 void InspectorOverlay::reset(const IntSize& viewportSize, const IntSize& frameViewFullSize)
743 {
744     auto configObject = Inspector::Protocol::OverlayTypes::OverlayConfiguration::create()
745         .setDeviceScaleFactor(m_page.deviceScaleFactor())
746         .setViewportSize(buildObjectForSize(viewportSize))
747         .setFrameViewFullSize(buildObjectForSize(frameViewFullSize))
748         .release();
749     evaluateInOverlay("reset", WTFMove(configObject));
750 }
751
752 static void evaluateCommandInOverlay(Page* page, Ref<InspectorArray>&& command)
753 {
754     page->mainFrame().script().evaluate(ScriptSourceCode(makeString("dispatch(", command->toJSONString(), ')')));
755 }
756
757 void InspectorOverlay::evaluateInOverlay(const String& method)
758 {
759     Ref<InspectorArray> command = InspectorArray::create();
760     command->pushString(method);
761
762     evaluateCommandInOverlay(overlayPage(), WTFMove(command));
763 }
764
765 void InspectorOverlay::evaluateInOverlay(const String& method, const String& argument)
766 {
767     Ref<InspectorArray> command = InspectorArray::create();
768     command->pushString(method);
769     command->pushString(argument);
770
771     evaluateCommandInOverlay(overlayPage(), WTFMove(command));
772 }
773
774 void InspectorOverlay::evaluateInOverlay(const String& method, RefPtr<InspectorValue>&& argument)
775 {
776     Ref<InspectorArray> command = InspectorArray::create();
777     command->pushString(method);
778     command->pushValue(WTFMove(argument));
779
780     evaluateCommandInOverlay(overlayPage(), WTFMove(command));
781 }
782
783 void InspectorOverlay::freePage()
784 {
785     m_overlayPage = nullptr;
786 }
787
788 } // namespace WebCore