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