[CSS Regions] Convert regions iterator loops to range-based loops
[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 (auto& iterRegion : regionList) {
438         if (!iterRegion->isValid())
439             continue;
440         RefPtr<InspectorObject> regionHighlightObject = buildObjectForRegionHighlight(mainFrameView, iterRegion);
441         if (!regionHighlightObject)
442             continue;
443         if (region == iterRegion) {
444             // Let the script know that this is the currently highlighted node.
445             regionHighlightObject->setBoolean("isHighlighted", true);
446         }
447         array->pushObject(regionHighlightObject.release());
448     }
449
450     return array.release();
451 }
452
453 static PassRefPtr<InspectorObject> buildObjectForSize(const IntSize& size)
454 {
455     RefPtr<InspectorObject> result = InspectorObject::create();
456     result->setNumber("width", size.width());
457     result->setNumber("height", size.height());
458     return result.release();
459 }
460
461 static PassRefPtr<InspectorObject> buildObjectForCSSRegionContentClip(RenderRegion* region)
462 {
463     Frame* containingFrame = region->document().frame();
464     if (!containingFrame)
465         return nullptr;
466
467     FrameView* containingView = containingFrame->view();
468     FrameView* mainView = containingFrame->page()->mainFrame().view();
469     RenderFlowThread* flowThread = region->flowThread();
470
471     // Get the clip box of the current region and covert it into an absolute quad.
472     LayoutRect flippedRegionRect(region->flowThreadPortionOverflowRect());
473     flowThread->flipForWritingMode(flippedRegionRect);
474
475     // Apply any border or padding of the region.
476     flippedRegionRect.setLocation(region->contentBoxRect().location());
477     
478     FloatQuad clipQuad = region->localToAbsoluteQuad(FloatRect(flippedRegionRect));
479     contentsQuadToPage(mainView, containingView, clipQuad);
480
481     RefPtr<InspectorObject> regionObject = InspectorObject::create();
482     regionObject->setArray("quad", buildArrayForQuad(clipQuad));
483     return regionObject.release();
484 }
485
486 void InspectorOverlay::drawGutter()
487 {
488     evaluateInOverlay("drawGutter", "");
489 }
490
491 static PassRefPtr<InspectorArray> buildObjectForRendererFragments(RenderObject* renderer, const HighlightConfig& config)
492 {
493     RefPtr<InspectorArray> fragmentsArray = InspectorArray::create();
494
495     RenderFlowThread* containingFlowThread = renderer->flowThreadContainingBlock();
496     if (!containingFlowThread) {
497         Highlight highlight;
498         buildRendererHighlight(renderer, nullptr, config, &highlight);
499         fragmentsArray->pushObject(buildObjectForHighlight(highlight));
500     } else {
501         RenderBox* enclosingBox = renderer->enclosingBox();
502         RenderRegion* startRegion = nullptr;
503         RenderRegion* endRegion = nullptr;
504         containingFlowThread->getRegionRangeForBox(enclosingBox, startRegion, endRegion);
505         if (!startRegion) {
506             // The flow has no visible regions. The renderer is not visible on screen.
507             return nullptr;
508         }
509         const RenderRegionList& regionList = containingFlowThread->renderRegionList();
510         for (RenderRegionList::const_iterator iter = regionList.find(startRegion); iter != regionList.end(); ++iter) {
511             RenderRegion* region = *iter;
512             if (region->isValid()) {
513                 // Compute the highlight of the fragment inside the current region.
514                 Highlight highlight;
515                 buildRendererHighlight(renderer, region, config, &highlight);
516                 RefPtr<InspectorObject> fragmentObject = buildObjectForHighlight(highlight);
517
518                 // Compute the clipping area of the region.
519                 fragmentObject->setObject("region", buildObjectForCSSRegionContentClip(region));
520                 fragmentsArray->pushObject(fragmentObject.release());
521             }
522             if (region == endRegion)
523                 break;
524         }
525     }
526
527     return fragmentsArray.release();
528 }
529
530 #if ENABLE(CSS_SHAPES)
531 static FloatPoint localPointToRoot(RenderObject* renderer, const FrameView* mainView, const FrameView* view, const FloatPoint& point)
532 {
533     FloatPoint result = renderer->localToAbsolute(point);
534     result = view->contentsToRootView(roundedIntPoint(result));
535     result += mainView->scrollOffset();
536     return result;
537 }
538
539 struct PathApplyInfo {
540     FrameView* rootView;
541     FrameView* view;
542     InspectorArray* array;
543     RenderObject* renderer;
544     const ShapeOutsideInfo* shapeOutsideInfo;
545 };
546
547 static void appendPathCommandAndPoints(PathApplyInfo* info, const String& command, const FloatPoint points[], unsigned length)
548 {
549     FloatPoint point;
550     info->array->pushString(command);
551     for (unsigned i = 0; i < length; i++) {
552         point = info->shapeOutsideInfo->shapeToRendererPoint(points[i]);
553         point = localPointToRoot(info->renderer, info->rootView, info->view, point);
554         info->array->pushNumber(point.x());
555         info->array->pushNumber(point.y());
556     }
557 }
558
559 static void appendPathSegment(void* info, const PathElement* pathElement)
560 {
561     PathApplyInfo* pathApplyInfo = static_cast<PathApplyInfo*>(info);
562     FloatPoint point;
563     switch (pathElement->type) {
564     // The points member will contain 1 value.
565     case PathElementMoveToPoint:
566         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("M"), pathElement->points, 1);
567         break;
568     // The points member will contain 1 value.
569     case PathElementAddLineToPoint:
570         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("L"), pathElement->points, 1);
571         break;
572     // The points member will contain 3 values.
573     case PathElementAddCurveToPoint:
574         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("C"), pathElement->points, 3);
575         break;
576     // The points member will contain 2 values.
577     case PathElementAddQuadCurveToPoint:
578         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("Q"), pathElement->points, 2);
579         break;
580     // The points member will contain no values.
581     case PathElementCloseSubpath:
582         appendPathCommandAndPoints(pathApplyInfo, ASCIILiteral("Z"), nullptr, 0);
583         break;
584     }
585 }
586
587 static PassRefPtr<InspectorObject> buildObjectForShapeOutside(Frame* containingFrame, RenderBox* renderer)
588 {
589     const ShapeOutsideInfo* shapeOutsideInfo = renderer->shapeOutsideInfo();
590     if (!shapeOutsideInfo)
591         return nullptr;
592
593     RefPtr<InspectorObject> shapeObject = InspectorObject::create();
594     LayoutRect shapeBounds = shapeOutsideInfo->computedShapePhysicalBoundingBox();
595     FloatQuad shapeQuad = renderer->localToAbsoluteQuad(FloatRect(shapeBounds));
596     contentsQuadToPage(containingFrame->page()->mainFrame().view(), containingFrame->view(), shapeQuad);
597     shapeObject->setArray(ASCIILiteral("bounds"), buildArrayForQuad(shapeQuad));
598
599     Shape::DisplayPaths paths;
600     shapeOutsideInfo->computedShape().buildDisplayPaths(paths);
601
602     if (paths.shape.length()) {
603         RefPtr<InspectorArray> shapePath = InspectorArray::create();
604         PathApplyInfo info;
605         info.rootView = containingFrame->page()->mainFrame().view();
606         info.view = containingFrame->view();
607         info.array = shapePath.get();
608         info.renderer = renderer;
609         info.shapeOutsideInfo = shapeOutsideInfo;
610
611         paths.shape.apply(&info, &appendPathSegment);
612
613         shapeObject->setArray(ASCIILiteral("shape"), shapePath.release());
614
615         if (paths.marginShape.length()) {
616             shapePath = InspectorArray::create();
617             info.array = shapePath.get();
618
619             paths.marginShape.apply(&info, &appendPathSegment);
620
621             shapeObject->setArray(ASCIILiteral("marginShape"), shapePath.release());
622         }
623     }
624
625     return shapeObject.release();
626 }
627 #endif
628
629 static PassRefPtr<InspectorObject> buildObjectForElementInfo(Node* node)
630 {
631     if (!node->isElementNode() || !node->document().frame())
632         return nullptr;
633
634     RefPtr<InspectorObject> elementInfo = InspectorObject::create();
635
636     Element* element = toElement(node);
637     bool isXHTML = element->document().isXHTMLDocument();
638     elementInfo->setString("tagName", isXHTML ? element->nodeName() : element->nodeName().lower());
639     elementInfo->setString("idValue", element->getIdAttribute());
640     HashSet<AtomicString> usedClassNames;
641     if (element->hasClass() && element->isStyledElement()) {
642         StringBuilder classNames;
643         const SpaceSplitString& classNamesString = toStyledElement(element)->classNames();
644         size_t classNameCount = classNamesString.size();
645         for (size_t i = 0; i < classNameCount; ++i) {
646             const AtomicString& className = classNamesString[i];
647             if (usedClassNames.contains(className))
648                 continue;
649             usedClassNames.add(className);
650             classNames.append('.');
651             classNames.append(className);
652         }
653         elementInfo->setString("className", classNames.toString());
654     }
655
656     RenderElement* renderer = element->renderer();
657     Frame* containingFrame = node->document().frame();
658     FrameView* containingView = containingFrame->view();
659     IntRect boundingBox = pixelSnappedIntRect(containingView->contentsToRootView(renderer->absoluteBoundingBoxRect()));
660     RenderBoxModelObject* modelObject = renderer->isBoxModelObject() ? toRenderBoxModelObject(renderer) : nullptr;
661     elementInfo->setString("nodeWidth", String::number(modelObject ? adjustForAbsoluteZoom(modelObject->pixelSnappedOffsetWidth(), *modelObject) : boundingBox.width()));
662     elementInfo->setString("nodeHeight", String::number(modelObject ? adjustForAbsoluteZoom(modelObject->pixelSnappedOffsetHeight(), *modelObject) : boundingBox.height()));
663     
664     if (renderer->isRenderNamedFlowFragmentContainer()) {
665         RenderNamedFlowFragment* region = toRenderBlockFlow(renderer)->renderNamedFlowFragment();
666         RenderFlowThread* flowThread = region->flowThread();
667         if (flowThread && flowThread->isRenderNamedFlowThread()) {
668             RefPtr<InspectorObject> regionFlowInfo = InspectorObject::create();
669             regionFlowInfo->setString("name", toRenderNamedFlowThread(flowThread)->flowThreadName());
670             regionFlowInfo->setArray("regions", buildObjectForCSSRegionsHighlight(region, flowThread));
671             elementInfo->setObject("regionFlowInfo", regionFlowInfo.release());
672         }
673     }
674
675     RenderFlowThread* containingFlowThread = renderer->flowThreadContainingBlock();
676     if (containingFlowThread && containingFlowThread->isRenderNamedFlowThread()) {
677         RefPtr<InspectorObject> contentFlowInfo = InspectorObject::create();
678         contentFlowInfo->setString("name", toRenderNamedFlowThread(containingFlowThread)->flowThreadName());
679         elementInfo->setObject("contentFlowInfo", contentFlowInfo.release());
680     }
681
682 #if ENABLE(CSS_SHAPES)
683     if (renderer->isBox()) {
684         RenderBox* renderBox = toRenderBox(renderer);
685         if (RefPtr<InspectorObject> shapeObject = buildObjectForShapeOutside(containingFrame, renderBox))
686             elementInfo->setObject("shapeOutsideInfo", shapeObject.release());
687     }
688 #endif
689
690     return elementInfo.release();
691 }
692
693 PassRefPtr<InspectorObject> InspectorOverlay::buildObjectForHighlightedNode() const
694 {
695     if (!m_highlightNode)
696         return nullptr;
697
698     Node* node = m_highlightNode.get();
699     RenderObject* renderer = node->renderer();
700     if (!renderer)
701         return nullptr;
702
703     RefPtr<InspectorArray> highlightFragments = buildObjectForRendererFragments(renderer, m_nodeHighlightConfig);
704     if (!highlightFragments)
705         return nullptr;
706
707     RefPtr<InspectorObject> highlightObject = InspectorObject::create();
708
709     // The main view's scroll offset is shared across all quads.
710     FrameView* mainView = m_page.mainFrame().view();
711     highlightObject->setObject("scroll", buildObjectForPoint(!mainView->delegatesScrolling() ? mainView->visibleContentRect().location() : FloatPoint()));
712
713     highlightObject->setArray("fragments", highlightFragments.release());
714
715     if (m_nodeHighlightConfig.showInfo) {
716         RefPtr<InspectorObject> elementInfo = buildObjectForElementInfo(node);
717         if (elementInfo)
718             highlightObject->setObject("elementInfo", elementInfo.release());
719     }
720         
721     return highlightObject.release();
722 }
723
724 void InspectorOverlay::drawNodeHighlight()
725 {
726     RefPtr<InspectorObject> highlightObject = buildObjectForHighlightedNode();
727     if (!highlightObject)
728         return;
729     evaluateInOverlay("drawNodeHighlight", highlightObject);
730 }
731
732 void InspectorOverlay::drawQuadHighlight()
733 {
734     if (!m_highlightQuad)
735         return;
736
737     Highlight highlight;
738     buildQuadHighlight(*m_highlightQuad, m_quadHighlightConfig, &highlight);
739     evaluateInOverlay("drawQuadHighlight", buildObjectForHighlight(highlight));
740 }
741
742 void InspectorOverlay::drawPausedInDebuggerMessage()
743 {
744     if (!m_pausedInDebuggerMessage.isNull())
745         evaluateInOverlay("drawPausedInDebuggerMessage", m_pausedInDebuggerMessage);
746 }
747
748 Page* InspectorOverlay::overlayPage()
749 {
750     if (m_overlayPage)
751         return m_overlayPage.get();
752
753     Page::PageClients pageClients;
754     fillWithEmptyClients(pageClients);
755     m_overlayPage = adoptPtr(new Page(pageClients));
756
757     Settings& settings = m_page.settings();
758     Settings& overlaySettings = m_overlayPage->settings();
759
760     overlaySettings.setStandardFontFamily(settings.standardFontFamily());
761     overlaySettings.setSerifFontFamily(settings.serifFontFamily());
762     overlaySettings.setSansSerifFontFamily(settings.sansSerifFontFamily());
763     overlaySettings.setCursiveFontFamily(settings.cursiveFontFamily());
764     overlaySettings.setFantasyFontFamily(settings.fantasyFontFamily());
765     overlaySettings.setPictographFontFamily(settings.pictographFontFamily());
766     overlaySettings.setMinimumFontSize(settings.minimumFontSize());
767     overlaySettings.setMinimumLogicalFontSize(settings.minimumLogicalFontSize());
768     overlaySettings.setMediaEnabled(false);
769     overlaySettings.setScriptEnabled(true);
770     overlaySettings.setPluginsEnabled(false);
771
772     Frame& frame = m_overlayPage->mainFrame();
773     frame.setView(FrameView::create(frame));
774     frame.init();
775     FrameLoader& loader = frame.loader();
776     frame.view()->setCanHaveScrollbars(false);
777     frame.view()->setTransparent(true);
778     ASSERT(loader.activeDocumentLoader());
779     loader.activeDocumentLoader()->writer().setMIMEType("text/html");
780     loader.activeDocumentLoader()->writer().begin();
781     loader.activeDocumentLoader()->writer().addData(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
782     loader.activeDocumentLoader()->writer().end();
783
784 #if OS(WINDOWS)
785     evaluateInOverlay("setPlatform", "windows");
786 #elif OS(MAC_OS_X)
787     evaluateInOverlay("setPlatform", "mac");
788 #elif OS(UNIX)
789     evaluateInOverlay("setPlatform", "linux");
790 #endif
791
792     return m_overlayPage.get();
793 }
794
795 void InspectorOverlay::reset(const IntSize& viewportSize, const IntSize& frameViewFullSize)
796 {
797     RefPtr<InspectorObject> resetData = InspectorObject::create();
798     resetData->setNumber("deviceScaleFactor", m_page.deviceScaleFactor());
799     resetData->setObject("viewportSize", buildObjectForSize(viewportSize));
800     resetData->setObject("frameViewFullSize", buildObjectForSize(frameViewFullSize));
801     evaluateInOverlay("reset", resetData.release());
802 }
803
804 void InspectorOverlay::evaluateInOverlay(const String& method, const String& argument)
805 {
806     RefPtr<InspectorArray> command = InspectorArray::create();
807     command->pushString(method);
808     command->pushString(argument);
809     overlayPage()->mainFrame().script().evaluate(ScriptSourceCode(makeString("dispatch(", command->toJSONString(), ")")));
810 }
811
812 void InspectorOverlay::evaluateInOverlay(const String& method, PassRefPtr<InspectorValue> argument)
813 {
814     RefPtr<InspectorArray> command = InspectorArray::create();
815     command->pushString(method);
816     command->pushValue(argument);
817     overlayPage()->mainFrame().script().evaluate(ScriptSourceCode(makeString("dispatch(", command->toJSONString(), ")")));
818 }
819
820 void InspectorOverlay::freePage()
821 {
822     m_overlayPage.clear();
823 }
824
825 } // namespace WebCore
826
827 #endif // ENABLE(INSPECTOR)