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