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