524d9297a015d1968d64d075fc82e3ba47c74618
[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 Computer, 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
31 #if ENABLE(INSPECTOR)
32
33 #include "InspectorOverlay.h"
34
35 #include "DocumentLoader.h"
36 #include "Element.h"
37 #include "EmptyClients.h"
38 #include "FrameView.h"
39 #include "GraphicsContext.h"
40 #include "InspectorClient.h"
41 #include "InspectorOverlayPage.h"
42 #include "MainFrame.h"
43 #include "Node.h"
44 #include "Page.h"
45 #include "PolygonShape.h"
46 #include "RectangleShape.h"
47 #include "RenderBoxModelObject.h"
48 #include "RenderElement.h"
49 #include "RenderFlowThread.h"
50 #include "RenderInline.h"
51 #include "RenderNamedFlowFragment.h"
52 #include "RenderNamedFlowThread.h"
53 #include "RenderRegion.h"
54 #include "RenderView.h"
55 #include "ScriptController.h"
56 #include "ScriptSourceCode.h"
57 #include "Settings.h"
58 #include "StyledElement.h"
59 #include <bindings/ScriptValue.h>
60 #include <inspector/InspectorValues.h>
61 #include <wtf/text/StringBuilder.h>
62
63 using namespace Inspector;
64
65 namespace WebCore {
66
67 namespace {
68
69 Path quadToPath(const FloatQuad& quad)
70 {
71     Path quadPath;
72     quadPath.moveTo(quad.p1());
73     quadPath.addLineTo(quad.p2());
74     quadPath.addLineTo(quad.p3());
75     quadPath.addLineTo(quad.p4());
76     quadPath.closeSubpath();
77     return quadPath;
78 }
79
80 void drawOutlinedQuad(GraphicsContext* context, const FloatQuad& quad, const Color& fillColor, const Color& outlineColor)
81 {
82     static const int outlineThickness = 2;
83
84     Path quadPath = quadToPath(quad);
85
86     // Clip out the quad, then draw with a 2px stroke to get a pixel
87     // of outline (because inflating a quad is hard)
88     {
89         context->save();
90         context->clipOut(quadPath);
91
92         context->setStrokeThickness(outlineThickness);
93         context->setStrokeColor(outlineColor, ColorSpaceDeviceRGB);
94         context->strokePath(quadPath);
95
96         context->restore();
97     }
98
99     // Now do the fill
100     context->setFillColor(fillColor, ColorSpaceDeviceRGB);
101     context->fillPath(quadPath);
102 }
103
104 static void contentsQuadToPage(const FrameView* mainView, const FrameView* view, FloatQuad& quad)
105 {
106     quad.setP1(view->contentsToRootView(roundedIntPoint(quad.p1())));
107     quad.setP2(view->contentsToRootView(roundedIntPoint(quad.p2())));
108     quad.setP3(view->contentsToRootView(roundedIntPoint(quad.p3())));
109     quad.setP4(view->contentsToRootView(roundedIntPoint(quad.p4())));
110     quad += mainView->scrollOffset();
111 }
112
113 static void buildRendererHighlight(RenderObject* renderer, RenderRegion* region, const HighlightConfig& highlightConfig, Highlight* highlight)
114 {
115     Frame* containingFrame = renderer->document().frame();
116     if (!containingFrame)
117         return;
118
119     highlight->setDataFromConfig(highlightConfig);
120     FrameView* containingView = containingFrame->view();
121     FrameView* mainView = containingFrame->page()->mainFrame().view();
122
123     // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads().
124     bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot();
125
126     if (isSVGRenderer) {
127         highlight->type = HighlightTypeRects;
128         renderer->absoluteQuads(highlight->quads);
129         for (size_t i = 0; i < highlight->quads.size(); ++i)
130             contentsQuadToPage(mainView, containingView, highlight->quads[i]);
131     } else if (renderer->isBox() || renderer->isRenderInline()) {
132         LayoutRect contentBox;
133         LayoutRect paddingBox;
134         LayoutRect borderBox;
135         LayoutRect marginBox;
136
137         if (renderer->isBox()) {
138             RenderBox* renderBox = toRenderBox(renderer);
139
140             LayoutBoxExtent margins(renderBox->marginTop(), renderBox->marginRight(), renderBox->marginBottom(), renderBox->marginLeft());
141
142             if (!renderBox->isOutOfFlowPositioned() && region) {
143                 RenderBox::LogicalExtentComputedValues computedValues;
144                 renderBox->computeLogicalWidthInRegion(computedValues, region);
145                 margins.mutableLogicalLeft(renderBox->style().writingMode()) = computedValues.m_margins.m_start;
146                 margins.mutableLogicalRight(renderBox->style().writingMode()) = computedValues.m_margins.m_end;
147             }
148
149             paddingBox = renderBox->clientBoxRectInRegion(region);
150             contentBox = LayoutRect(paddingBox.x() + renderBox->paddingLeft(), paddingBox.y() + renderBox->paddingTop(),
151                 paddingBox.width() - renderBox->paddingLeft() - renderBox->paddingRight(), paddingBox.height() - renderBox->paddingTop() - renderBox->paddingBottom());
152             borderBox = LayoutRect(paddingBox.x() - renderBox->borderLeft(), paddingBox.y() - renderBox->borderTop(),
153                 paddingBox.width() + renderBox->borderLeft() + renderBox->borderRight(), paddingBox.height() + renderBox->borderTop() + renderBox->borderBottom());
154             marginBox = LayoutRect(borderBox.x() - margins.left(), borderBox.y() - margins.top(),
155                 borderBox.width() + margins.left() + margins.right(), borderBox.height() + margins.top() + margins.bottom());
156         } else {
157             RenderInline* renderInline = toRenderInline(renderer);
158
159             // RenderInline's bounding box includes paddings and borders, excludes margins.
160             borderBox = renderInline->linesBoundingBox();
161             paddingBox = LayoutRect(borderBox.x() + renderInline->borderLeft(), borderBox.y() + renderInline->borderTop(),
162                 borderBox.width() - renderInline->borderLeft() - renderInline->borderRight(), borderBox.height() - renderInline->borderTop() - renderInline->borderBottom());
163             contentBox = LayoutRect(paddingBox.x() + renderInline->paddingLeft(), paddingBox.y() + renderInline->paddingTop(),
164                 paddingBox.width() - renderInline->paddingLeft() - renderInline->paddingRight(), paddingBox.height() - renderInline->paddingTop() - renderInline->paddingBottom());
165             // Ignore marginTop and marginBottom for inlines.
166             marginBox = LayoutRect(borderBox.x() - renderInline->marginLeft(), borderBox.y(),
167                 borderBox.width() + renderInline->marginWidth(), borderBox.height());
168         }
169
170         FloatQuad absContentQuad;
171         FloatQuad absPaddingQuad;
172         FloatQuad absBorderQuad;
173         FloatQuad absMarginQuad;
174
175         if (region) {
176             RenderFlowThread* flowThread = region->flowThread();
177
178             // Figure out the quads in the space of the RenderFlowThread.
179             absContentQuad = renderer->localToContainerQuad(FloatRect(contentBox), flowThread);
180             absPaddingQuad = renderer->localToContainerQuad(FloatRect(paddingBox), flowThread);
181             absBorderQuad = renderer->localToContainerQuad(FloatRect(borderBox), flowThread);
182             absMarginQuad = renderer->localToContainerQuad(FloatRect(marginBox), flowThread);
183
184             // Move the quad relative to the space of the current region.
185             LayoutRect flippedRegionRect(region->flowThreadPortionRect());
186             flowThread->flipForWritingMode(flippedRegionRect);
187
188             FloatSize delta = region->contentBoxRect().location() - flippedRegionRect.location();
189             absContentQuad.move(delta);
190             absPaddingQuad.move(delta);
191             absBorderQuad.move(delta);
192             absMarginQuad.move(delta);
193
194             // Resolve the absolute quads starting from the current region.
195             absContentQuad = region->localToAbsoluteQuad(absContentQuad);
196             absPaddingQuad = region->localToAbsoluteQuad(absPaddingQuad);
197             absBorderQuad = region->localToAbsoluteQuad(absBorderQuad);
198             absMarginQuad = region->localToAbsoluteQuad(absMarginQuad);
199         } else {
200             absContentQuad = renderer->localToAbsoluteQuad(FloatRect(contentBox));
201             absPaddingQuad = renderer->localToAbsoluteQuad(FloatRect(paddingBox));
202             absBorderQuad = renderer->localToAbsoluteQuad(FloatRect(borderBox));
203             absMarginQuad = renderer->localToAbsoluteQuad(FloatRect(marginBox));
204         }
205
206         contentsQuadToPage(mainView, containingView, absContentQuad);
207         contentsQuadToPage(mainView, containingView, absPaddingQuad);
208         contentsQuadToPage(mainView, containingView, absBorderQuad);
209         contentsQuadToPage(mainView, containingView, absMarginQuad);
210
211         highlight->type = HighlightTypeNode;
212         highlight->quads.append(absMarginQuad);
213         highlight->quads.append(absBorderQuad);
214         highlight->quads.append(absPaddingQuad);
215         highlight->quads.append(absContentQuad);
216     }
217 }
218
219 static void buildNodeHighlight(Node* node, RenderRegion* region, const HighlightConfig& highlightConfig, Highlight* highlight)
220 {
221     RenderObject* renderer = node->renderer();
222     if (!renderer)
223         return;
224     buildRendererHighlight(renderer, region, highlightConfig, highlight);
225 }
226
227 static void buildQuadHighlight(const FloatQuad& quad, const HighlightConfig& highlightConfig, Highlight *highlight)
228 {
229     highlight->setDataFromConfig(highlightConfig);
230     highlight->type = HighlightTypeRects;
231     highlight->quads.append(quad);
232 }
233
234 } // anonymous namespace
235
236 InspectorOverlay::InspectorOverlay(Page& page, InspectorClient* client)
237     : m_page(page)
238     , m_client(client)
239 {
240 }
241
242 InspectorOverlay::~InspectorOverlay()
243 {
244 }
245
246 void InspectorOverlay::paint(GraphicsContext& context)
247 {
248     if (m_pausedInDebuggerMessage.isNull() && !m_highlightNode && !m_highlightQuad && m_size.isEmpty())
249         return;
250     GraphicsContextStateSaver stateSaver(context);
251     FrameView* view = overlayPage()->mainFrame().view();
252     view->updateLayoutAndStyleIfNeededRecursive();
253     view->paint(&context, IntRect(0, 0, view->width(), view->height()));
254 }
255
256 void InspectorOverlay::drawOutline(GraphicsContext* context, const LayoutRect& rect, const Color& color)
257 {
258     FloatRect outlineRect = rect;
259     drawOutlinedQuad(context, outlineRect, Color(), color);
260 }
261
262 void InspectorOverlay::getHighlight(Highlight* highlight) const
263 {
264     if (!m_highlightNode && !m_highlightQuad)
265         return;
266
267     highlight->type = HighlightTypeRects;
268     if (m_highlightNode)
269         buildNodeHighlight(m_highlightNode.get(), nullptr, m_nodeHighlightConfig, highlight);
270     else
271         buildQuadHighlight(*m_highlightQuad, m_quadHighlightConfig, highlight);
272 }
273
274 void InspectorOverlay::setPausedInDebuggerMessage(const String* message)
275 {
276     m_pausedInDebuggerMessage = message ? *message : String();
277     update();
278 }
279
280 void InspectorOverlay::hideHighlight()
281 {
282     m_highlightNode.clear();
283     m_highlightQuad.clear();
284     update();
285 }
286
287 void InspectorOverlay::highlightNode(Node* node, const HighlightConfig& highlightConfig)
288 {
289     m_nodeHighlightConfig = highlightConfig;
290     m_highlightNode = node;
291     update();
292 }
293
294 void InspectorOverlay::highlightQuad(PassOwnPtr<FloatQuad> quad, const HighlightConfig& highlightConfig)
295 {
296     if (m_quadHighlightConfig.usePageCoordinates)
297         *quad -= m_page.mainFrame().view()->scrollOffset();
298
299     m_quadHighlightConfig = highlightConfig;
300     m_highlightQuad = quad;
301     update();
302 }
303
304 Node* InspectorOverlay::highlightedNode() const
305 {
306     return m_highlightNode.get();
307 }
308
309 void InspectorOverlay::didSetSearchingForNode(bool enabled)
310 {
311     m_client->didSetSearchingForNode(enabled);
312 }
313
314 void InspectorOverlay::update()
315 {
316     if (!m_highlightNode && !m_highlightQuad && m_pausedInDebuggerMessage.isNull() && m_size.isEmpty()) {
317         m_client->hideHighlight();
318         return;
319     }
320
321     FrameView* view = m_page.mainFrame().view();
322     if (!view)
323         return;
324
325     FrameView* overlayView = overlayPage()->mainFrame().view();
326     IntSize viewportSize = view->visibleContentRect().size();
327     IntSize frameViewFullSize = view->visibleContentRectIncludingScrollbars().size();
328     IntSize size = m_size.isEmpty() ? frameViewFullSize : m_size;
329     overlayPage()->setPageScaleFactor(m_page.pageScaleFactor(), IntPoint());
330     size.scale(m_page.pageScaleFactor());
331     overlayView->resize(size);
332
333     // Clear canvas and paint things.
334     reset(viewportSize, m_size.isEmpty() ? IntSize() : frameViewFullSize);
335
336     // Include scrollbars to avoid masking them by the gutter.
337     drawGutter();
338     drawNodeHighlight();
339     drawQuadHighlight();
340     drawPausedInDebuggerMessage();
341
342     // Position DOM elements.
343     overlayPage()->mainFrame().document()->recalcStyle(Style::Force);
344     if (overlayView->needsLayout())
345         overlayView->layout();
346
347     // Kick paint.
348     m_client->highlight();
349 }
350
351 static PassRefPtr<InspectorObject> buildObjectForPoint(const FloatPoint& point)
352 {
353     RefPtr<InspectorObject> object = InspectorObject::create();
354     object->setNumber("x", point.x());
355     object->setNumber("y", point.y());
356     return object.release();
357 }
358
359 static PassRefPtr<InspectorArray> buildArrayForQuad(const FloatQuad& quad)
360 {
361     RefPtr<InspectorArray> array = InspectorArray::create();
362     array->pushObject(buildObjectForPoint(quad.p1()));
363     array->pushObject(buildObjectForPoint(quad.p2()));
364     array->pushObject(buildObjectForPoint(quad.p3()));
365     array->pushObject(buildObjectForPoint(quad.p4()));
366     return array.release();
367 }
368
369 static PassRefPtr<InspectorObject> buildObjectForHighlight(const Highlight& highlight)
370 {
371     RefPtr<InspectorObject> object = InspectorObject::create();
372     RefPtr<InspectorArray> array = InspectorArray::create();
373     for (size_t i = 0; i < highlight.quads.size(); ++i)
374         array->pushArray(buildArrayForQuad(highlight.quads[i]));
375     object->setArray("quads", array.release());
376     object->setBoolean("showRulers", highlight.showRulers);
377     object->setString("contentColor", highlight.contentColor.serialized());
378     object->setString("contentOutlineColor", highlight.contentOutlineColor.serialized());
379     object->setString("paddingColor", highlight.paddingColor.serialized());
380     object->setString("borderColor", highlight.borderColor.serialized());
381     object->setString("marginColor", highlight.marginColor.serialized());
382     return object.release();
383 }
384
385 static PassRefPtr<InspectorObject> buildObjectForRegionHighlight(FrameView* mainView, RenderRegion* region)
386 {
387     FrameView* containingView = region->frame().view();
388     if (!containingView)
389         return nullptr;
390
391     RenderBlockFlow* regionContainer = toRenderBlockFlow(region->parent());
392     LayoutRect borderBox = regionContainer->borderBoxRect();
393     borderBox.setWidth(borderBox.width() + regionContainer->verticalScrollbarWidth());
394     borderBox.setHeight(borderBox.height() + regionContainer->horizontalScrollbarHeight());
395
396     // Create incoming and outgoing boxes that we use to chain the regions toghether.
397     const LayoutSize linkBoxSize(10, 10);
398     const LayoutSize linkBoxMidpoint(linkBoxSize.width() / 2, linkBoxSize.height() / 2);
399     
400     LayoutRect incomingRectBox = LayoutRect(borderBox.location() - linkBoxMidpoint, linkBoxSize);
401     LayoutRect outgoingRectBox = LayoutRect(borderBox.location() - linkBoxMidpoint + borderBox.size(), linkBoxSize);
402
403     // Move the link boxes slightly inside the region border box.
404     LayoutUnit maxUsableHeight = std::max(LayoutUnit(), borderBox.height() - linkBoxMidpoint.height());
405     LayoutUnit linkBoxVerticalOffset = std::min(LayoutUnit::fromPixel(15), maxUsableHeight);
406     incomingRectBox.move(0, linkBoxVerticalOffset);
407     outgoingRectBox.move(0, -linkBoxVerticalOffset);
408
409     FloatQuad borderRectQuad = regionContainer->localToAbsoluteQuad(FloatRect(borderBox));
410     FloatQuad incomingRectQuad = regionContainer->localToAbsoluteQuad(FloatRect(incomingRectBox));
411     FloatQuad outgoingRectQuad = regionContainer->localToAbsoluteQuad(FloatRect(outgoingRectBox));
412
413     contentsQuadToPage(mainView, containingView, borderRectQuad);
414     contentsQuadToPage(mainView, containingView, incomingRectQuad);
415     contentsQuadToPage(mainView, containingView, outgoingRectQuad);
416
417     RefPtr<InspectorObject> regionObject = InspectorObject::create();
418
419     regionObject->setArray("borderQuad", buildArrayForQuad(borderRectQuad));
420     regionObject->setArray("incomingQuad", buildArrayForQuad(incomingRectQuad));
421     regionObject->setArray("outgoingQuad", buildArrayForQuad(outgoingRectQuad));
422
423     return regionObject.release();
424 }
425
426 static PassRefPtr<InspectorArray> buildObjectForCSSRegionsHighlight(RenderRegion* region, RenderFlowThread* flowThread)
427 {
428     FrameView* mainFrameView = region->document().page()->mainFrame().view();
429
430     RefPtr<InspectorArray> array = InspectorArray::create();
431
432     const RenderRegionList& regionList = flowThread->renderRegionList();
433     for (auto& iterRegion : regionList) {
434         if (!iterRegion->isValid())
435             continue;
436         RefPtr<InspectorObject> regionHighlightObject = buildObjectForRegionHighlight(mainFrameView, iterRegion);
437         if (!regionHighlightObject)
438             continue;
439         if (region == iterRegion) {
440             // Let the script know that this is the currently highlighted node.
441             regionHighlightObject->setBoolean("isHighlighted", true);
442         }
443         array->pushObject(regionHighlightObject.release());
444     }
445
446     return array.release();
447 }
448
449 static PassRefPtr<InspectorObject> buildObjectForSize(const IntSize& size)
450 {
451     RefPtr<InspectorObject> result = InspectorObject::create();
452     result->setNumber("width", size.width());
453     result->setNumber("height", size.height());
454     return result.release();
455 }
456
457 static PassRefPtr<InspectorObject> buildObjectForCSSRegionContentClip(RenderRegion* region)
458 {
459     Frame* containingFrame = region->document().frame();
460     if (!containingFrame)
461         return nullptr;
462
463     FrameView* containingView = containingFrame->view();
464     FrameView* mainView = containingFrame->page()->mainFrame().view();
465     RenderFlowThread* flowThread = region->flowThread();
466
467     // Get the clip box of the current region and covert it into an absolute quad.
468     LayoutRect flippedRegionRect(region->flowThreadPortionOverflowRect());
469     flowThread->flipForWritingMode(flippedRegionRect);
470
471     // Apply any border or padding of the region.
472     flippedRegionRect.setLocation(region->contentBoxRect().location());
473     
474     FloatQuad clipQuad = region->localToAbsoluteQuad(FloatRect(flippedRegionRect));
475     contentsQuadToPage(mainView, containingView, clipQuad);
476
477     RefPtr<InspectorObject> regionObject = InspectorObject::create();
478     regionObject->setArray("quad", buildArrayForQuad(clipQuad));
479     return regionObject.release();
480 }
481
482 void InspectorOverlay::drawGutter()
483 {
484     evaluateInOverlay("drawGutter", "");
485 }
486
487 static PassRefPtr<InspectorArray> buildObjectForRendererFragments(RenderObject* renderer, const HighlightConfig& config)
488 {
489     RefPtr<InspectorArray> fragmentsArray = InspectorArray::create();
490
491     RenderFlowThread* containingFlowThread = renderer->flowThreadContainingBlock();
492     if (!containingFlowThread) {
493         Highlight highlight;
494         buildRendererHighlight(renderer, nullptr, config, &highlight);
495         fragmentsArray->pushObject(buildObjectForHighlight(highlight));
496     } else {
497         RenderBox* enclosingBox = renderer->enclosingBox();
498         RenderRegion* startRegion = nullptr;
499         RenderRegion* endRegion = nullptr;
500         containingFlowThread->getRegionRangeForBox(enclosingBox, startRegion, endRegion);
501         if (!startRegion) {
502             // The flow has no visible regions. The renderer is not visible on screen.
503             return nullptr;
504         }
505         const RenderRegionList& regionList = containingFlowThread->renderRegionList();
506         for (RenderRegionList::const_iterator iter = regionList.find(startRegion); iter != regionList.end(); ++iter) {
507             RenderRegion* region = *iter;
508             if (region->isValid()) {
509                 // Compute the highlight of the fragment inside the current region.
510                 Highlight highlight;
511                 buildRendererHighlight(renderer, region, config, &highlight);
512                 RefPtr<InspectorObject> fragmentObject = buildObjectForHighlight(highlight);
513
514                 // Compute the clipping area of the region.
515                 fragmentObject->setObject("region", buildObjectForCSSRegionContentClip(region));
516                 fragmentsArray->pushObject(fragmentObject.release());
517             }
518             if (region == endRegion)
519                 break;
520         }
521     }
522
523     return fragmentsArray.release();
524 }
525
526 #if ENABLE(CSS_SHAPES)
527 static FloatPoint localPointToRoot(RenderObject* renderer, const FrameView* mainView, const FrameView* view, const FloatPoint& point)
528 {
529     FloatPoint result = renderer->localToAbsolute(point);
530     result = view->contentsToRootView(roundedIntPoint(result));
531     result += mainView->scrollOffset();
532     return result;
533 }
534
535 struct PathApplyInfo {
536     FrameView* rootView;
537     FrameView* view;
538     InspectorArray* array;
539     RenderObject* renderer;
540     const ShapeOutsideInfo* shapeOutsideInfo;
541 };
542
543 static void appendPathCommandAndPoints(PathApplyInfo* info, const String& command, const FloatPoint points[], unsigned length)
544 {
545     FloatPoint point;
546     info->array->pushString(command);
547     for (unsigned i = 0; i < length; i++) {
548         point = info->shapeOutsideInfo->shapeToRendererPoint(points[i]);
549         point = localPointToRoot(info->renderer, info->rootView, info->view, point);
550         info->array->pushNumber(point.x());
551         info->array->pushNumber(point.y());
552     }
553 }
554
555 static void appendPathSegment(void* info, const PathElement* pathElement)
556 {
557     PathApplyInfo* pathApplyInfo = static_cast<PathApplyInfo*>(info);
558     FloatPoint point;
559     switch (pathElement->type) {
560     // The points member will contain 1 value.
561     case PathElementMoveToPoint:
562         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("M"), pathElement->points, 1);
563         break;
564     // The points member will contain 1 value.
565     case PathElementAddLineToPoint:
566         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("L"), pathElement->points, 1);
567         break;
568     // The points member will contain 3 values.
569     case PathElementAddCurveToPoint:
570         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("C"), pathElement->points, 3);
571         break;
572     // The points member will contain 2 values.
573     case PathElementAddQuadCurveToPoint:
574         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("Q"), pathElement->points, 2);
575         break;
576     // The points member will contain no values.
577     case PathElementCloseSubpath:
578         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("Z"), nullptr, 0);
579         break;
580     }
581 }
582
583 static PassRefPtr<InspectorObject> buildObjectForShapeOutside(Frame* containingFrame, RenderBox* renderer)
584 {
585     const ShapeOutsideInfo* shapeOutsideInfo = renderer->shapeOutsideInfo();
586     if (!shapeOutsideInfo)
587         return nullptr;
588
589     RefPtr<InspectorObject> shapeObject = InspectorObject::create();
590     LayoutRect shapeBounds = shapeOutsideInfo->computedShapePhysicalBoundingBox();
591     FloatQuad shapeQuad = renderer->localToAbsoluteQuad(FloatRect(shapeBounds));
592     contentsQuadToPage(containingFrame->page()->mainFrame().view(), containingFrame->view(), shapeQuad);
593     shapeObject->setArray(ASCIILiteral("bounds"), buildArrayForQuad(shapeQuad));
594
595     Shape::DisplayPaths paths;
596     shapeOutsideInfo->computedShape().buildDisplayPaths(paths);
597
598     if (paths.shape.length()) {
599         RefPtr<InspectorArray> shapePath = InspectorArray::create();
600         PathApplyInfo info;
601         info.rootView = containingFrame->page()->mainFrame().view();
602         info.view = containingFrame->view();
603         info.array = shapePath.get();
604         info.renderer = renderer;
605         info.shapeOutsideInfo = shapeOutsideInfo;
606
607         paths.shape.apply(&info, &appendPathSegment);
608
609         shapeObject->setArray(ASCIILiteral("shape"), shapePath.release());
610
611         if (paths.marginShape.length()) {
612             shapePath = InspectorArray::create();
613             info.array = shapePath.get();
614
615             paths.marginShape.apply(&info, &appendPathSegment);
616
617             shapeObject->setArray(ASCIILiteral("marginShape"), shapePath.release());
618         }
619     }
620
621     return shapeObject.release();
622 }
623 #endif
624
625 static PassRefPtr<InspectorObject> buildObjectForElementInfo(Node* node)
626 {
627     if (!node->isElementNode() || !node->document().frame())
628         return nullptr;
629
630     RefPtr<InspectorObject> elementInfo = InspectorObject::create();
631
632     Element* element = toElement(node);
633     bool isXHTML = element->document().isXHTMLDocument();
634     elementInfo->setString("tagName", isXHTML ? element->nodeName() : element->nodeName().lower());
635     elementInfo->setString("idValue", element->getIdAttribute());
636     HashSet<AtomicString> usedClassNames;
637     if (element->hasClass() && element->isStyledElement()) {
638         StringBuilder classNames;
639         const SpaceSplitString& classNamesString = toStyledElement(element)->classNames();
640         size_t classNameCount = classNamesString.size();
641         for (size_t i = 0; i < classNameCount; ++i) {
642             const AtomicString& className = classNamesString[i];
643             if (usedClassNames.contains(className))
644                 continue;
645             usedClassNames.add(className);
646             classNames.append('.');
647             classNames.append(className);
648         }
649         elementInfo->setString("className", classNames.toString());
650     }
651
652     RenderElement* renderer = element->renderer();
653     Frame* containingFrame = node->document().frame();
654     FrameView* containingView = containingFrame->view();
655     IntRect boundingBox = pixelSnappedIntRect(containingView->contentsToRootView(renderer->absoluteBoundingBoxRect()));
656     RenderBoxModelObject* modelObject = renderer->isBoxModelObject() ? toRenderBoxModelObject(renderer) : nullptr;
657     elementInfo->setString("nodeWidth", String::number(modelObject ? adjustForAbsoluteZoom(modelObject->pixelSnappedOffsetWidth(), *modelObject) : boundingBox.width()));
658     elementInfo->setString("nodeHeight", String::number(modelObject ? adjustForAbsoluteZoom(modelObject->pixelSnappedOffsetHeight(), *modelObject) : boundingBox.height()));
659     
660     if (renderer->isRenderNamedFlowFragmentContainer()) {
661         RenderNamedFlowFragment* region = toRenderBlockFlow(renderer)->renderNamedFlowFragment();
662         RenderFlowThread* flowThread = region->flowThread();
663         if (flowThread && flowThread->isRenderNamedFlowThread()) {
664             RefPtr<InspectorObject> regionFlowInfo = InspectorObject::create();
665             regionFlowInfo->setString("name", toRenderNamedFlowThread(flowThread)->flowThreadName());
666             regionFlowInfo->setArray("regions", buildObjectForCSSRegionsHighlight(region, flowThread));
667             elementInfo->setObject("regionFlowInfo", regionFlowInfo.release());
668         }
669     }
670
671     RenderFlowThread* containingFlowThread = renderer->flowThreadContainingBlock();
672     if (containingFlowThread && containingFlowThread->isRenderNamedFlowThread()) {
673         RefPtr<InspectorObject> contentFlowInfo = InspectorObject::create();
674         contentFlowInfo->setString("name", toRenderNamedFlowThread(containingFlowThread)->flowThreadName());
675         elementInfo->setObject("contentFlowInfo", contentFlowInfo.release());
676     }
677
678 #if ENABLE(CSS_SHAPES)
679     if (renderer->isBox()) {
680         RenderBox* renderBox = toRenderBox(renderer);
681         if (RefPtr<InspectorObject> shapeObject = buildObjectForShapeOutside(containingFrame, renderBox))
682             elementInfo->setObject("shapeOutsideInfo", shapeObject.release());
683     }
684 #endif
685
686     return elementInfo.release();
687 }
688
689 PassRefPtr<InspectorObject> InspectorOverlay::buildObjectForHighlightedNode() const
690 {
691     if (!m_highlightNode)
692         return nullptr;
693
694     Node* node = m_highlightNode.get();
695     RenderObject* renderer = node->renderer();
696     if (!renderer)
697         return nullptr;
698
699     RefPtr<InspectorArray> highlightFragments = buildObjectForRendererFragments(renderer, m_nodeHighlightConfig);
700     if (!highlightFragments)
701         return nullptr;
702
703     RefPtr<InspectorObject> highlightObject = InspectorObject::create();
704
705     // The main view's scroll offset is shared across all quads.
706     FrameView* mainView = m_page.mainFrame().view();
707     highlightObject->setObject("scroll", buildObjectForPoint(!mainView->delegatesScrolling() ? mainView->visibleContentRect().location() : FloatPoint()));
708
709     highlightObject->setArray("fragments", highlightFragments.release());
710
711     if (m_nodeHighlightConfig.showInfo) {
712         RefPtr<InspectorObject> elementInfo = buildObjectForElementInfo(node);
713         if (elementInfo)
714             highlightObject->setObject("elementInfo", elementInfo.release());
715     }
716         
717     return highlightObject.release();
718 }
719
720 void InspectorOverlay::drawNodeHighlight()
721 {
722     RefPtr<InspectorObject> highlightObject = buildObjectForHighlightedNode();
723     if (!highlightObject)
724         return;
725     evaluateInOverlay("drawNodeHighlight", highlightObject);
726 }
727
728 void InspectorOverlay::drawQuadHighlight()
729 {
730     if (!m_highlightQuad)
731         return;
732
733     Highlight highlight;
734     buildQuadHighlight(*m_highlightQuad, m_quadHighlightConfig, &highlight);
735     evaluateInOverlay("drawQuadHighlight", buildObjectForHighlight(highlight));
736 }
737
738 void InspectorOverlay::drawPausedInDebuggerMessage()
739 {
740     if (!m_pausedInDebuggerMessage.isNull())
741         evaluateInOverlay("drawPausedInDebuggerMessage", m_pausedInDebuggerMessage);
742 }
743
744 Page* InspectorOverlay::overlayPage()
745 {
746     if (m_overlayPage)
747         return m_overlayPage.get();
748
749     Page::PageClients pageClients;
750     fillWithEmptyClients(pageClients);
751     m_overlayPage = adoptPtr(new Page(pageClients));
752
753     Settings& settings = m_page.settings();
754     Settings& overlaySettings = m_overlayPage->settings();
755
756     overlaySettings.setStandardFontFamily(settings.standardFontFamily());
757     overlaySettings.setSerifFontFamily(settings.serifFontFamily());
758     overlaySettings.setSansSerifFontFamily(settings.sansSerifFontFamily());
759     overlaySettings.setCursiveFontFamily(settings.cursiveFontFamily());
760     overlaySettings.setFantasyFontFamily(settings.fantasyFontFamily());
761     overlaySettings.setPictographFontFamily(settings.pictographFontFamily());
762     overlaySettings.setMinimumFontSize(settings.minimumFontSize());
763     overlaySettings.setMinimumLogicalFontSize(settings.minimumLogicalFontSize());
764     overlaySettings.setMediaEnabled(false);
765     overlaySettings.setScriptEnabled(true);
766     overlaySettings.setPluginsEnabled(false);
767
768     Frame& frame = m_overlayPage->mainFrame();
769     frame.setView(FrameView::create(frame));
770     frame.init();
771     FrameLoader& loader = frame.loader();
772     frame.view()->setCanHaveScrollbars(false);
773     frame.view()->setTransparent(true);
774     ASSERT(loader.activeDocumentLoader());
775     loader.activeDocumentLoader()->writer().setMIMEType("text/html");
776     loader.activeDocumentLoader()->writer().begin();
777     loader.activeDocumentLoader()->writer().addData(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
778     loader.activeDocumentLoader()->writer().end();
779
780 #if OS(WINDOWS)
781     evaluateInOverlay("setPlatform", "windows");
782 #elif OS(MAC_OS_X)
783     evaluateInOverlay("setPlatform", "mac");
784 #elif OS(UNIX)
785     evaluateInOverlay("setPlatform", "linux");
786 #endif
787
788     return m_overlayPage.get();
789 }
790
791 void InspectorOverlay::reset(const IntSize& viewportSize, const IntSize& frameViewFullSize)
792 {
793     RefPtr<InspectorObject> resetData = InspectorObject::create();
794     resetData->setNumber("deviceScaleFactor", m_page.deviceScaleFactor());
795     resetData->setObject("viewportSize", buildObjectForSize(viewportSize));
796     resetData->setObject("frameViewFullSize", buildObjectForSize(frameViewFullSize));
797     evaluateInOverlay("reset", resetData.release());
798 }
799
800 void InspectorOverlay::evaluateInOverlay(const String& method, const String& argument)
801 {
802     RefPtr<InspectorArray> command = InspectorArray::create();
803     command->pushString(method);
804     command->pushString(argument);
805     overlayPage()->mainFrame().script().evaluate(ScriptSourceCode(makeString("dispatch(", command->toJSONString(), ")")));
806 }
807
808 void InspectorOverlay::evaluateInOverlay(const String& method, PassRefPtr<InspectorValue> argument)
809 {
810     RefPtr<InspectorArray> command = InspectorArray::create();
811     command->pushString(method);
812     command->pushValue(argument);
813     overlayPage()->mainFrame().script().evaluate(ScriptSourceCode(makeString("dispatch(", command->toJSONString(), ")")));
814 }
815
816 void InspectorOverlay::freePage()
817 {
818     m_overlayPage.clear();
819 }
820
821 } // namespace WebCore
822
823 #endif // ENABLE(INSPECTOR)