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