Web Inspector: Node highlights are wrong when the page is zoomed
[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 "DocumentLoader.h"
33 #include "Element.h"
34 #include "EmptyClients.h"
35 #include "FrameView.h"
36 #include "GraphicsContext.h"
37 #include "InspectorClient.h"
38 #include "InspectorOverlayPage.h"
39 #include "MainFrame.h"
40 #include "Node.h"
41 #include "Page.h"
42 #include "PageConfiguration.h"
43 #include "PolygonShape.h"
44 #include "RectangleShape.h"
45 #include "RenderBoxModelObject.h"
46 #include "RenderElement.h"
47 #include "RenderFlowThread.h"
48 #include "RenderInline.h"
49 #include "RenderNamedFlowFragment.h"
50 #include "RenderNamedFlowThread.h"
51 #include "RenderRegion.h"
52 #include "RenderView.h"
53 #include "ScriptController.h"
54 #include "ScriptSourceCode.h"
55 #include "Settings.h"
56 #include "StyledElement.h"
57 #include <bindings/ScriptValue.h>
58 #include <inspector/InspectorProtocolObjects.h>
59 #include <inspector/InspectorValues.h>
60 #include <wtf/text/StringBuilder.h>
61
62 using namespace Inspector;
63
64 namespace WebCore {
65
66 static void contentsQuadToCoordinateSystem(const FrameView* mainView, const FrameView* view, FloatQuad& quad, InspectorOverlay::CoordinateSystem coordinateSystem)
67 {
68     quad.setP1(view->contentsToRootView(roundedIntPoint(quad.p1())));
69     quad.setP2(view->contentsToRootView(roundedIntPoint(quad.p2())));
70     quad.setP3(view->contentsToRootView(roundedIntPoint(quad.p3())));
71     quad.setP4(view->contentsToRootView(roundedIntPoint(quad.p4())));
72
73     if (coordinateSystem == InspectorOverlay::CoordinateSystem::View)
74         quad += mainView->scrollOffset();
75 }
76
77 static void contentsQuadToPage(const FrameView* mainView, const FrameView* view, FloatQuad& quad)
78 {
79     contentsQuadToCoordinateSystem(mainView, view, quad, InspectorOverlay::CoordinateSystem::View);
80 }
81
82 static void buildRendererHighlight(RenderObject* renderer, RenderRegion* region, const HighlightConfig& highlightConfig, Highlight& highlight, InspectorOverlay::CoordinateSystem coordinateSystem)
83 {
84     Frame* containingFrame = renderer->document().frame();
85     if (!containingFrame)
86         return;
87
88     highlight.setDataFromConfig(highlightConfig);
89     FrameView* containingView = containingFrame->view();
90     FrameView* mainView = containingFrame->page()->mainFrame().view();
91
92     // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads().
93     bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot();
94
95     if (isSVGRenderer) {
96         highlight.type = HighlightType::Rects;
97         renderer->absoluteQuads(highlight.quads);
98         for (size_t i = 0; i < highlight.quads.size(); ++i)
99             contentsQuadToCoordinateSystem(mainView, containingView, highlight.quads[i], coordinateSystem);
100     } else if (is<RenderBox>(*renderer) || is<RenderInline>(*renderer)) {
101         LayoutRect contentBox;
102         LayoutRect paddingBox;
103         LayoutRect borderBox;
104         LayoutRect marginBox;
105
106         if (is<RenderBox>(*renderer)) {
107             auto& renderBox = downcast<RenderBox>(*renderer);
108
109             LayoutBoxExtent margins(renderBox.marginTop(), renderBox.marginRight(), renderBox.marginBottom(), renderBox.marginLeft());
110
111             if (!renderBox.isOutOfFlowPositioned() && region) {
112                 RenderBox::LogicalExtentComputedValues computedValues;
113                 renderBox.computeLogicalWidthInRegion(computedValues, region);
114                 margins.start(renderBox.style().writingMode()) = computedValues.m_margins.m_start;
115                 margins.end(renderBox.style().writingMode()) = computedValues.m_margins.m_end;
116             }
117
118             paddingBox = renderBox.clientBoxRectInRegion(region);
119             contentBox = LayoutRect(paddingBox.x() + renderBox.paddingLeft(), paddingBox.y() + renderBox.paddingTop(),
120                 paddingBox.width() - renderBox.paddingLeft() - renderBox.paddingRight(), paddingBox.height() - renderBox.paddingTop() - renderBox.paddingBottom());
121             borderBox = LayoutRect(paddingBox.x() - renderBox.borderLeft(), paddingBox.y() - renderBox.borderTop(),
122                 paddingBox.width() + renderBox.borderLeft() + renderBox.borderRight(), paddingBox.height() + renderBox.borderTop() + renderBox.borderBottom());
123             marginBox = LayoutRect(borderBox.x() - margins.left(), borderBox.y() - margins.top(),
124                 borderBox.width() + margins.left() + margins.right(), borderBox.height() + margins.top() + margins.bottom());
125         } else {
126             auto& renderInline = downcast<RenderInline>(*renderer);
127
128             // RenderInline's bounding box includes paddings and borders, excludes margins.
129             borderBox = renderInline.linesBoundingBox();
130             paddingBox = LayoutRect(borderBox.x() + renderInline.borderLeft(), borderBox.y() + renderInline.borderTop(),
131                 borderBox.width() - renderInline.borderLeft() - renderInline.borderRight(), borderBox.height() - renderInline.borderTop() - renderInline.borderBottom());
132             contentBox = LayoutRect(paddingBox.x() + renderInline.paddingLeft(), paddingBox.y() + renderInline.paddingTop(),
133                 paddingBox.width() - renderInline.paddingLeft() - renderInline.paddingRight(), paddingBox.height() - renderInline.paddingTop() - renderInline.paddingBottom());
134             // Ignore marginTop and marginBottom for inlines.
135             marginBox = LayoutRect(borderBox.x() - renderInline.marginLeft(), borderBox.y(),
136                 borderBox.width() + renderInline.horizontalMarginExtent(), borderBox.height());
137         }
138
139         FloatQuad absContentQuad;
140         FloatQuad absPaddingQuad;
141         FloatQuad absBorderQuad;
142         FloatQuad absMarginQuad;
143
144         if (region) {
145             RenderFlowThread* flowThread = region->flowThread();
146
147             // Figure out the quads in the space of the RenderFlowThread.
148             absContentQuad = renderer->localToContainerQuad(FloatRect(contentBox), flowThread);
149             absPaddingQuad = renderer->localToContainerQuad(FloatRect(paddingBox), flowThread);
150             absBorderQuad = renderer->localToContainerQuad(FloatRect(borderBox), flowThread);
151             absMarginQuad = renderer->localToContainerQuad(FloatRect(marginBox), flowThread);
152
153             // Move the quad relative to the space of the current region.
154             LayoutRect flippedRegionRect(region->flowThreadPortionRect());
155             flowThread->flipForWritingMode(flippedRegionRect);
156
157             FloatSize delta = region->contentBoxRect().location() - flippedRegionRect.location();
158             absContentQuad.move(delta);
159             absPaddingQuad.move(delta);
160             absBorderQuad.move(delta);
161             absMarginQuad.move(delta);
162
163             // Resolve the absolute quads starting from the current region.
164             absContentQuad = region->localToAbsoluteQuad(absContentQuad);
165             absPaddingQuad = region->localToAbsoluteQuad(absPaddingQuad);
166             absBorderQuad = region->localToAbsoluteQuad(absBorderQuad);
167             absMarginQuad = region->localToAbsoluteQuad(absMarginQuad);
168         } else {
169             absContentQuad = renderer->localToAbsoluteQuad(FloatRect(contentBox));
170             absPaddingQuad = renderer->localToAbsoluteQuad(FloatRect(paddingBox));
171             absBorderQuad = renderer->localToAbsoluteQuad(FloatRect(borderBox));
172             absMarginQuad = renderer->localToAbsoluteQuad(FloatRect(marginBox));
173         }
174
175         contentsQuadToCoordinateSystem(mainView, containingView, absContentQuad, coordinateSystem);
176         contentsQuadToCoordinateSystem(mainView, containingView, absPaddingQuad, coordinateSystem);
177         contentsQuadToCoordinateSystem(mainView, containingView, absBorderQuad, coordinateSystem);
178         contentsQuadToCoordinateSystem(mainView, containingView, absMarginQuad, coordinateSystem);
179
180         highlight.type = HighlightType::Node;
181         highlight.quads.append(absMarginQuad);
182         highlight.quads.append(absBorderQuad);
183         highlight.quads.append(absPaddingQuad);
184         highlight.quads.append(absContentQuad);
185     }
186 }
187
188 static void buildNodeHighlight(Node& node, RenderRegion* region, const HighlightConfig& highlightConfig, Highlight& highlight, InspectorOverlay::CoordinateSystem coordinateSystem)
189 {
190     RenderObject* renderer = node.renderer();
191     if (!renderer)
192         return;
193
194     buildRendererHighlight(renderer, region, highlightConfig, highlight, coordinateSystem);
195 }
196
197 static void buildQuadHighlight(const FloatQuad& quad, const HighlightConfig& highlightConfig, Highlight& highlight)
198 {
199     highlight.setDataFromConfig(highlightConfig);
200     highlight.type = HighlightType::Rects;
201     highlight.quads.append(quad);
202 }
203
204 InspectorOverlay::InspectorOverlay(Page& page, InspectorClient* client)
205     : m_page(page)
206     , m_client(client)
207     , m_paintRectUpdateTimer(*this, &InspectorOverlay::updatePaintRectsTimerFired)
208 {
209 }
210
211 InspectorOverlay::~InspectorOverlay()
212 {
213 }
214
215 void InspectorOverlay::paint(GraphicsContext& context)
216 {
217     if (!shouldShowOverlay())
218         return;
219
220     GraphicsContextStateSaver stateSaver(context);
221     FrameView* view = overlayPage()->mainFrame().view();
222     view->updateLayoutAndStyleIfNeededRecursive();
223     view->paint(&context, IntRect(0, 0, view->width(), view->height()));
224 }
225
226 void InspectorOverlay::getHighlight(Highlight& highlight, InspectorOverlay::CoordinateSystem coordinateSystem) const
227 {
228     if (!m_highlightNode && !m_highlightQuad)
229         return;
230
231     highlight.type = HighlightType::Rects;
232     if (m_highlightNode)
233         buildNodeHighlight(*m_highlightNode, nullptr, m_nodeHighlightConfig, highlight, coordinateSystem);
234     else
235         buildQuadHighlight(*m_highlightQuad, m_quadHighlightConfig, highlight);
236 }
237
238 void InspectorOverlay::setPausedInDebuggerMessage(const String* message)
239 {
240     m_pausedInDebuggerMessage = message ? *message : String();
241     update();
242 }
243
244 void InspectorOverlay::hideHighlight()
245 {
246     m_highlightNode = nullptr;
247     m_highlightNodeList = nullptr;
248     m_highlightQuad = nullptr;
249     update();
250 }
251
252 void InspectorOverlay::highlightNodeList(PassRefPtr<NodeList> nodes, const HighlightConfig& highlightConfig)
253 {
254     m_nodeHighlightConfig = highlightConfig;
255     m_highlightNodeList = nodes;
256     m_highlightNode = nullptr;
257     update();
258 }
259
260 void InspectorOverlay::highlightNode(Node* node, const HighlightConfig& highlightConfig)
261 {
262     m_nodeHighlightConfig = highlightConfig;
263     m_highlightNode = node;
264     m_highlightNodeList = nullptr;
265     update();
266 }
267
268 void InspectorOverlay::highlightQuad(std::unique_ptr<FloatQuad> quad, const HighlightConfig& highlightConfig)
269 {
270     if (m_quadHighlightConfig.usePageCoordinates)
271         *quad -= m_page.mainFrame().view()->scrollOffset();
272
273     m_quadHighlightConfig = highlightConfig;
274     m_highlightQuad = WTF::move(quad);
275     update();
276 }
277
278 Node* InspectorOverlay::highlightedNode() const
279 {
280     return m_highlightNode.get();
281 }
282
283 void InspectorOverlay::didSetSearchingForNode(bool enabled)
284 {
285     m_client->didSetSearchingForNode(enabled);
286 }
287
288 void InspectorOverlay::setIndicating(bool indicating)
289 {
290     m_indicating = indicating;
291
292     if (m_indicating)
293         evaluateInOverlay(ASCIILiteral("showPageIndication"));
294     else
295         evaluateInOverlay(ASCIILiteral("hidePageIndication"));
296
297     update();
298 }
299
300 bool InspectorOverlay::shouldShowOverlay() const
301 {
302     return m_highlightNode || m_highlightNodeList || m_highlightQuad || m_indicating || m_showingPaintRects || !m_pausedInDebuggerMessage.isNull();
303 }
304
305 void InspectorOverlay::update()
306 {
307     if (!shouldShowOverlay()) {
308         m_client->hideHighlight();
309         return;
310     }
311
312     FrameView* view = m_page.mainFrame().view();
313     if (!view)
314         return;
315
316     FrameView* overlayView = overlayPage()->mainFrame().view();
317     IntSize viewportSize = view->unscaledVisibleContentSizeIncludingObscuredArea();
318     IntSize frameViewFullSize = view->unscaledVisibleContentSizeIncludingObscuredArea(ScrollableArea::IncludeScrollbars);
319     overlayView->resize(frameViewFullSize);
320
321     // Clear canvas and paint things.
322     // FIXME: Remove extra parameter?
323     reset(viewportSize, IntSize());
324
325     // Include scrollbars to avoid masking them by the gutter.
326     drawGutter();
327     drawNodeHighlight();
328     drawQuadHighlight();
329     drawPausedInDebuggerMessage();
330     drawPaintRects();
331
332     // Position DOM elements.
333     overlayPage()->mainFrame().document()->recalcStyle(Style::Force);
334     if (overlayView->needsLayout())
335         overlayView->layout();
336
337     forcePaint();
338 }
339
340 static Ref<Inspector::Protocol::OverlayTypes::Point> buildObjectForPoint(const FloatPoint& point)
341 {
342     return Inspector::Protocol::OverlayTypes::Point::create()
343         .setX(point.x())
344         .setY(point.y())
345         .release();
346 }
347
348 static Ref<Inspector::Protocol::OverlayTypes::Rect> buildObjectForRect(const FloatRect& rect)
349 {
350     return Inspector::Protocol::OverlayTypes::Rect::create()
351         .setX(rect.x())
352         .setY(rect.y())
353         .setWidth(rect.width())
354         .setHeight(rect.height())
355         .release();
356 }
357
358 static Ref<Inspector::Protocol::OverlayTypes::Quad> buildArrayForQuad(const FloatQuad& quad)
359 {
360     auto array = Inspector::Protocol::OverlayTypes::Quad::create();
361     array->addItem(buildObjectForPoint(quad.p1()));
362     array->addItem(buildObjectForPoint(quad.p2()));
363     array->addItem(buildObjectForPoint(quad.p3()));
364     array->addItem(buildObjectForPoint(quad.p4()));
365     return WTF::move(array);
366 }
367
368 static Ref<Inspector::Protocol::OverlayTypes::FragmentHighlightData> buildObjectForHighlight(const Highlight& highlight)
369 {
370     auto arrayOfQuads = Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::Quad>::create();
371     for (size_t i = 0; i < highlight.quads.size(); ++i)
372         arrayOfQuads->addItem(buildArrayForQuad(highlight.quads[i]));
373
374     return Inspector::Protocol::OverlayTypes::FragmentHighlightData::create()
375         .setQuads(WTF::move(arrayOfQuads))
376         .setContentColor(highlight.contentColor.serialized())
377         .setContentOutlineColor(highlight.contentOutlineColor.serialized())
378         .setPaddingColor(highlight.paddingColor.serialized())
379         .setBorderColor(highlight.borderColor.serialized())
380         .setMarginColor(highlight.marginColor.serialized())
381         .release();
382 }
383
384 static RefPtr<Inspector::Protocol::OverlayTypes::Region> buildObjectForRegion(FrameView* mainView, RenderRegion* region)
385 {
386     FrameView* containingView = region->frame().view();
387     if (!containingView)
388         return nullptr;
389
390     RenderBlockFlow& regionContainer = downcast<RenderBlockFlow>(*region->parent());
391     LayoutRect borderBox = regionContainer.borderBoxRect();
392     borderBox.setWidth(borderBox.width() + regionContainer.verticalScrollbarWidth());
393     borderBox.setHeight(borderBox.height() + regionContainer.horizontalScrollbarHeight());
394
395     // Create incoming and outgoing boxes that we use to chain the regions toghether.
396     const LayoutSize linkBoxSize(10, 10);
397     const LayoutSize linkBoxMidpoint(linkBoxSize.width() / 2, linkBoxSize.height() / 2);
398
399     LayoutRect incomingRectBox = LayoutRect(borderBox.location() - linkBoxMidpoint, linkBoxSize);
400     LayoutRect outgoingRectBox = LayoutRect(borderBox.location() - linkBoxMidpoint + borderBox.size(), linkBoxSize);
401
402     // Move the link boxes slightly inside the region border box.
403     LayoutUnit maxUsableHeight = std::max(LayoutUnit(), borderBox.height() - linkBoxMidpoint.height());
404     LayoutUnit linkBoxVerticalOffset = std::min(LayoutUnit::fromPixel(15), maxUsableHeight);
405     incomingRectBox.move(0, linkBoxVerticalOffset);
406     outgoingRectBox.move(0, -linkBoxVerticalOffset);
407
408     FloatQuad borderRectQuad = regionContainer.localToAbsoluteQuad(FloatRect(borderBox));
409     FloatQuad incomingRectQuad = regionContainer.localToAbsoluteQuad(FloatRect(incomingRectBox));
410     FloatQuad outgoingRectQuad = regionContainer.localToAbsoluteQuad(FloatRect(outgoingRectBox));
411
412     contentsQuadToPage(mainView, containingView, borderRectQuad);
413     contentsQuadToPage(mainView, containingView, incomingRectQuad);
414     contentsQuadToPage(mainView, containingView, outgoingRectQuad);
415
416     return Inspector::Protocol::OverlayTypes::Region::create()
417         .setBorderQuad(buildArrayForQuad(borderRectQuad))
418         .setIncomingQuad(buildArrayForQuad(incomingRectQuad))
419         .setOutgoingQuad(buildArrayForQuad(outgoingRectQuad))
420         .release();
421 }
422
423 static Ref<Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::Region>> buildObjectForFlowRegions(RenderRegion* region, RenderFlowThread* flowThread)
424 {
425     FrameView* mainFrameView = region->document().page()->mainFrame().view();
426
427     auto arrayOfRegions = Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::Region>::create();
428
429     const RenderRegionList& regionList = flowThread->renderRegionList();
430     for (auto& iterRegion : regionList) {
431         if (!iterRegion->isValid())
432             continue;
433         RefPtr<Inspector::Protocol::OverlayTypes::Region> regionObject = buildObjectForRegion(mainFrameView, iterRegion);
434         if (!regionObject)
435             continue;
436         if (region == iterRegion) {
437             // Let the script know that this is the currently highlighted node.
438             regionObject->setIsHighlighted(true);
439         }
440         arrayOfRegions->addItem(WTF::move(regionObject));
441     }
442
443     return WTF::move(arrayOfRegions);
444 }
445
446 static Ref<Inspector::Protocol::OverlayTypes::Size> buildObjectForSize(const IntSize& size)
447 {
448     return Inspector::Protocol::OverlayTypes::Size::create()
449         .setWidth(size.width())
450         .setHeight(size.height())
451         .release();
452 }
453
454 static RefPtr<Inspector::Protocol::OverlayTypes::Quad> buildQuadObjectForCSSRegionContentClip(RenderRegion* region)
455 {
456     Frame* containingFrame = region->document().frame();
457     if (!containingFrame)
458         return nullptr;
459
460     FrameView* containingView = containingFrame->view();
461     FrameView* mainView = containingFrame->page()->mainFrame().view();
462     RenderFlowThread* flowThread = region->flowThread();
463
464     // Get the clip box of the current region and covert it into an absolute quad.
465     LayoutRect flippedRegionRect(region->flowThreadPortionOverflowRect());
466     flowThread->flipForWritingMode(flippedRegionRect);
467
468     // Apply any border or padding of the region.
469     flippedRegionRect.setLocation(region->contentBoxRect().location());
470     
471     FloatQuad clipQuad = region->localToAbsoluteQuad(FloatRect(flippedRegionRect));
472     contentsQuadToPage(mainView, containingView, clipQuad);
473
474     return buildArrayForQuad(clipQuad);
475 }
476
477 void InspectorOverlay::setShowingPaintRects(bool showingPaintRects)
478 {
479     if (m_showingPaintRects == showingPaintRects)
480         return;
481
482     m_showingPaintRects = showingPaintRects;
483     if (!m_showingPaintRects) {
484         m_paintRects.clear();
485         m_paintRectUpdateTimer.stop();
486         drawPaintRects();
487         forcePaint();
488     }
489 }
490
491 void InspectorOverlay::showPaintRect(const FloatRect& rect)
492 {
493     if (!m_showingPaintRects)
494         return;
495
496     IntRect rootRect = m_page.mainFrame().view()->contentsToRootView(enclosingIntRect(rect));
497
498     const std::chrono::milliseconds removeDelay = std::chrono::milliseconds(250);
499
500     std::chrono::steady_clock::time_point removeTime = std::chrono::steady_clock::now() + removeDelay;
501     m_paintRects.append(TimeRectPair(removeTime, rootRect));
502
503     if (!m_paintRectUpdateTimer.isActive()) {
504         const double paintRectsUpdateIntervalSeconds = 0.032;
505         m_paintRectUpdateTimer.startRepeating(paintRectsUpdateIntervalSeconds);
506     }
507
508     drawPaintRects();
509     forcePaint();
510 }
511
512 void InspectorOverlay::updatePaintRectsTimerFired()
513 {
514     std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
515     bool rectsChanged = false;
516     while (!m_paintRects.isEmpty() && m_paintRects.first().first < now) {
517         m_paintRects.removeFirst();
518         rectsChanged = true;
519     }
520
521     if (m_paintRects.isEmpty())
522         m_paintRectUpdateTimer.stop();
523
524     if (rectsChanged) {
525         drawPaintRects();
526         forcePaint();
527     }
528 }
529
530 void InspectorOverlay::drawPaintRects()
531 {
532     auto arrayOfRects = Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::Rect>::create();
533     for (const auto& pair : m_paintRects)
534         arrayOfRects->addItem(buildObjectForRect(pair.second));
535
536     evaluateInOverlay(ASCIILiteral("updatePaintRects"), WTF::move(arrayOfRects));
537 }
538
539 void InspectorOverlay::drawGutter()
540 {
541     evaluateInOverlay(ASCIILiteral("drawGutter"));
542 }
543
544 static RefPtr<Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::FragmentHighlightData>> buildArrayForRendererFragments(RenderObject* renderer, const HighlightConfig& config)
545 {
546     auto arrayOfFragments = Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::FragmentHighlightData>::create();
547
548     RenderFlowThread* containingFlowThread = renderer->flowThreadContainingBlock();
549     if (!containingFlowThread) {
550         Highlight highlight;
551         buildRendererHighlight(renderer, nullptr, config, highlight, InspectorOverlay::CoordinateSystem::View);
552         arrayOfFragments->addItem(buildObjectForHighlight(highlight));
553     } else {
554         RenderRegion* startRegion = nullptr;
555         RenderRegion* endRegion = nullptr;
556         if (!containingFlowThread->getRegionRangeForBox(&renderer->enclosingBox(), startRegion, endRegion)) {
557             // The flow has no visible regions. The renderer is not visible on screen.
558             return nullptr;
559         }
560
561         const RenderRegionList& regionList = containingFlowThread->renderRegionList();
562         for (RenderRegionList::const_iterator iter = regionList.find(startRegion); iter != regionList.end(); ++iter) {
563             RenderRegion* region = *iter;
564             if (region->isValid()) {
565                 // Compute the highlight of the fragment inside the current region.
566                 Highlight highlight;
567                 buildRendererHighlight(renderer, region, config, highlight, InspectorOverlay::CoordinateSystem::View);
568                 Ref<Inspector::Protocol::OverlayTypes::FragmentHighlightData> fragmentHighlight = buildObjectForHighlight(highlight);
569
570                 // Compute the clipping area of the region.
571                 fragmentHighlight->setRegionClippingArea(buildQuadObjectForCSSRegionContentClip(region));
572                 arrayOfFragments->addItem(WTF::move(fragmentHighlight));
573             }
574             if (region == endRegion)
575                 break;
576         }
577     }
578
579     return WTF::move(arrayOfFragments);
580 }
581
582 #if ENABLE(CSS_SHAPES)
583 static FloatPoint localPointToRoot(RenderObject* renderer, const FrameView* mainView, const FrameView* view, const FloatPoint& point)
584 {
585     FloatPoint result = renderer->localToAbsolute(point);
586     result = view->contentsToRootView(roundedIntPoint(result));
587     result += mainView->scrollOffset();
588     return result;
589 }
590
591 struct PathApplyInfo {
592     FrameView* rootView;
593     FrameView* view;
594     Inspector::Protocol::OverlayTypes::DisplayPath* pathArray;
595     RenderObject* renderer;
596     const ShapeOutsideInfo* shapeOutsideInfo;
597 };
598
599 static void appendPathCommandAndPoints(PathApplyInfo& info, const String& command, const FloatPoint points[], unsigned length)
600 {
601     FloatPoint point;
602     info.pathArray->addItem(command);
603     for (unsigned i = 0; i < length; i++) {
604         point = info.shapeOutsideInfo->shapeToRendererPoint(points[i]);
605         point = localPointToRoot(info.renderer, info.rootView, info.view, point);
606         info.pathArray->addItem(point.x());
607         info.pathArray->addItem(point.y());
608     }
609 }
610
611 // Used as a functor for Shape::apply, which has not been cleaned up to use modern C++.
612 static void appendPathSegment(void* info, const PathElement* pathElement)
613 {
614     PathApplyInfo& pathApplyInfo = *static_cast<PathApplyInfo*>(info);
615     FloatPoint point;
616     switch (pathElement->type) {
617     // The points member will contain 1 value.
618     case PathElementMoveToPoint:
619         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("M"), pathElement->points, 1);
620         break;
621     // The points member will contain 1 value.
622     case PathElementAddLineToPoint:
623         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("L"), pathElement->points, 1);
624         break;
625     // The points member will contain 3 values.
626     case PathElementAddCurveToPoint:
627         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("C"), pathElement->points, 3);
628         break;
629     // The points member will contain 2 values.
630     case PathElementAddQuadCurveToPoint:
631         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("Q"), pathElement->points, 2);
632         break;
633     // The points member will contain no values.
634     case PathElementCloseSubpath:
635         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("Z"), nullptr, 0);
636         break;
637     }
638 }
639
640 static RefPtr<Inspector::Protocol::OverlayTypes::ShapeOutsideData> buildObjectForShapeOutside(Frame* containingFrame, RenderBox* renderer)
641 {
642     const ShapeOutsideInfo* shapeOutsideInfo = renderer->shapeOutsideInfo();
643     if (!shapeOutsideInfo)
644         return nullptr;
645
646     LayoutRect shapeBounds = shapeOutsideInfo->computedShapePhysicalBoundingBox();
647     FloatQuad shapeQuad = renderer->localToAbsoluteQuad(FloatRect(shapeBounds));
648     contentsQuadToPage(containingFrame->page()->mainFrame().view(), containingFrame->view(), shapeQuad);
649
650     auto shapeObject = Inspector::Protocol::OverlayTypes::ShapeOutsideData::create()
651         .setBounds(buildArrayForQuad(shapeQuad))
652         .release();
653
654     Shape::DisplayPaths paths;
655     shapeOutsideInfo->computedShape().buildDisplayPaths(paths);
656
657     if (paths.shape.length()) {
658         auto shapePath = Inspector::Protocol::OverlayTypes::DisplayPath::create();
659         PathApplyInfo info;
660         info.rootView = containingFrame->page()->mainFrame().view();
661         info.view = containingFrame->view();
662         info.pathArray = &shapePath.get();
663         info.renderer = renderer;
664         info.shapeOutsideInfo = shapeOutsideInfo;
665
666         paths.shape.apply(&info, &appendPathSegment);
667
668         shapeObject->setShape(shapePath.copyRef());
669
670         if (paths.marginShape.length()) {
671             auto marginShapePath = Inspector::Protocol::OverlayTypes::DisplayPath::create();
672             info.pathArray = &marginShapePath.get();
673
674             paths.marginShape.apply(&info, &appendPathSegment);
675
676             shapeObject->setMarginShape(marginShapePath.copyRef());
677         }
678     }
679
680     return WTF::move(shapeObject);
681 }
682 #endif
683
684 static RefPtr<Inspector::Protocol::OverlayTypes::ElementData> buildObjectForElementData(Node* node, HighlightType type)
685 {
686     if (!is<Element>(node) || !node->document().frame())
687         return nullptr;
688
689     Element& element = downcast<Element>(*node);
690     bool isXHTML = element.document().isXHTMLDocument();
691
692     auto elementData = Inspector::Protocol::OverlayTypes::ElementData::create()
693         .setTagName(isXHTML ? element.nodeName() : element.nodeName().lower())
694         .setIdValue(element.getIdAttribute())
695         .release();
696
697     HashSet<AtomicString> usedClassNames;
698     if (element.hasClass() && is<StyledElement>(element)) {
699         StringBuilder classNames;
700         const SpaceSplitString& classNamesString = downcast<StyledElement>(element).classNames();
701         size_t classNameCount = classNamesString.size();
702         for (size_t i = 0; i < classNameCount; ++i) {
703             const AtomicString& className = classNamesString[i];
704             if (usedClassNames.contains(className))
705                 continue;
706             usedClassNames.add(className);
707             classNames.append('.');
708             classNames.append(className);
709         }
710         elementData->setClassName(classNames.toString());
711     }
712
713     RenderElement* renderer = element.renderer();
714     if (!renderer)
715         return nullptr;
716
717     Frame* containingFrame = node->document().frame();
718     FrameView* containingView = containingFrame->view();
719     IntRect boundingBox = snappedIntRect(containingView->contentsToRootView(renderer->absoluteBoundingBoxRect()));
720     RenderBoxModelObject* modelObject = is<RenderBoxModelObject>(*renderer) ? downcast<RenderBoxModelObject>(renderer) : nullptr;
721     auto sizeObject = Inspector::Protocol::OverlayTypes::Size::create()
722         .setWidth(modelObject ? adjustForAbsoluteZoom(modelObject->pixelSnappedOffsetWidth(), *modelObject) : boundingBox.width())
723         .setHeight(modelObject ? adjustForAbsoluteZoom(modelObject->pixelSnappedOffsetHeight(), *modelObject) : boundingBox.height())
724         .release();
725     elementData->setSize(WTF::move(sizeObject));
726
727     if (type != HighlightType::NodeList && renderer->isRenderNamedFlowFragmentContainer()) {
728         RenderNamedFlowFragment& region = *downcast<RenderBlockFlow>(*renderer).renderNamedFlowFragment();
729         if (region.isValid()) {
730             RenderFlowThread* flowThread = region.flowThread();
731             auto regionFlowData = Inspector::Protocol::OverlayTypes::RegionFlowData::create()
732                 .setName(downcast<RenderNamedFlowThread>(*flowThread).flowThreadName())
733                 .setRegions(buildObjectForFlowRegions(&region, flowThread))
734                 .release();
735             elementData->setRegionFlowData(WTF::move(regionFlowData));
736         }
737     }
738
739     RenderFlowThread* containingFlowThread = renderer->flowThreadContainingBlock();
740     if (is<RenderNamedFlowThread>(containingFlowThread)) {
741         auto contentFlowData = Inspector::Protocol::OverlayTypes::ContentFlowData::create()
742             .setName(downcast<RenderNamedFlowThread>(*containingFlowThread).flowThreadName())
743             .release();
744
745         elementData->setContentFlowData(WTF::move(contentFlowData));
746     }
747
748 #if ENABLE(CSS_SHAPES)
749     if (is<RenderBox>(*renderer)) {
750         auto& renderBox = downcast<RenderBox>(*renderer);
751         if (RefPtr<Inspector::Protocol::OverlayTypes::ShapeOutsideData> shapeObject = buildObjectForShapeOutside(containingFrame, &renderBox))
752             elementData->setShapeOutsideData(WTF::move(shapeObject));
753     }
754 #endif
755
756     // Need to enable AX to get the computed role.
757     if (!WebCore::AXObjectCache::accessibilityEnabled())
758         WebCore::AXObjectCache::enableAccessibility();
759
760     if (AXObjectCache* axObjectCache = node->document().axObjectCache()) {
761         if (AccessibilityObject* axObject = axObjectCache->getOrCreate(node))
762             elementData->setRole(axObject->computedRoleString());
763     }
764
765     return WTF::move(elementData);
766 }
767
768 RefPtr<Inspector::Protocol::OverlayTypes::NodeHighlightData> InspectorOverlay::buildHighlightObjectForNode(Node* node, HighlightType type) const
769 {
770     if (!node)
771         return nullptr;
772
773     RenderObject* renderer = node->renderer();
774     if (!renderer)
775         return nullptr;
776
777     RefPtr<Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::FragmentHighlightData>> arrayOfFragmentHighlights = buildArrayForRendererFragments(renderer, m_nodeHighlightConfig);
778     if (!arrayOfFragmentHighlights)
779         return nullptr;
780
781     // The main view's scroll offset is shared across all quads.
782     FrameView* mainView = m_page.mainFrame().view();
783
784     auto nodeHighlightObject = Inspector::Protocol::OverlayTypes::NodeHighlightData::create()
785         .setScrollOffset(buildObjectForPoint(!mainView->delegatesScrolling() ? mainView->visibleContentRect().location() : FloatPoint()))
786         .setFragments(WTF::move(arrayOfFragmentHighlights))
787         .release();
788
789     if (m_nodeHighlightConfig.showInfo) {
790         if (RefPtr<Inspector::Protocol::OverlayTypes::ElementData> elementData = buildObjectForElementData(node, type))
791             nodeHighlightObject->setElementData(WTF::move(elementData));
792     }
793
794     return WTF::move(nodeHighlightObject);
795 }
796
797 Ref<Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::NodeHighlightData>> InspectorOverlay::buildObjectForHighlightedNodes() const
798 {
799     auto highlights = Inspector::Protocol::Array<Inspector::Protocol::OverlayTypes::NodeHighlightData>::create();
800
801     if (m_highlightNode) {
802         if (RefPtr<Inspector::Protocol::OverlayTypes::NodeHighlightData> nodeHighlightData = buildHighlightObjectForNode(m_highlightNode.get(), HighlightType::Node))
803             highlights->addItem(WTF::move(nodeHighlightData));
804     } else if (m_highlightNodeList) {
805         for (unsigned i = 0; i < m_highlightNodeList->length(); ++i) {
806             if (RefPtr<Inspector::Protocol::OverlayTypes::NodeHighlightData> nodeHighlightData = buildHighlightObjectForNode(m_highlightNodeList->item(i), HighlightType::NodeList))
807                 highlights->addItem(WTF::move(nodeHighlightData));
808         }
809     }
810
811     return WTF::move(highlights);
812 }
813
814 void InspectorOverlay::drawNodeHighlight()
815 {
816     if (m_highlightNode || m_highlightNodeList)
817         evaluateInOverlay("drawNodeHighlight", buildObjectForHighlightedNodes());
818 }
819
820 void InspectorOverlay::drawQuadHighlight()
821 {
822     if (!m_highlightQuad)
823         return;
824
825     Highlight highlight;
826     buildQuadHighlight(*m_highlightQuad, m_quadHighlightConfig, highlight);
827     evaluateInOverlay("drawQuadHighlight", buildObjectForHighlight(highlight));
828 }
829
830 void InspectorOverlay::drawPausedInDebuggerMessage()
831 {
832     if (!m_pausedInDebuggerMessage.isNull())
833         evaluateInOverlay("drawPausedInDebuggerMessage", m_pausedInDebuggerMessage);
834 }
835
836 Page* InspectorOverlay::overlayPage()
837 {
838     if (m_overlayPage)
839         return m_overlayPage.get();
840
841     PageConfiguration pageConfiguration;
842     fillWithEmptyClients(pageConfiguration);
843     m_overlayPage = std::make_unique<Page>(pageConfiguration);
844
845     Settings& settings = m_page.settings();
846     Settings& overlaySettings = m_overlayPage->settings();
847
848     overlaySettings.setStandardFontFamily(settings.standardFontFamily());
849     overlaySettings.setSerifFontFamily(settings.serifFontFamily());
850     overlaySettings.setSansSerifFontFamily(settings.sansSerifFontFamily());
851     overlaySettings.setCursiveFontFamily(settings.cursiveFontFamily());
852     overlaySettings.setFantasyFontFamily(settings.fantasyFontFamily());
853     overlaySettings.setPictographFontFamily(settings.pictographFontFamily());
854     overlaySettings.setMinimumFontSize(settings.minimumFontSize());
855     overlaySettings.setMinimumLogicalFontSize(settings.minimumLogicalFontSize());
856     overlaySettings.setMediaEnabled(false);
857     overlaySettings.setScriptEnabled(true);
858     overlaySettings.setPluginsEnabled(false);
859
860     Frame& frame = m_overlayPage->mainFrame();
861     frame.setView(FrameView::create(frame));
862     frame.init();
863     FrameLoader& loader = frame.loader();
864     frame.view()->setCanHaveScrollbars(false);
865     frame.view()->setTransparent(true);
866     ASSERT(loader.activeDocumentLoader());
867     loader.activeDocumentLoader()->writer().setMIMEType("text/html");
868     loader.activeDocumentLoader()->writer().begin();
869     loader.activeDocumentLoader()->writer().addData(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
870     loader.activeDocumentLoader()->writer().end();
871
872 #if OS(WINDOWS)
873     evaluateInOverlay("setPlatform", "windows");
874 #elif OS(MAC_OS_X)
875     evaluateInOverlay("setPlatform", "mac");
876 #elif OS(UNIX)
877     evaluateInOverlay("setPlatform", "linux");
878 #endif
879
880     return m_overlayPage.get();
881 }
882
883 void InspectorOverlay::forcePaint()
884 {
885     // This overlay page is very weird and doesn't automatically paint. We have to force paints manually.
886     m_client->highlight();
887 }
888
889 void InspectorOverlay::reset(const IntSize& viewportSize, const IntSize& frameViewFullSize)
890 {
891     auto configObject = Inspector::Protocol::OverlayTypes::OverlayConfiguration::create()
892         .setDeviceScaleFactor(m_page.deviceScaleFactor())
893         .setViewportSize(buildObjectForSize(viewportSize))
894         .setFrameViewFullSize(buildObjectForSize(frameViewFullSize))
895         .release();
896     evaluateInOverlay("reset", WTF::move(configObject));
897 }
898
899 void InspectorOverlay::evaluateInOverlay(const String& method)
900 {
901     Ref<InspectorArray> command = InspectorArray::create();
902     command->pushString(method);
903     overlayPage()->mainFrame().script().evaluate(ScriptSourceCode(makeString("dispatch(", command->toJSONString(), ')')));
904 }
905
906 void InspectorOverlay::evaluateInOverlay(const String& method, const String& argument)
907 {
908     Ref<InspectorArray> command = InspectorArray::create();
909     command->pushString(method);
910     command->pushString(argument);
911     overlayPage()->mainFrame().script().evaluate(ScriptSourceCode(makeString("dispatch(", command->toJSONString(), ')')));
912 }
913
914 void InspectorOverlay::evaluateInOverlay(const String& method, RefPtr<InspectorValue>&& argument)
915 {
916     Ref<InspectorArray> command = InspectorArray::create();
917     command->pushString(method);
918     command->pushValue(WTF::move(argument));
919     overlayPage()->mainFrame().script().evaluate(ScriptSourceCode(makeString("dispatch(", command->toJSONString(), ')')));
920 }
921
922 void InspectorOverlay::freePage()
923 {
924     m_overlayPage.reset();
925 }
926
927 } // namespace WebCore