Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / RenderView.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public License
16  * along with this library; see the file COPYING.LIB.  If not, write to
17  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #include "config.h"
22 #include "core/rendering/RenderView.h"
23
24 #include "RuntimeEnabledFeatures.h"
25 #include "core/dom/Document.h"
26 #include "core/dom/Element.h"
27 #include "core/frame/LocalFrame.h"
28 #include "core/html/HTMLDialogElement.h"
29 #include "core/html/HTMLFrameOwnerElement.h"
30 #include "core/html/HTMLIFrameElement.h"
31 #include "core/page/Page.h"
32 #include "core/rendering/ColumnInfo.h"
33 #include "core/rendering/FlowThreadController.h"
34 #include "core/rendering/GraphicsContextAnnotator.h"
35 #include "core/rendering/HitTestResult.h"
36 #include "core/rendering/RenderFlowThread.h"
37 #include "core/rendering/RenderGeometryMap.h"
38 #include "core/rendering/RenderLayer.h"
39 #include "core/rendering/RenderSelectionInfo.h"
40 #include "core/rendering/compositing/CompositedLayerMapping.h"
41 #include "core/rendering/compositing/RenderLayerCompositor.h"
42 #include "core/svg/SVGDocumentExtensions.h"
43 #include "platform/geometry/FloatQuad.h"
44 #include "platform/geometry/TransformState.h"
45 #include "platform/graphics/GraphicsContext.h"
46
47 namespace WebCore {
48
49 RenderView::RenderView(Document* document)
50     : RenderBlockFlow(document)
51     , m_frameView(document->view())
52     , m_selectionStart(0)
53     , m_selectionEnd(0)
54     , m_selectionStartPos(-1)
55     , m_selectionEndPos(-1)
56     , m_pageLogicalHeight(0)
57     , m_pageLogicalHeightChanged(false)
58     , m_layoutState(0)
59     , m_layoutStateDisableCount(0)
60     , m_renderQuoteHead(0)
61     , m_renderCounterCount(0)
62 {
63     // init RenderObject attributes
64     setInline(false);
65
66     m_minPreferredLogicalWidth = 0;
67     m_maxPreferredLogicalWidth = 0;
68
69     setPreferredLogicalWidthsDirty(MarkOnlyThis);
70
71     setPositionState(AbsolutePosition); // to 0,0 :)
72 }
73
74 RenderView::~RenderView()
75 {
76 }
77
78 bool RenderView::hitTest(const HitTestRequest& request, HitTestResult& result)
79 {
80     return hitTest(request, result.hitTestLocation(), result);
81 }
82
83 bool RenderView::hitTest(const HitTestRequest& request, const HitTestLocation& location, HitTestResult& result)
84 {
85     // We have to recursively update layout/style here because otherwise, when the hit test recurses
86     // into a child document, it could trigger a layout on the parent document, which can destroy RenderLayers
87     // that are higher up in the call stack, leading to crashes.
88     // Note that Document::updateLayout calls its parent's updateLayout.
89     // FIXME: It should be the caller's responsibility to ensure an up-to-date layout.
90     frameView()->updateLayoutAndStyleIfNeededRecursive();
91     return layer()->hitTest(request, location, result);
92 }
93
94 void RenderView::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit, LogicalExtentComputedValues& computedValues) const
95 {
96     computedValues.m_extent = (!shouldUsePrintingLayout() && m_frameView) ? LayoutUnit(viewLogicalHeight()) : logicalHeight;
97 }
98
99 void RenderView::updateLogicalWidth()
100 {
101     if (!shouldUsePrintingLayout() && m_frameView)
102         setLogicalWidth(viewLogicalWidth());
103 }
104
105 LayoutUnit RenderView::availableLogicalHeight(AvailableLogicalHeightType heightType) const
106 {
107     // If we have columns, then the available logical height is reduced to the column height.
108     if (hasColumns())
109         return columnInfo()->columnHeight();
110     return RenderBlockFlow::availableLogicalHeight(heightType);
111 }
112
113 bool RenderView::isChildAllowed(RenderObject* child, RenderStyle*) const
114 {
115     return child->isBox();
116 }
117
118 static bool canCenterDialog(const RenderStyle* style)
119 {
120     // FIXME: We must center for FixedPosition as well.
121     return style->position() == AbsolutePosition && style->hasAutoTopAndBottom();
122 }
123
124 void RenderView::positionDialog(RenderBox* box)
125 {
126     HTMLDialogElement* dialog = toHTMLDialogElement(box->node());
127     if (dialog->centeringMode() == HTMLDialogElement::NotCentered)
128         return;
129     if (dialog->centeringMode() == HTMLDialogElement::Centered) {
130         if (canCenterDialog(box->style()))
131             box->setY(dialog->centeredPosition());
132         return;
133     }
134
135     ASSERT(dialog->centeringMode() == HTMLDialogElement::NeedsCentering);
136     if (!canCenterDialog(box->style())) {
137         dialog->setNotCentered();
138         return;
139     }
140     FrameView* frameView = document().view();
141     int scrollTop = frameView->scrollOffset().height();
142     int visibleHeight = frameView->visibleContentRect(IncludeScrollbars).height();
143     LayoutUnit top = scrollTop;
144     if (box->height() < visibleHeight)
145         top += (visibleHeight - box->height()) / 2;
146     box->setY(top);
147     dialog->setCentered(top);
148 }
149
150 void RenderView::positionDialogs()
151 {
152     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
153     if (!positionedDescendants)
154         return;
155     TrackedRendererListHashSet::iterator end = positionedDescendants->end();
156     for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
157         RenderBox* box = *it;
158         if (isHTMLDialogElement(box->node()))
159             positionDialog(box);
160     }
161 }
162
163 void RenderView::layoutContent()
164 {
165     ASSERT(needsLayout());
166
167     RenderBlockFlow::layout();
168
169     if (RuntimeEnabledFeatures::dialogElementEnabled())
170         positionDialogs();
171
172 #ifndef NDEBUG
173     checkLayoutState();
174 #endif
175 }
176
177 #ifndef NDEBUG
178 void RenderView::checkLayoutState()
179 {
180     if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
181         ASSERT(layoutDeltaMatches(LayoutSize()));
182     }
183     ASSERT(!m_layoutStateDisableCount);
184     ASSERT(!m_layoutState->next());
185 }
186 #endif
187
188 void RenderView::layout()
189 {
190     if (!document().paginated())
191         setPageLogicalHeight(0);
192
193     if (shouldUsePrintingLayout())
194         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = logicalWidth();
195
196     SubtreeLayoutScope layoutScope(*this);
197
198     // Use calcWidth/Height to get the new width/height, since this will take the full page zoom factor into account.
199     bool relayoutChildren = !shouldUsePrintingLayout() && (!m_frameView || width() != viewWidth() || height() != viewHeight());
200     if (relayoutChildren) {
201         layoutScope.setChildNeedsLayout(this);
202         for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
203             if (child->isSVGRoot())
204                 continue;
205
206             if ((child->isBox() && toRenderBox(child)->hasRelativeLogicalHeight())
207                     || child->style()->logicalHeight().isPercent()
208                     || child->style()->logicalMinHeight().isPercent()
209                     || child->style()->logicalMaxHeight().isPercent())
210                 layoutScope.setChildNeedsLayout(child);
211         }
212
213         if (document().svgExtensions())
214             document().accessSVGExtensions().invalidateSVGRootsWithRelativeLengthDescendents(&layoutScope);
215     }
216
217     ASSERT(!m_layoutState);
218     if (!needsLayout())
219         return;
220
221     RootLayoutStateScope rootLayoutStateScope(*this);
222
223     m_pageLogicalHeightChanged = false;
224
225     layoutContent();
226
227 #ifndef NDEBUG
228     checkLayoutState();
229 #endif
230     clearNeedsLayout();
231 }
232
233 void RenderView::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
234 {
235     ASSERT_UNUSED(wasFixed, !wasFixed || *wasFixed == static_cast<bool>(mode & IsFixed));
236
237     if (!repaintContainer && mode & UseTransforms && shouldUseTransformFromContainer(0)) {
238         TransformationMatrix t;
239         getTransformFromContainer(0, LayoutSize(), t);
240         transformState.applyTransform(t);
241     }
242
243     if (mode & IsFixed && m_frameView)
244         transformState.move(m_frameView->scrollOffsetForFixedPosition());
245
246     if (repaintContainer == this)
247         return;
248
249     if (mode & TraverseDocumentBoundaries) {
250         if (RenderObject* parentDocRenderer = frame()->ownerRenderer()) {
251             transformState.move(-frame()->view()->scrollOffset());
252             if (parentDocRenderer->isBox())
253                 transformState.move(toLayoutSize(toRenderBox(parentDocRenderer)->contentBoxRect().location()));
254             parentDocRenderer->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
255             return;
256         }
257     }
258
259     // If a container was specified, and was not 0 or the RenderView,
260     // then we should have found it by now.
261     ASSERT_ARG(repaintContainer, !repaintContainer);
262 }
263
264 const RenderObject* RenderView::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
265 {
266     LayoutSize offsetForFixedPosition;
267     LayoutSize offset;
268     RenderObject* container = 0;
269
270     if (m_frameView)
271         offsetForFixedPosition = m_frameView->scrollOffsetForFixedPosition();
272
273     if (geometryMap.mapCoordinatesFlags() & TraverseDocumentBoundaries) {
274         if (RenderPart* parentDocRenderer = frame()->ownerRenderer()) {
275             offset = -m_frameView->scrollOffset();
276             offset += toLayoutSize(parentDocRenderer->contentBoxRect().location());
277             container = parentDocRenderer;
278         }
279     }
280
281     // If a container was specified, and was not 0 or the RenderView, then we
282     // should have found it by now unless we're traversing to a parent document.
283     ASSERT_ARG(ancestorToStopAt, !ancestorToStopAt || ancestorToStopAt == this || container);
284
285     if ((!ancestorToStopAt || container) && shouldUseTransformFromContainer(container)) {
286         TransformationMatrix t;
287         getTransformFromContainer(container, LayoutSize(), t);
288         geometryMap.push(this, t, false, false, false, true, offsetForFixedPosition);
289     } else {
290         geometryMap.push(this, offset, false, false, false, false, offsetForFixedPosition);
291     }
292
293     return container;
294 }
295
296 void RenderView::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
297 {
298     if (mode & IsFixed && m_frameView)
299         transformState.move(m_frameView->scrollOffsetForFixedPosition());
300
301     if (mode & UseTransforms && shouldUseTransformFromContainer(0)) {
302         TransformationMatrix t;
303         getTransformFromContainer(0, LayoutSize(), t);
304         transformState.applyTransform(t);
305     }
306 }
307
308 void RenderView::computeSelfHitTestRects(Vector<LayoutRect>& rects, const LayoutPoint&) const
309 {
310     // Record the entire size of the contents of the frame. Note that we don't just
311     // use the viewport size (containing block) here because we want to ensure this includes
312     // all children (so we can avoid walking them explicitly).
313     rects.append(LayoutRect(LayoutPoint::zero(), frameView()->contentsSize()));
314 }
315
316 void RenderView::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
317 {
318     // If we ever require layout but receive a paint anyway, something has gone horribly wrong.
319     ASSERT(!needsLayout());
320     // RenderViews should never be called to paint with an offset not on device pixels.
321     ASSERT(LayoutPoint(IntPoint(paintOffset.x(), paintOffset.y())) == paintOffset);
322
323     ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
324
325     // This avoids painting garbage between columns if there is a column gap.
326     if (m_frameView && style()->isOverflowPaged())
327         paintInfo.context->fillRect(paintInfo.rect, m_frameView->baseBackgroundColor());
328
329     paintObject(paintInfo, paintOffset);
330 }
331
332 static inline bool rendererObscuresBackground(RenderBox* rootBox)
333 {
334     ASSERT(rootBox);
335     RenderStyle* style = rootBox->style();
336     if (style->visibility() != VISIBLE
337         || style->opacity() != 1
338         || style->hasFilter()
339         || style->hasTransform())
340         return false;
341
342     if (rootBox->compositingState() == PaintsIntoOwnBacking)
343         return false;
344
345     const RenderObject* rootRenderer = rootBox->rendererForRootBackground();
346     if (rootRenderer->style()->backgroundClip() == TextFillBox)
347         return false;
348
349     return true;
350 }
351
352 bool RenderView::rootFillsViewportBackground(RenderBox* rootBox) const
353 {
354     ASSERT(rootBox);
355     // CSS Boxes always fill the viewport background (see paintRootBoxFillLayers)
356     if (!rootBox->isSVG())
357         return true;
358
359     return rootBox->frameRect().contains(frameRect());
360 }
361
362 void RenderView::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint&)
363 {
364     // Check to see if we are enclosed by a layer that requires complex painting rules.  If so, we cannot blit
365     // when scrolling, and we need to use slow repaints.  Examples of layers that require this are transparent layers,
366     // layers with reflections, or transformed layers.
367     // FIXME: This needs to be dynamic.  We should be able to go back to blitting if we ever stop being inside
368     // a transform, transparency layer, etc.
369     Element* elt;
370     for (elt = document().ownerElement(); view() && elt && elt->renderer(); elt = elt->document().ownerElement()) {
371         RenderLayer* layer = elt->renderer()->enclosingLayer();
372         if (layer->cannotBlitToWindow()) {
373             frameView()->setCannotBlitToWindow();
374             break;
375         }
376
377         if (layer->enclosingCompositingLayerForRepaint()) {
378             frameView()->setCannotBlitToWindow();
379             break;
380         }
381     }
382
383     if (document().ownerElement() || !view())
384         return;
385
386     if (paintInfo.skipRootBackground())
387         return;
388
389     bool shouldPaintBackground = true;
390     Node* documentElement = document().documentElement();
391     if (RenderBox* rootBox = documentElement ? toRenderBox(documentElement->renderer()) : 0)
392         shouldPaintBackground = !rootFillsViewportBackground(rootBox) || !rendererObscuresBackground(rootBox);
393
394     // If painting will entirely fill the view, no need to fill the background.
395     if (!shouldPaintBackground)
396         return;
397
398     // This code typically only executes if the root element's visibility has been set to hidden,
399     // if there is a transform on the <html>, or if there is a page scale factor less than 1.
400     // Only fill with the base background color (typically white) if we're the root document,
401     // since iframes/frames with no background in the child document should show the parent's background.
402     if (frameView()->isTransparent()) // FIXME: This needs to be dynamic.  We should be able to go back to blitting if we ever stop being transparent.
403         frameView()->setCannotBlitToWindow(); // The parent must show behind the child.
404     else {
405         Color baseColor = frameView()->baseBackgroundColor();
406         if (baseColor.alpha()) {
407             CompositeOperator previousOperator = paintInfo.context->compositeOperation();
408             paintInfo.context->setCompositeOperation(CompositeCopy);
409             paintInfo.context->fillRect(paintInfo.rect, baseColor);
410             paintInfo.context->setCompositeOperation(previousOperator);
411         } else {
412             paintInfo.context->clearRect(paintInfo.rect);
413         }
414     }
415 }
416
417 void RenderView::repaintViewRectangle(const LayoutRect& ur) const
418 {
419     ASSERT(!ur.isEmpty());
420
421     if (document().printing() || !m_frameView)
422         return;
423
424     // We always just invalidate the root view, since we could be an iframe that is clipped out
425     // or even invisible.
426     Element* elt = document().ownerElement();
427     if (!elt)
428         m_frameView->repaintContentRectangle(pixelSnappedIntRect(ur));
429     else if (RenderBox* obj = elt->renderBox()) {
430         LayoutRect vr = viewRect();
431         LayoutRect r = intersection(ur, vr);
432
433         // Subtract out the contentsX and contentsY offsets to get our coords within the viewing
434         // rectangle.
435         r.moveBy(-vr.location());
436
437         // FIXME: Hardcoded offsets here are not good.
438         r.moveBy(obj->contentBoxRect().location());
439         obj->repaintRectangle(r);
440     }
441 }
442
443 void RenderView::repaintViewAndCompositedLayers()
444 {
445     repaint();
446
447     // The only way we know how to hit these ASSERTS below this point is via the Chromium OS login screen.
448     DisableCompositingQueryAsserts disabler;
449
450     if (compositor()->inCompositingMode())
451         compositor()->repaintCompositedLayers();
452 }
453
454 void RenderView::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
455 {
456     // If a container was specified, and was not 0 or the RenderView,
457     // then we should have found it by now.
458     ASSERT_ARG(repaintContainer, !repaintContainer || repaintContainer == this);
459
460     if (document().printing())
461         return;
462
463     if (style()->isFlippedBlocksWritingMode()) {
464         // We have to flip by hand since the view's logical height has not been determined.  We
465         // can use the viewport width and height.
466         if (style()->isHorizontalWritingMode())
467             rect.setY(viewHeight() - rect.maxY());
468         else
469             rect.setX(viewWidth() - rect.maxX());
470     }
471
472     if (fixed && m_frameView) {
473         rect.move(m_frameView->scrollOffsetForFixedPosition());
474         // If we have a pending scroll, invalidate the previous scroll position.
475         if (!m_frameView->pendingScrollDelta().isZero()) {
476             rect.move(-m_frameView->pendingScrollDelta());
477         }
478     }
479
480     // Apply our transform if we have one (because of full page zooming).
481     if (!repaintContainer && layer() && layer()->transform())
482         rect = layer()->transform()->mapRect(rect);
483 }
484
485 void RenderView::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
486 {
487     rects.append(pixelSnappedIntRect(accumulatedOffset, layer()->size()));
488 }
489
490 void RenderView::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
491 {
492     if (wasFixed)
493         *wasFixed = false;
494     quads.append(FloatRect(FloatPoint(), layer()->size()));
495 }
496
497 static RenderObject* rendererAfterPosition(RenderObject* object, unsigned offset)
498 {
499     if (!object)
500         return 0;
501
502     RenderObject* child = object->childAt(offset);
503     return child ? child : object->nextInPreOrderAfterChildren();
504 }
505
506 IntRect RenderView::selectionBounds(bool clipToVisibleContent) const
507 {
508     typedef HashMap<RenderObject*, OwnPtr<RenderSelectionInfo> > SelectionMap;
509     SelectionMap selectedObjects;
510
511     RenderObject* os = m_selectionStart;
512     RenderObject* stop = rendererAfterPosition(m_selectionEnd, m_selectionEndPos);
513     while (os && os != stop) {
514         if ((os->canBeSelectionLeaf() || os == m_selectionStart || os == m_selectionEnd) && os->selectionState() != SelectionNone) {
515             // Blocks are responsible for painting line gaps and margin gaps. They must be examined as well.
516             selectedObjects.set(os, adoptPtr(new RenderSelectionInfo(os, clipToVisibleContent)));
517             RenderBlock* cb = os->containingBlock();
518             while (cb && !cb->isRenderView()) {
519                 OwnPtr<RenderSelectionInfo>& blockInfo = selectedObjects.add(cb, nullptr).storedValue->value;
520                 if (blockInfo)
521                     break;
522                 blockInfo = adoptPtr(new RenderSelectionInfo(cb, clipToVisibleContent));
523                 cb = cb->containingBlock();
524             }
525         }
526
527         os = os->nextInPreOrder();
528     }
529
530     // Now create a single bounding box rect that encloses the whole selection.
531     LayoutRect selRect;
532     SelectionMap::iterator end = selectedObjects.end();
533     for (SelectionMap::iterator i = selectedObjects.begin(); i != end; ++i) {
534         RenderSelectionInfo* info = i->value.get();
535         // RenderSelectionInfo::rect() is in the coordinates of the repaintContainer, so map to page coordinates.
536         LayoutRect currRect = info->rect();
537         if (const RenderLayerModelObject* repaintContainer = info->repaintContainer()) {
538             FloatQuad absQuad = repaintContainer->localToAbsoluteQuad(FloatRect(currRect));
539             currRect = absQuad.enclosingBoundingBox();
540         }
541         selRect.unite(currRect);
542     }
543     return pixelSnappedIntRect(selRect);
544 }
545
546 void RenderView::repaintSelection() const
547 {
548     HashSet<RenderBlock*> processedBlocks;
549
550     RenderObject* end = rendererAfterPosition(m_selectionEnd, m_selectionEndPos);
551     for (RenderObject* o = m_selectionStart; o && o != end; o = o->nextInPreOrder()) {
552         if (!o->canBeSelectionLeaf() && o != m_selectionStart && o != m_selectionEnd)
553             continue;
554         if (o->selectionState() == SelectionNone)
555             continue;
556
557         RenderSelectionInfo(o, true).repaint();
558
559         // Blocks are responsible for painting line gaps and margin gaps. They must be examined as well.
560         for (RenderBlock* block = o->containingBlock(); block && !block->isRenderView(); block = block->containingBlock()) {
561             if (!processedBlocks.add(block).isNewEntry)
562                 break;
563             RenderSelectionInfo(block, true).repaint();
564         }
565     }
566 }
567
568 // When exploring the RenderTree looking for the nodes involved in the Selection, sometimes it's
569 // required to change the traversing direction because the "start" position is below the "end" one.
570 static inline RenderObject* getNextOrPrevRenderObjectBasedOnDirection(const RenderObject* o, const RenderObject* stop, bool& continueExploring, bool& exploringBackwards)
571 {
572     RenderObject* next;
573     if (exploringBackwards) {
574         next = o->previousInPreOrder();
575         continueExploring = next && !(next)->isRenderView();
576     } else {
577         next = o->nextInPreOrder();
578         continueExploring = next && next != stop;
579         exploringBackwards = !next && (next != stop);
580         if (exploringBackwards) {
581             next = stop->previousInPreOrder();
582             continueExploring = next && !next->isRenderView();
583         }
584     }
585
586     return next;
587 }
588
589 void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* end, int endPos, SelectionRepaintMode blockRepaintMode)
590 {
591     // This code makes no assumptions as to if the rendering tree is up to date or not
592     // and will not try to update it. Currently clearSelection calls this
593     // (intentionally) without updating the rendering tree as it doesn't care.
594     // Other callers may want to force recalc style before calling this.
595
596     // Make sure both our start and end objects are defined.
597     // Check www.msnbc.com and try clicking around to find the case where this happened.
598     if ((start && !end) || (end && !start))
599         return;
600
601     // Just return if the selection hasn't changed.
602     if (m_selectionStart == start && m_selectionStartPos == startPos &&
603         m_selectionEnd == end && m_selectionEndPos == endPos)
604         return;
605
606     // Record the old selected objects.  These will be used later
607     // when we compare against the new selected objects.
608     int oldStartPos = m_selectionStartPos;
609     int oldEndPos = m_selectionEndPos;
610
611     // Objects each have a single selection rect to examine.
612     typedef HashMap<RenderObject*, OwnPtr<RenderSelectionInfo> > SelectedObjectMap;
613     SelectedObjectMap oldSelectedObjects;
614     SelectedObjectMap newSelectedObjects;
615
616     // Blocks contain selected objects and fill gaps between them, either on the left, right, or in between lines and blocks.
617     // In order to get the repaint rect right, we have to examine left, middle, and right rects individually, since otherwise
618     // the union of those rects might remain the same even when changes have occurred.
619     typedef HashMap<RenderBlock*, OwnPtr<RenderBlockSelectionInfo> > SelectedBlockMap;
620     SelectedBlockMap oldSelectedBlocks;
621     SelectedBlockMap newSelectedBlocks;
622
623     RenderObject* os = m_selectionStart;
624     RenderObject* stop = rendererAfterPosition(m_selectionEnd, m_selectionEndPos);
625     bool exploringBackwards = false;
626     bool continueExploring = os && (os != stop);
627     while (continueExploring) {
628         if ((os->canBeSelectionLeaf() || os == m_selectionStart || os == m_selectionEnd) && os->selectionState() != SelectionNone) {
629             // Blocks are responsible for painting line gaps and margin gaps.  They must be examined as well.
630             oldSelectedObjects.set(os, adoptPtr(new RenderSelectionInfo(os, true)));
631             if (blockRepaintMode == RepaintNewXOROld) {
632                 RenderBlock* cb = os->containingBlock();
633                 while (cb && !cb->isRenderView()) {
634                     OwnPtr<RenderBlockSelectionInfo>& blockInfo = oldSelectedBlocks.add(cb, nullptr).storedValue->value;
635                     if (blockInfo)
636                         break;
637                     blockInfo = adoptPtr(new RenderBlockSelectionInfo(cb));
638                     cb = cb->containingBlock();
639                 }
640             }
641         }
642
643         os = getNextOrPrevRenderObjectBasedOnDirection(os, stop, continueExploring, exploringBackwards);
644     }
645
646     // Now clear the selection.
647     SelectedObjectMap::iterator oldObjectsEnd = oldSelectedObjects.end();
648     for (SelectedObjectMap::iterator i = oldSelectedObjects.begin(); i != oldObjectsEnd; ++i)
649         i->key->setSelectionStateIfNeeded(SelectionNone);
650
651     // set selection start and end
652     m_selectionStart = start;
653     m_selectionStartPos = startPos;
654     m_selectionEnd = end;
655     m_selectionEndPos = endPos;
656
657     // Update the selection status of all objects between m_selectionStart and m_selectionEnd
658     if (start && start == end)
659         start->setSelectionStateIfNeeded(SelectionBoth);
660     else {
661         if (start)
662             start->setSelectionStateIfNeeded(SelectionStart);
663         if (end)
664             end->setSelectionStateIfNeeded(SelectionEnd);
665     }
666
667     RenderObject* o = start;
668     stop = rendererAfterPosition(end, endPos);
669
670     while (o && o != stop) {
671         if (o != start && o != end && o->canBeSelectionLeaf())
672             o->setSelectionStateIfNeeded(SelectionInside);
673         o = o->nextInPreOrder();
674     }
675
676     if (blockRepaintMode != RepaintNothing)
677         layer()->clearBlockSelectionGapsBounds();
678
679     // Now that the selection state has been updated for the new objects, walk them again and
680     // put them in the new objects list.
681     o = start;
682     exploringBackwards = false;
683     continueExploring = o && (o != stop);
684     while (continueExploring) {
685         if ((o->canBeSelectionLeaf() || o == start || o == end) && o->selectionState() != SelectionNone) {
686             newSelectedObjects.set(o, adoptPtr(new RenderSelectionInfo(o, true)));
687             RenderBlock* cb = o->containingBlock();
688             while (cb && !cb->isRenderView()) {
689                 OwnPtr<RenderBlockSelectionInfo>& blockInfo = newSelectedBlocks.add(cb, nullptr).storedValue->value;
690                 if (blockInfo)
691                     break;
692                 blockInfo = adoptPtr(new RenderBlockSelectionInfo(cb));
693                 cb = cb->containingBlock();
694             }
695         }
696
697         o = getNextOrPrevRenderObjectBasedOnDirection(o, stop, continueExploring, exploringBackwards);
698     }
699
700     if (!m_frameView || blockRepaintMode == RepaintNothing)
701         return;
702
703     // Have any of the old selected objects changed compared to the new selection?
704     for (SelectedObjectMap::iterator i = oldSelectedObjects.begin(); i != oldObjectsEnd; ++i) {
705         RenderObject* obj = i->key;
706         RenderSelectionInfo* newInfo = newSelectedObjects.get(obj);
707         RenderSelectionInfo* oldInfo = i->value.get();
708         if (!newInfo || oldInfo->rect() != newInfo->rect() || oldInfo->state() != newInfo->state() ||
709             (m_selectionStart == obj && oldStartPos != m_selectionStartPos) ||
710             (m_selectionEnd == obj && oldEndPos != m_selectionEndPos)) {
711             oldInfo->repaint();
712             if (newInfo) {
713                 newInfo->repaint();
714                 newSelectedObjects.remove(obj);
715             }
716         }
717     }
718
719     // Any new objects that remain were not found in the old objects dict, and so they need to be updated.
720     SelectedObjectMap::iterator newObjectsEnd = newSelectedObjects.end();
721     for (SelectedObjectMap::iterator i = newSelectedObjects.begin(); i != newObjectsEnd; ++i)
722         i->value->repaint();
723
724     // Have any of the old blocks changed?
725     SelectedBlockMap::iterator oldBlocksEnd = oldSelectedBlocks.end();
726     for (SelectedBlockMap::iterator i = oldSelectedBlocks.begin(); i != oldBlocksEnd; ++i) {
727         RenderBlock* block = i->key;
728         RenderBlockSelectionInfo* newInfo = newSelectedBlocks.get(block);
729         RenderBlockSelectionInfo* oldInfo = i->value.get();
730         if (!newInfo || oldInfo->rects() != newInfo->rects() || oldInfo->state() != newInfo->state()) {
731             oldInfo->repaint();
732             if (newInfo) {
733                 newInfo->repaint();
734                 newSelectedBlocks.remove(block);
735             }
736         }
737     }
738
739     // Any new blocks that remain were not found in the old blocks dict, and so they need to be updated.
740     SelectedBlockMap::iterator newBlocksEnd = newSelectedBlocks.end();
741     for (SelectedBlockMap::iterator i = newSelectedBlocks.begin(); i != newBlocksEnd; ++i)
742         i->value->repaint();
743 }
744
745 void RenderView::getSelection(RenderObject*& startRenderer, int& startOffset, RenderObject*& endRenderer, int& endOffset) const
746 {
747     startRenderer = m_selectionStart;
748     startOffset = m_selectionStartPos;
749     endRenderer = m_selectionEnd;
750     endOffset = m_selectionEndPos;
751 }
752
753 void RenderView::clearSelection()
754 {
755     layer()->repaintBlockSelectionGaps();
756     setSelection(0, -1, 0, -1, RepaintNewMinusOld);
757 }
758
759 void RenderView::selectionStartEnd(int& startPos, int& endPos) const
760 {
761     startPos = m_selectionStartPos;
762     endPos = m_selectionEndPos;
763 }
764
765 bool RenderView::shouldUsePrintingLayout() const
766 {
767     if (!document().printing() || !m_frameView)
768         return false;
769     return m_frameView->frame().shouldUsePrintingLayout();
770 }
771
772 LayoutRect RenderView::viewRect() const
773 {
774     if (shouldUsePrintingLayout())
775         return LayoutRect(LayoutPoint(), size());
776     if (m_frameView)
777         return m_frameView->visibleContentRect();
778     return LayoutRect();
779 }
780
781 IntRect RenderView::unscaledDocumentRect() const
782 {
783     LayoutRect overflowRect(layoutOverflowRect());
784     flipForWritingMode(overflowRect);
785     return pixelSnappedIntRect(overflowRect);
786 }
787
788 bool RenderView::rootBackgroundIsEntirelyFixed() const
789 {
790     RenderObject* rootObject = document().documentElement() ? document().documentElement()->renderer() : 0;
791     if (!rootObject)
792         return false;
793
794     RenderObject* rootRenderer = rootObject->rendererForRootBackground();
795     return rootRenderer->hasEntirelyFixedBackground();
796 }
797
798 LayoutRect RenderView::backgroundRect(RenderBox* backgroundRenderer) const
799 {
800     if (!hasColumns())
801         return unscaledDocumentRect();
802
803     ColumnInfo* columnInfo = this->columnInfo();
804     LayoutRect backgroundRect(0, 0, columnInfo->desiredColumnWidth(), columnInfo->columnHeight() * columnInfo->columnCount());
805     if (!isHorizontalWritingMode())
806         backgroundRect = backgroundRect.transposedRect();
807     backgroundRenderer->flipForWritingMode(backgroundRect);
808
809     return backgroundRect;
810 }
811
812 IntRect RenderView::documentRect() const
813 {
814     FloatRect overflowRect(unscaledDocumentRect());
815     if (hasTransform())
816         overflowRect = layer()->currentTransform().mapRect(overflowRect);
817     return IntRect(overflowRect);
818 }
819
820 int RenderView::viewHeight(IncludeScrollbarsInRect scrollbarInclusion) const
821 {
822     int height = 0;
823     if (!shouldUsePrintingLayout() && m_frameView)
824         height = m_frameView->layoutSize(scrollbarInclusion).height();
825
826     return height;
827 }
828
829 int RenderView::viewWidth(IncludeScrollbarsInRect scrollbarInclusion) const
830 {
831     int width = 0;
832     if (!shouldUsePrintingLayout() && m_frameView)
833         width = m_frameView->layoutSize(scrollbarInclusion).width();
834
835     return width;
836 }
837
838 int RenderView::viewLogicalHeight() const
839 {
840     return style()->isHorizontalWritingMode() ? viewHeight(ExcludeScrollbars) : viewWidth(ExcludeScrollbars);
841 }
842
843 float RenderView::zoomFactor() const
844 {
845     return m_frameView->frame().pageZoomFactor();
846 }
847
848 void RenderView::pushLayoutState(RenderObject& root)
849 {
850     ASSERT(m_layoutStateDisableCount == 0);
851     ASSERT(m_layoutState == 0);
852
853     pushLayoutStateForCurrentFlowThread(root);
854     m_layoutState = new LayoutState(root);
855 }
856
857 bool RenderView::shouldDisableLayoutStateForSubtree(RenderObject& renderer) const
858 {
859     RenderObject* o = &renderer;
860     while (o) {
861         if (o->shouldDisableLayoutState())
862             return true;
863         o = o->container();
864     }
865     return false;
866 }
867
868 void RenderView::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
869 {
870     if (result.innerNode())
871         return;
872
873     Node* node = document().documentElement();
874     if (node) {
875         result.setInnerNode(node);
876         if (!result.innerNonSharedNode())
877             result.setInnerNonSharedNode(node);
878
879         LayoutPoint adjustedPoint = point;
880         offsetForContents(adjustedPoint);
881
882         result.setLocalPoint(adjustedPoint);
883     }
884 }
885
886 bool RenderView::usesCompositing() const
887 {
888     return m_compositor && m_compositor->staleInCompositingMode();
889 }
890
891 RenderLayerCompositor* RenderView::compositor()
892 {
893     if (!m_compositor)
894         m_compositor = adoptPtr(new RenderLayerCompositor(*this));
895
896     return m_compositor.get();
897 }
898
899 void RenderView::setIsInWindow(bool isInWindow)
900 {
901     if (m_compositor)
902         m_compositor->setIsInWindow(isInWindow);
903 }
904
905 FlowThreadController* RenderView::flowThreadController()
906 {
907     if (!m_flowThreadController)
908         m_flowThreadController = FlowThreadController::create();
909
910     return m_flowThreadController.get();
911 }
912
913 void RenderView::pushLayoutStateForCurrentFlowThread(const RenderObject& object)
914 {
915     if (!m_flowThreadController)
916         return;
917
918     RenderFlowThread* currentFlowThread = m_flowThreadController->currentRenderFlowThread();
919     if (!currentFlowThread)
920         return;
921
922     currentFlowThread->pushFlowThreadLayoutState(object);
923 }
924
925 void RenderView::popLayoutStateForCurrentFlowThread()
926 {
927     if (!m_flowThreadController)
928         return;
929
930     RenderFlowThread* currentFlowThread = m_flowThreadController->currentRenderFlowThread();
931     if (!currentFlowThread)
932         return;
933
934     currentFlowThread->popFlowThreadLayoutState();
935 }
936
937 IntervalArena* RenderView::intervalArena()
938 {
939     if (!m_intervalArena)
940         m_intervalArena = IntervalArena::create();
941     return m_intervalArena.get();
942 }
943
944 bool RenderView::backgroundIsKnownToBeOpaqueInRect(const LayoutRect&) const
945 {
946     // FIXME: Remove this main frame check. Same concept applies to subframes too.
947     if (!frame()->isMainFrame())
948         return false;
949
950     return m_frameView->hasOpaqueBackground();
951 }
952
953 double RenderView::layoutViewportWidth() const
954 {
955     float scale = m_frameView ? m_frameView->frame().pageZoomFactor() : 1;
956     return viewWidth(IncludeScrollbars) / scale;
957 }
958
959 double RenderView::layoutViewportHeight() const
960 {
961     float scale = m_frameView ? m_frameView->frame().pageZoomFactor() : 1;
962     return viewHeight(IncludeScrollbars) / scale;
963 }
964
965 } // namespace WebCore