Move parseFontFaceDescriptor to CSSPropertyParser.cpp
[chromium-blink-merge.git] / third_party / WebKit / Source / core / layout / LayoutObject.cpp
blob8b2ce680a823b95e64094ab5a8403c7394f98962
1 /*
2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2000 Dirk Mueller (mueller@kde.org)
5 * (C) 2004 Allan Sandfeld Jensen (kde@carewolf.com)
6 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
7 * Copyright (C) 2009 Google Inc. All rights reserved.
8 * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
27 #include "config.h"
28 #include "core/layout/LayoutObject.h"
30 #include "core/HTMLNames.h"
31 #include "core/css/resolver/StyleResolver.h"
32 #include "core/dom/AXObjectCache.h"
33 #include "core/dom/ElementTraversal.h"
34 #include "core/dom/StyleEngine.h"
35 #include "core/dom/shadow/ShadowRoot.h"
36 #include "core/editing/EditingBoundary.h"
37 #include "core/editing/EditingUtilities.h"
38 #include "core/editing/FrameSelection.h"
39 #include "core/editing/TextAffinity.h"
40 #include "core/fetch/ResourceLoadPriorityOptimizer.h"
41 #include "core/fetch/ResourceLoader.h"
42 #include "core/frame/DeprecatedScheduleStyleRecalcDuringLayout.h"
43 #include "core/frame/EventHandlerRegistry.h"
44 #include "core/frame/FrameView.h"
45 #include "core/frame/LocalFrame.h"
46 #include "core/frame/Settings.h"
47 #include "core/frame/UseCounter.h"
48 #include "core/html/HTMLAnchorElement.h"
49 #include "core/html/HTMLElement.h"
50 #include "core/html/HTMLHtmlElement.h"
51 #include "core/html/HTMLTableCellElement.h"
52 #include "core/html/HTMLTableElement.h"
53 #include "core/input/EventHandler.h"
54 #include "core/layout/HitTestResult.h"
55 #include "core/layout/LayoutCounter.h"
56 #include "core/layout/LayoutDeprecatedFlexibleBox.h"
57 #include "core/layout/LayoutFlexibleBox.h"
58 #include "core/layout/LayoutFlowThread.h"
59 #include "core/layout/LayoutGeometryMap.h"
60 #include "core/layout/LayoutGrid.h"
61 #include "core/layout/LayoutImage.h"
62 #include "core/layout/LayoutImageResourceStyleImage.h"
63 #include "core/layout/LayoutInline.h"
64 #include "core/layout/LayoutListItem.h"
65 #include "core/layout/LayoutMultiColumnSpannerPlaceholder.h"
66 #include "core/layout/LayoutObjectInlines.h"
67 #include "core/layout/LayoutPart.h"
68 #include "core/layout/LayoutScrollbarPart.h"
69 #include "core/layout/LayoutTableCaption.h"
70 #include "core/layout/LayoutTableCell.h"
71 #include "core/layout/LayoutTableCol.h"
72 #include "core/layout/LayoutTableRow.h"
73 #include "core/layout/LayoutTheme.h"
74 #include "core/layout/LayoutView.h"
75 #include "core/layout/compositing/DeprecatedPaintLayerCompositor.h"
76 #include "core/page/AutoscrollController.h"
77 #include "core/page/Page.h"
78 #include "core/paint/DeprecatedPaintLayer.h"
79 #include "core/paint/ObjectPainter.h"
80 #include "core/style/ContentData.h"
81 #include "core/style/ShadowList.h"
82 #include "platform/JSONValues.h"
83 #include "platform/RuntimeEnabledFeatures.h"
84 #include "platform/TraceEvent.h"
85 #include "platform/TracedValue.h"
86 #include "platform/geometry/TransformState.h"
87 #include "platform/graphics/GraphicsContext.h"
88 #include "platform/graphics/paint/DisplayItemList.h"
89 #include "wtf/Partitions.h"
90 #include "wtf/RefCountedLeakCounter.h"
91 #include "wtf/text/StringBuilder.h"
92 #include "wtf/text/WTFString.h"
93 #include <algorithm>
94 #ifndef NDEBUG
95 #include <stdio.h>
96 #endif
98 namespace blink {
100 namespace {
102 static bool gModifyLayoutTreeStructureAnyState = false;
104 static bool gDisablePaintInvalidationStateAsserts = false;
106 } // namespace
108 using namespace HTMLNames;
110 const LayoutUnit& caretWidth()
112 static LayoutUnit gCaretWidth(1);
113 return gCaretWidth;
116 #if ENABLE(ASSERT)
118 LayoutObject::SetLayoutNeededForbiddenScope::SetLayoutNeededForbiddenScope(LayoutObject& layoutObject)
119 : m_layoutObject(layoutObject)
120 , m_preexistingForbidden(m_layoutObject.isSetNeedsLayoutForbidden())
122 m_layoutObject.setNeedsLayoutIsForbidden(true);
125 LayoutObject::SetLayoutNeededForbiddenScope::~SetLayoutNeededForbiddenScope()
127 m_layoutObject.setNeedsLayoutIsForbidden(m_preexistingForbidden);
129 #endif
131 struct SameSizeAsLayoutObject {
132 virtual ~SameSizeAsLayoutObject() { } // Allocate vtable pointer.
133 void* pointers[5];
134 #if ENABLE(ASSERT)
135 unsigned m_debugBitfields : 2;
136 #endif
137 unsigned m_bitfields;
138 unsigned m_bitfields2;
139 LayoutRect rect; // Stores the previous paint invalidation rect.
140 LayoutPoint position; // Stores the previous position from the paint invalidation container.
143 static_assert(sizeof(LayoutObject) == sizeof(SameSizeAsLayoutObject), "LayoutObject should stay small");
145 bool LayoutObject::s_affectsParentBlock = false;
147 typedef HashMap<const LayoutObject*, LayoutRect> SelectionPaintInvalidationMap;
148 static SelectionPaintInvalidationMap* selectionPaintInvalidationMap = nullptr;
150 void* LayoutObject::operator new(size_t sz)
152 ASSERT(isMainThread());
153 return partitionAlloc(WTF::Partitions::layoutPartition(), sz);
156 void LayoutObject::operator delete(void* ptr)
158 ASSERT(isMainThread());
159 partitionFree(ptr);
162 LayoutObject* LayoutObject::createObject(Element* element, const ComputedStyle& style)
164 ASSERT(isAllowedToModifyLayoutTreeStructure(element->document()));
166 // Minimal support for content properties replacing an entire element.
167 // Works only if we have exactly one piece of content and it's a URL.
168 // Otherwise acts as if we didn't support this feature.
169 const ContentData* contentData = style.contentData();
170 if (contentData && !contentData->next() && contentData->isImage() && !element->isPseudoElement()) {
171 LayoutImage* image = new LayoutImage(element);
172 // LayoutImageResourceStyleImage requires a style being present on the image but we don't want to
173 // trigger a style change now as the node is not fully attached. Moving this code to style change
174 // doesn't make sense as it should be run once at layoutObject creation.
175 image->setStyleInternal(const_cast<ComputedStyle*>(&style));
176 if (const StyleImage* styleImage = toImageContentData(contentData)->image()) {
177 image->setImageResource(LayoutImageResourceStyleImage::create(const_cast<StyleImage*>(styleImage)));
178 image->setIsGeneratedContent();
179 } else {
180 image->setImageResource(LayoutImageResource::create());
182 image->setStyleInternal(nullptr);
183 return image;
186 switch (style.display()) {
187 case NONE:
188 return nullptr;
189 case INLINE:
190 return new LayoutInline(element);
191 case BLOCK:
192 case INLINE_BLOCK:
193 return new LayoutBlockFlow(element);
194 case LIST_ITEM:
195 return new LayoutListItem(element);
196 case TABLE:
197 case INLINE_TABLE:
198 return new LayoutTable(element);
199 case TABLE_ROW_GROUP:
200 case TABLE_HEADER_GROUP:
201 case TABLE_FOOTER_GROUP:
202 return new LayoutTableSection(element);
203 case TABLE_ROW:
204 return new LayoutTableRow(element);
205 case TABLE_COLUMN_GROUP:
206 case TABLE_COLUMN:
207 return new LayoutTableCol(element);
208 case TABLE_CELL:
209 return new LayoutTableCell(element);
210 case TABLE_CAPTION:
211 return new LayoutTableCaption(element);
212 case BOX:
213 case INLINE_BOX:
214 return new LayoutDeprecatedFlexibleBox(*element);
215 case FLEX:
216 case INLINE_FLEX:
217 return new LayoutFlexibleBox(element);
218 case GRID:
219 case INLINE_GRID:
220 return new LayoutGrid(element);
223 ASSERT_NOT_REACHED();
224 return nullptr;
227 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, layoutObjectCounter, ("LayoutObject"));
229 LayoutObject::LayoutObject(Node* node)
230 : ImageResourceClient()
231 , m_style(nullptr)
232 , m_node(node)
233 , m_parent(nullptr)
234 , m_previous(nullptr)
235 , m_next(nullptr)
236 #if ENABLE(ASSERT)
237 , m_hasAXObject(false)
238 , m_setNeedsLayoutForbidden(false)
239 #endif
240 , m_bitfields(node)
242 #ifndef NDEBUG
243 layoutObjectCounter.increment();
244 #endif
245 InstanceCounters::incrementCounter(InstanceCounters::LayoutObjectCounter);
248 LayoutObject::~LayoutObject()
250 ASSERT(!m_hasAXObject);
251 #ifndef NDEBUG
252 layoutObjectCounter.decrement();
253 #endif
254 InstanceCounters::decrementCounter(InstanceCounters::LayoutObjectCounter);
257 bool LayoutObject::isDescendantOf(const LayoutObject* obj) const
259 for (const LayoutObject* r = this; r; r = r->m_parent) {
260 if (r == obj)
261 return true;
263 return false;
266 bool LayoutObject::isHR() const
268 return isHTMLHRElement(node());
271 bool LayoutObject::isLegend() const
273 return isHTMLLegendElement(node());
276 void LayoutObject::setIsInsideFlowThreadIncludingDescendants(bool insideFlowThread)
278 LayoutObject* next;
279 for (LayoutObject *object = this; object; object = next) {
280 // If object is a fragmentation context it already updated the descendants flag accordingly.
281 if (object->isLayoutFlowThread()) {
282 next = object->nextInPreOrderAfterChildren(this);
283 continue;
285 next = object->nextInPreOrder(this);
286 ASSERT(insideFlowThread != object->isInsideFlowThread());
287 object->setIsInsideFlowThread(insideFlowThread);
291 bool LayoutObject::requiresAnonymousTableWrappers(const LayoutObject* newChild) const
293 // Check should agree with:
294 // CSS 2.1 Tables: 17.2.1 Anonymous table objects
295 // http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes
296 if (newChild->isLayoutTableCol()) {
297 const LayoutTableCol* newTableColumn = toLayoutTableCol(newChild);
298 bool isColumnInColumnGroup = newTableColumn->isTableColumn() && isLayoutTableCol();
299 return !isTable() && !isColumnInColumnGroup;
301 if (newChild->isTableCaption())
302 return !isTable();
303 if (newChild->isTableSection())
304 return !isTable();
305 if (newChild->isTableRow())
306 return !isTableSection();
307 if (newChild->isTableCell())
308 return !isTableRow();
309 return false;
312 void LayoutObject::addChild(LayoutObject* newChild, LayoutObject* beforeChild)
314 ASSERT(isAllowedToModifyLayoutTreeStructure(document()));
316 LayoutObjectChildList* children = virtualChildren();
317 ASSERT(children);
318 if (!children)
319 return;
321 if (requiresAnonymousTableWrappers(newChild)) {
322 // Generate an anonymous table or reuse existing one from previous child
323 // Per: 17.2.1 Anonymous table objects 3. Generate missing parents
324 // http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes
325 LayoutTable* table;
326 LayoutObject* afterChild = beforeChild ? beforeChild->previousSibling() : children->lastChild();
327 if (afterChild && afterChild->isAnonymous() && afterChild->isTable() && !afterChild->isBeforeContent()) {
328 table = toLayoutTable(afterChild);
329 } else {
330 table = LayoutTable::createAnonymousWithParent(this);
331 addChild(table, beforeChild);
333 table->addChild(newChild);
334 } else {
335 children->insertChildNode(this, newChild, beforeChild);
338 if (newChild->isText() && newChild->style()->textTransform() == CAPITALIZE)
339 toLayoutText(newChild)->transformText();
341 // SVG creates layoutObjects for <g display="none">, as SVG requires children of hidden
342 // <g>s to have layoutObjects - at least that's how our implementation works. Consider:
343 // <g display="none"><foreignObject><body style="position: relative">FOO...
344 // - layerTypeRequired() would return true for the <body>, creating a new Layer
345 // - when the document is painted, both layers are painted. The <body> layer doesn't
346 // know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
347 // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
348 // and stop creating layers at all for these cases - they're not used anyways.
349 if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
350 toLayoutBoxModelObject(newChild)->layer()->removeOnlyThisLayer();
353 void LayoutObject::removeChild(LayoutObject* oldChild)
355 ASSERT(isAllowedToModifyLayoutTreeStructure(document()));
357 LayoutObjectChildList* children = virtualChildren();
358 ASSERT(children);
359 if (!children)
360 return;
362 children->removeChildNode(this, oldChild);
365 void LayoutObject::setDangerousOneWayParent(LayoutObject* parent)
367 ASSERT(!previousSibling());
368 ASSERT(!nextSibling());
369 ASSERT(!parent || !m_parent);
370 setParent(parent);
373 void LayoutObject::registerSubtreeChangeListenerOnDescendants(bool value)
375 // If we're set to the same value then we're done as that means it's
376 // set down the tree that way already.
377 if (m_bitfields.subtreeChangeListenerRegistered() == value)
378 return;
380 m_bitfields.setSubtreeChangeListenerRegistered(value);
382 for (LayoutObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
383 curr->registerSubtreeChangeListenerOnDescendants(value);
386 void LayoutObject::notifyAncestorsOfSubtreeChange()
388 if (m_bitfields.notifiedOfSubtreeChange())
389 return;
391 m_bitfields.setNotifiedOfSubtreeChange(true);
392 if (parent())
393 parent()->notifyAncestorsOfSubtreeChange();
396 void LayoutObject::notifyOfSubtreeChange()
398 if (!m_bitfields.subtreeChangeListenerRegistered())
399 return;
400 if (m_bitfields.notifiedOfSubtreeChange())
401 return;
403 notifyAncestorsOfSubtreeChange();
405 // We can modify the layout tree during layout which means that we may
406 // try to schedule this during performLayout. This should no longer
407 // happen when crbug.com/370457 is fixed.
408 DeprecatedScheduleStyleRecalcDuringLayout marker(document().lifecycle());
409 document().scheduleLayoutTreeUpdateIfNeeded();
412 void LayoutObject::handleSubtreeModifications()
414 ASSERT(wasNotifiedOfSubtreeChange());
415 ASSERT(document().lifecycle().stateAllowsLayoutTreeNotifications());
417 if (consumesSubtreeChangeNotification())
418 subtreeDidChange();
420 m_bitfields.setNotifiedOfSubtreeChange(false);
422 for (LayoutObject* object = slowFirstChild(); object; object = object->nextSibling()) {
423 if (!object->wasNotifiedOfSubtreeChange())
424 continue;
425 object->handleSubtreeModifications();
429 LayoutObject* LayoutObject::nextInPreOrder() const
431 if (LayoutObject* o = slowFirstChild())
432 return o;
434 return nextInPreOrderAfterChildren();
437 LayoutObject* LayoutObject::nextInPreOrderAfterChildren() const
439 LayoutObject* o = nextSibling();
440 if (!o) {
441 o = parent();
442 while (o && !o->nextSibling())
443 o = o->parent();
444 if (o)
445 o = o->nextSibling();
448 return o;
451 LayoutObject* LayoutObject::nextInPreOrder(const LayoutObject* stayWithin) const
453 if (LayoutObject* o = slowFirstChild())
454 return o;
456 return nextInPreOrderAfterChildren(stayWithin);
459 LayoutObject* LayoutObject::nextInPreOrderAfterChildren(const LayoutObject* stayWithin) const
461 if (this == stayWithin)
462 return nullptr;
464 const LayoutObject* current = this;
465 LayoutObject* next = current->nextSibling();
466 for (; !next; next = current->nextSibling()) {
467 current = current->parent();
468 if (!current || current == stayWithin)
469 return nullptr;
471 return next;
474 LayoutObject* LayoutObject::previousInPreOrder() const
476 if (LayoutObject* o = previousSibling()) {
477 while (LayoutObject* lastChild = o->slowLastChild())
478 o = lastChild;
479 return o;
482 return parent();
485 LayoutObject* LayoutObject::previousInPreOrder(const LayoutObject* stayWithin) const
487 if (this == stayWithin)
488 return nullptr;
490 return previousInPreOrder();
493 LayoutObject* LayoutObject::childAt(unsigned index) const
495 LayoutObject* child = slowFirstChild();
496 for (unsigned i = 0; child && i < index; i++)
497 child = child->nextSibling();
498 return child;
501 LayoutObject* LayoutObject::lastLeafChild() const
503 LayoutObject* r = slowLastChild();
504 while (r) {
505 LayoutObject* n = nullptr;
506 n = r->slowLastChild();
507 if (!n)
508 break;
509 r = n;
511 return r;
514 static void addLayers(LayoutObject* obj, DeprecatedPaintLayer* parentLayer, LayoutObject*& newObject,
515 DeprecatedPaintLayer*& beforeChild)
517 if (obj->hasLayer()) {
518 if (!beforeChild && newObject) {
519 // We need to figure out the layer that follows newObject. We only do
520 // this the first time we find a child layer, and then we update the
521 // pointer values for newObject and beforeChild used by everyone else.
522 beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
523 newObject = nullptr;
525 parentLayer->addChild(toLayoutBoxModelObject(obj)->layer(), beforeChild);
526 return;
529 for (LayoutObject* curr = obj->slowFirstChild(); curr; curr = curr->nextSibling())
530 addLayers(curr, parentLayer, newObject, beforeChild);
533 void LayoutObject::addLayers(DeprecatedPaintLayer* parentLayer)
535 if (!parentLayer)
536 return;
538 LayoutObject* object = this;
539 DeprecatedPaintLayer* beforeChild = nullptr;
540 blink::addLayers(this, parentLayer, object, beforeChild);
543 void LayoutObject::removeLayers(DeprecatedPaintLayer* parentLayer)
545 if (!parentLayer)
546 return;
548 if (hasLayer()) {
549 parentLayer->removeChild(toLayoutBoxModelObject(this)->layer());
550 return;
553 for (LayoutObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
554 curr->removeLayers(parentLayer);
557 void LayoutObject::moveLayers(DeprecatedPaintLayer* oldParent, DeprecatedPaintLayer* newParent)
559 if (!newParent)
560 return;
562 if (hasLayer()) {
563 DeprecatedPaintLayer* layer = toLayoutBoxModelObject(this)->layer();
564 ASSERT(oldParent == layer->parent());
565 if (oldParent)
566 oldParent->removeChild(layer);
567 newParent->addChild(layer);
568 return;
571 for (LayoutObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
572 curr->moveLayers(oldParent, newParent);
575 DeprecatedPaintLayer* LayoutObject::findNextLayer(DeprecatedPaintLayer* parentLayer, LayoutObject* startPoint, bool checkParent)
577 // Error check the parent layer passed in. If it's null, we can't find anything.
578 if (!parentLayer)
579 return 0;
581 // Step 1: If our layer is a child of the desired parent, then return our layer.
582 DeprecatedPaintLayer* ourLayer = hasLayer() ? toLayoutBoxModelObject(this)->layer() : nullptr;
583 if (ourLayer && ourLayer->parent() == parentLayer)
584 return ourLayer;
586 // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
587 // into our siblings trying to find the next layer whose parent is the desired parent.
588 if (!ourLayer || ourLayer == parentLayer) {
589 for (LayoutObject* curr = startPoint ? startPoint->nextSibling() : slowFirstChild();
590 curr; curr = curr->nextSibling()) {
591 DeprecatedPaintLayer* nextLayer = curr->findNextLayer(parentLayer, nullptr, false);
592 if (nextLayer)
593 return nextLayer;
597 // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
598 // find anything.
599 if (parentLayer == ourLayer)
600 return nullptr;
602 // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
603 // follow us to see if we can locate a layer.
604 if (checkParent && parent())
605 return parent()->findNextLayer(parentLayer, this, true);
607 return nullptr;
610 DeprecatedPaintLayer* LayoutObject::enclosingLayer() const
612 for (const LayoutObject* current = this; current; current = current->parent()) {
613 if (current->hasLayer())
614 return toLayoutBoxModelObject(current)->layer();
616 // FIXME: we should get rid of detached layout subtrees, at which point this code should
617 // not be reached. crbug.com/411429
618 return nullptr;
621 bool LayoutObject::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
623 LayoutBox* enclosingBox = this->enclosingBox();
624 if (!enclosingBox)
625 return false;
627 enclosingBox->scrollRectToVisible(rect, alignX, alignY);
628 return true;
631 LayoutBox* LayoutObject::enclosingBox() const
633 LayoutObject* curr = const_cast<LayoutObject*>(this);
634 while (curr) {
635 if (curr->isBox())
636 return toLayoutBox(curr);
637 curr = curr->parent();
640 ASSERT_NOT_REACHED();
641 return nullptr;
644 LayoutBoxModelObject* LayoutObject::enclosingBoxModelObject() const
646 LayoutObject* curr = const_cast<LayoutObject*>(this);
647 while (curr) {
648 if (curr->isBoxModelObject())
649 return toLayoutBoxModelObject(curr);
650 curr = curr->parent();
653 ASSERT_NOT_REACHED();
654 return nullptr;
657 LayoutBox* LayoutObject::enclosingScrollableBox() const
659 for (LayoutObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
660 if (!ancestor->isBox())
661 continue;
663 LayoutBox* ancestorBox = toLayoutBox(ancestor);
664 if (ancestorBox->canBeScrolledAndHasScrollableArea())
665 return ancestorBox;
668 return nullptr;
671 LayoutFlowThread* LayoutObject::locateFlowThreadContainingBlock() const
673 ASSERT(isInsideFlowThread());
675 // See if we have the thread cached because we're in the middle of layout.
676 if (LayoutState* layoutState = view()->layoutState()) {
677 if (LayoutFlowThread* flowThread = layoutState->flowThread())
678 return flowThread;
681 // Not in the middle of layout so have to find the thread the slow way.
682 return LayoutFlowThread::locateFlowThreadContainingBlockOf(*this);
685 bool LayoutObject::skipInvalidationWhenLaidOutChildren() const
687 if (!m_bitfields.neededLayoutBecauseOfChildren())
688 return false;
690 // SVG layoutObjects need to be invalidated when their children are laid out.
691 // LayoutBlocks with line boxes are responsible to invalidate them so we can't ignore them.
692 if (isSVG() || (isLayoutBlockFlow() && toLayoutBlockFlow(this)->firstLineBox()))
693 return false;
695 // In case scrollbars got repositioned (which will typically happen if the layout object got
696 // resized), we cannot skip invalidation.
697 if (hasNonCompositedScrollbars())
698 return false;
700 // We can't detect whether a plugin has box effects, so disable this optimization for that case.
701 if (isEmbeddedObject())
702 return false;
704 return !hasBoxEffect();
707 LayoutBlock* LayoutObject::firstLineBlock() const
709 return nullptr;
712 static inline bool objectIsRelayoutBoundary(const LayoutObject* object)
714 // FIXME: In future it may be possible to broaden these conditions in order to improve performance.
715 if (object->isTextControl())
716 return true;
718 if (object->isSVGRoot())
719 return true;
721 if (!object->hasOverflowClip())
722 return false;
724 if (object->style()->width().isIntrinsicOrAuto() || object->style()->height().isIntrinsicOrAuto() || object->style()->height().hasPercent())
725 return false;
727 // Table parts can't be relayout roots since the table is responsible for layouting all the parts.
728 if (object->isTablePart())
729 return false;
731 // Inside multicol it's generally problematic to allow relayout roots. The multicol container
732 // itself may be scheduled for relayout as well (due to other changes that may have happened
733 // since the previous layout pass), which might affect the column heights, which may affect how
734 // this object breaks across columns). Spanners may also have been added or removed since the
735 // previous layout pass, which is just another way of affecting the column heights (and the
736 // number of rows). Instead of identifying cases where it's safe to allow relayout roots, just
737 // disallow them inside multicol.
738 if (object->isInsideFlowThread())
739 return false;
741 return true;
744 void LayoutObject::markContainerChainForLayout(bool scheduleRelayout, SubtreeLayoutScope* layouter)
746 ASSERT(!isSetNeedsLayoutForbidden());
747 ASSERT(!layouter || this != layouter->root());
749 LayoutObject* object = container();
750 LayoutObject* last = this;
752 bool simplifiedNormalFlowLayout = needsSimplifiedNormalFlowLayout() && !selfNeedsLayout() && !normalChildNeedsLayout();
754 while (object) {
755 if (object->selfNeedsLayout())
756 return;
758 // Don't mark the outermost object of an unrooted subtree. That object will be
759 // marked when the subtree is added to the document.
760 LayoutObject* container = object->container();
761 if (!container && !object->isLayoutView())
762 return;
763 if (!last->isTextOrSVGChild() && last->style()->hasOutOfFlowPosition()) {
764 bool willSkipRelativelyPositionedInlines = !object->isLayoutBlock() || object->isAnonymousBlock();
765 // Skip relatively positioned inlines and anonymous blocks to get to the enclosing LayoutBlock.
766 while (object && (!object->isLayoutBlock() || object->isAnonymousBlock()))
767 object = object->container();
768 if (!object || object->posChildNeedsLayout())
769 return;
770 if (willSkipRelativelyPositionedInlines)
771 container = object->container();
772 object->setPosChildNeedsLayout(true);
773 simplifiedNormalFlowLayout = true;
774 ASSERT(!object->isSetNeedsLayoutForbidden());
775 } else if (simplifiedNormalFlowLayout) {
776 if (object->needsSimplifiedNormalFlowLayout())
777 return;
778 object->setNeedsSimplifiedNormalFlowLayout(true);
779 ASSERT(!object->isSetNeedsLayoutForbidden());
780 } else {
781 if (object->normalChildNeedsLayout())
782 return;
783 object->setNormalChildNeedsLayout(true);
784 ASSERT(!object->isSetNeedsLayoutForbidden());
787 if (layouter) {
788 layouter->recordObjectMarkedForLayout(object);
789 if (object == layouter->root())
790 return;
793 last = object;
794 if (scheduleRelayout && objectIsRelayoutBoundary(last))
795 break;
796 object = container;
799 if (scheduleRelayout)
800 last->scheduleRelayout();
803 #if ENABLE(ASSERT)
804 void LayoutObject::checkBlockPositionedObjectsNeedLayout()
806 ASSERT(!needsLayout());
808 if (isLayoutBlock())
809 toLayoutBlock(this)->checkPositionedObjectsNeedLayout();
811 #endif
813 void LayoutObject::setPreferredLogicalWidthsDirty(MarkingBehavior markParents)
815 m_bitfields.setPreferredLogicalWidthsDirty(true);
816 if (markParents == MarkContainerChain && (isText() || !style()->hasOutOfFlowPosition()))
817 invalidateContainerPreferredLogicalWidths();
820 void LayoutObject::clearPreferredLogicalWidthsDirty()
822 m_bitfields.setPreferredLogicalWidthsDirty(false);
825 inline void LayoutObject::invalidateContainerPreferredLogicalWidths()
827 // In order to avoid pathological behavior when inlines are deeply nested, we do include them
828 // in the chain that we mark dirty (even though they're kind of irrelevant).
829 LayoutObject* o = isTableCell() ? containingBlock() : container();
830 while (o && !o->preferredLogicalWidthsDirty()) {
831 // Don't invalidate the outermost object of an unrooted subtree. That object will be
832 // invalidated when the subtree is added to the document.
833 LayoutObject* container = o->isTableCell() ? o->containingBlock() : o->container();
834 if (!container && !o->isLayoutView())
835 break;
837 o->m_bitfields.setPreferredLogicalWidthsDirty(true);
838 if (o->style()->hasOutOfFlowPosition()) {
839 // A positioned object has no effect on the min/max width of its containing block ever.
840 // We can optimize this case and not go up any further.
841 break;
843 o = container;
847 LayoutBlock* LayoutObject::containerForFixedPosition(const LayoutBoxModelObject* paintInvalidationContainer, bool* paintInvalidationContainerSkipped) const
849 ASSERT(!paintInvalidationContainerSkipped || !*paintInvalidationContainerSkipped);
850 ASSERT(!isText());
851 ASSERT(style()->position() == FixedPosition);
853 LayoutObject* ancestor = parent();
854 for (; ancestor && !ancestor->canContainFixedPositionObjects(); ancestor = ancestor->parent()) {
855 if (paintInvalidationContainerSkipped && ancestor == paintInvalidationContainer)
856 *paintInvalidationContainerSkipped = true;
859 ASSERT(!ancestor || !ancestor->isAnonymousBlock());
860 return toLayoutBlock(ancestor);
863 LayoutBlock* LayoutObject::containingBlockForAbsolutePosition() const
865 LayoutObject* o = parent();
866 while (o) {
867 if (o->style()->position() != StaticPosition && (!o->isInline() || o->isReplaced()))
868 break;
870 if (o->canContainFixedPositionObjects())
871 break;
873 // For relpositioned inlines, we return the nearest non-anonymous enclosing block. We don't try
874 // to return the inline itself. This allows us to avoid having a positioned objects
875 // list in all LayoutInlines and lets us return a strongly-typed LayoutBlock* result
876 // from this method. The container() method can actually be used to obtain the
877 // inline directly.
878 if (o->style()->hasInFlowPosition() && o->isInline() && !o->isReplaced()) {
879 o = o->containingBlock();
880 break;
883 o = o->parent();
886 if (o && !o->isLayoutBlock())
887 o = o->containingBlock();
889 while (o && o->isAnonymousBlock())
890 o = o->containingBlock();
892 if (!o || !o->isLayoutBlock())
893 return nullptr; // This can still happen in case of an orphaned tree
895 return toLayoutBlock(o);
898 LayoutBlock* LayoutObject::containingBlock() const
900 LayoutObject* o = parent();
901 if (!o && isLayoutScrollbarPart())
902 o = toLayoutScrollbarPart(this)->layoutObjectOwningScrollbar();
903 if (!isTextOrSVGChild()) {
904 if (m_style->position() == FixedPosition)
905 return containerForFixedPosition();
906 if (m_style->position() == AbsolutePosition)
907 return containingBlockForAbsolutePosition();
909 if (isColumnSpanAll()) {
910 o = spannerPlaceholder()->containingBlock();
911 } else {
912 while (o && ((o->isInline() && !o->isReplaced()) || !o->isLayoutBlock()))
913 o = o->parent();
916 if (!o || !o->isLayoutBlock())
917 return nullptr; // This can still happen in case of an orphaned tree
919 return toLayoutBlock(o);
922 bool LayoutObject::mustInvalidateFillLayersPaintOnHeightChange(const FillLayer& layer) const
924 // Nobody will use multiple layers without wanting fancy positioning.
925 if (layer.next())
926 return true;
928 // Make sure we have a valid image.
929 StyleImage* img = layer.image();
930 if (!img || !img->canRender(*this, style()->effectiveZoom()))
931 return false;
933 if (layer.repeatY() != RepeatFill && layer.repeatY() != NoRepeatFill)
934 return true;
936 // TODO(alancutter): Make this work correctly for calc lengths.
937 if (layer.yPosition().hasPercent() && !layer.yPosition().isZero())
938 return true;
940 if (layer.backgroundYOrigin() != TopEdge)
941 return true;
943 EFillSizeType sizeType = layer.sizeType();
945 if (sizeType == Contain || sizeType == Cover)
946 return true;
948 if (sizeType == SizeLength) {
949 // TODO(alancutter): Make this work correctly for calc lengths.
950 if (layer.sizeLength().height().hasPercent() && !layer.sizeLength().height().isZero())
951 return true;
952 if (img->isGeneratedImage() && layer.sizeLength().height().isAuto())
953 return true;
954 } else if (img->usesImageContainerSize()) {
955 return true;
958 return false;
961 FloatRect LayoutObject::absoluteBoundingBoxFloatRect() const
963 Vector<FloatQuad> quads;
964 absoluteQuads(quads);
966 size_t n = quads.size();
967 if (n == 0)
968 return FloatRect();
970 FloatRect result = quads[0].boundingBox();
971 for (size_t i = 1; i < n; ++i)
972 result.unite(quads[i].boundingBox());
973 return result;
976 IntRect LayoutObject::absoluteBoundingBoxRect() const
978 Vector<FloatQuad> quads;
979 absoluteQuads(quads);
981 size_t n = quads.size();
982 if (!n)
983 return IntRect();
985 IntRect result = quads[0].enclosingBoundingBox();
986 for (size_t i = 1; i < n; ++i)
987 result.unite(quads[i].enclosingBoundingBox());
988 return result;
991 IntRect LayoutObject::absoluteBoundingBoxRectIgnoringTransforms() const
993 FloatPoint absPos = localToAbsolute();
994 Vector<IntRect> rects;
995 absoluteRects(rects, flooredLayoutPoint(absPos));
997 size_t n = rects.size();
998 if (!n)
999 return IntRect();
1001 IntRect result = rects[0];
1002 for (size_t i = 1; i < n; ++i)
1003 result.unite(rects[i]);
1004 return result;
1007 IntRect LayoutObject::absoluteElementBoundingBoxRect() const
1009 Vector<LayoutRect> rects;
1010 const LayoutBoxModelObject* container = enclosingLayer()->layoutObject();
1011 addElementVisualOverflowRects(rects, LayoutPoint(localToContainerPoint(FloatPoint(), container)));
1012 return container->localToAbsoluteQuad(FloatQuad(FloatRect(unionRect(rects)))).enclosingBoundingBox();
1015 FloatRect LayoutObject::absoluteBoundingBoxRectForRange(const Range* range)
1017 if (!range || !range->startContainer())
1018 return FloatRect();
1020 range->ownerDocument().updateLayout();
1022 Vector<FloatQuad> quads;
1023 range->textQuads(quads);
1025 FloatRect result;
1026 for (size_t i = 0; i < quads.size(); ++i)
1027 result.unite(quads[i].boundingBox());
1029 return result;
1032 void LayoutObject::addAbsoluteRectForLayer(IntRect& result)
1034 if (hasLayer())
1035 result.unite(absoluteBoundingBoxRect());
1036 for (LayoutObject* current = slowFirstChild(); current; current = current->nextSibling())
1037 current->addAbsoluteRectForLayer(result);
1040 IntRect LayoutObject::paintingRootRect(IntRect& topLevelRect)
1042 IntRect result = absoluteBoundingBoxRect();
1043 for (LayoutObject* current = slowFirstChild(); current; current = current->nextSibling())
1044 current->addAbsoluteRectForLayer(result);
1045 return result;
1048 void LayoutObject::paint(const PaintInfo&, const LayoutPoint&)
1052 const LayoutBoxModelObject* LayoutObject::containerForPaintInvalidation() const
1054 RELEASE_ASSERT(isRooted());
1055 return adjustCompositedContainerForSpecialAncestors(enclosingCompositedContainer());
1058 const LayoutBoxModelObject& LayoutObject::containerForPaintInvalidationOnRootedTree() const
1060 RELEASE_ASSERT(isRooted());
1062 const LayoutBoxModelObject* paintInvalidationContainer = containerForPaintInvalidation();
1063 ASSERT(paintInvalidationContainer);
1065 return *paintInvalidationContainer;
1068 const LayoutBoxModelObject* LayoutObject::enclosingCompositedContainer() const
1070 LayoutBoxModelObject* container = nullptr;
1071 // FIXME: CompositingState is not necessarily up to date for many callers of this function.
1072 DisableCompositingQueryAsserts disabler;
1074 if (DeprecatedPaintLayer* compositingLayer = enclosingLayer()->enclosingLayerForPaintInvalidationCrossingFrameBoundaries())
1075 container = compositingLayer->layoutObject();
1076 return container;
1079 const LayoutBoxModelObject* LayoutObject::adjustCompositedContainerForSpecialAncestors(const LayoutBoxModelObject* paintInvalidationContainer) const
1081 if (paintInvalidationContainer)
1082 return paintInvalidationContainer;
1084 LayoutView* layoutView = view();
1085 while (layoutView->frame()->ownerLayoutObject())
1086 layoutView = layoutView->frame()->ownerLayoutObject()->view();
1087 return layoutView;
1090 String LayoutObject::decoratedName() const
1092 StringBuilder name;
1093 name.append(this->name());
1095 if (isAnonymous())
1096 name.append(" (anonymous)");
1097 // FIXME: Remove the special case for LayoutView here (requires rebaseline of all tests).
1098 if (isOutOfFlowPositioned() && !isLayoutView())
1099 name.append(" (positioned)");
1100 if (isRelPositioned())
1101 name.append(" (relative positioned)");
1102 if (isStickyPositioned())
1103 name.append(" (sticky positioned)");
1104 if (isFloating())
1105 name.append(" (floating)");
1106 if (spannerPlaceholder())
1107 name.append(" (column spanner)");
1109 return name.toString();
1112 String LayoutObject::debugName() const
1114 StringBuilder name;
1115 name.append(decoratedName());
1117 if (const Node* node = this->node()) {
1118 name.append(' ');
1119 name.append(node->debugName());
1121 return name.toString();
1124 bool LayoutObject::isPaintInvalidationContainer() const
1126 return hasLayer() && toLayoutBoxModelObject(this)->layer()->isPaintInvalidationContainer();
1129 template <typename T>
1130 void addJsonObjectForRect(TracedValue* value, const char* name, const T& rect)
1132 value->beginDictionary(name);
1133 value->setDouble("x", rect.x());
1134 value->setDouble("y", rect.y());
1135 value->setDouble("width", rect.width());
1136 value->setDouble("height", rect.height());
1137 value->endDictionary();
1140 template <typename T>
1141 void addJsonObjectForPoint(TracedValue* value, const char* name, const T& point)
1143 value->beginDictionary(name);
1144 value->setDouble("x", point.x());
1145 value->setDouble("y", point.y());
1146 value->endDictionary();
1149 static PassRefPtr<TraceEvent::ConvertableToTraceFormat> jsonObjectForPaintInvalidationInfo(const LayoutRect& rect, const String& invalidationReason)
1151 RefPtr<TracedValue> value = TracedValue::create();
1152 addJsonObjectForRect(value.get(), "rect", rect);
1153 value->setString("invalidation_reason", invalidationReason);
1154 return value;
1157 LayoutRect LayoutObject::computePaintInvalidationRect(const LayoutBoxModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
1159 return clippedOverflowRectForPaintInvalidation(paintInvalidationContainer, paintInvalidationState);
1162 void LayoutObject::invalidatePaintUsingContainer(const LayoutBoxModelObject& paintInvalidationContainer, const LayoutRect& r, PaintInvalidationReason invalidationReason) const
1164 ASSERT(gDisablePaintInvalidationStateAsserts || document().lifecycle().state() == DocumentLifecycle::InPaintInvalidation);
1166 if (r.isEmpty())
1167 return;
1169 RELEASE_ASSERT(isRooted());
1171 // FIXME: Unify "devtools.timeline.invalidationTracking" and "blink.invalidation". crbug.com/413527.
1172 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"),
1173 "PaintInvalidationTracking",
1174 TRACE_EVENT_SCOPE_THREAD,
1175 "data", InspectorPaintInvalidationTrackingEvent::data(this, paintInvalidationContainer));
1176 TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"), "LayoutObject::invalidatePaintUsingContainer()",
1177 "object", this->debugName().ascii(),
1178 "info", jsonObjectForPaintInvalidationInfo(r, paintInvalidationReasonToString(invalidationReason)));
1180 if (paintInvalidationContainer.isLayoutView()) {
1181 toLayoutView(&paintInvalidationContainer)->invalidatePaintForRectangle(r, invalidationReason);
1182 return;
1185 if (paintInvalidationContainer.view()->usesCompositing()) {
1186 ASSERT(paintInvalidationContainer.isPaintInvalidationContainer());
1187 paintInvalidationContainer.setBackingNeedsPaintInvalidationInRect(r, invalidationReason);
1191 void LayoutObject::invalidateDisplayItemClient(const DisplayItemClientWrapper& displayItemClient) const
1193 // Not using enclosingCompositedContainer() directly because this object may be in an orphaned subtree.
1194 if (DeprecatedPaintLayer* enclosingLayer = this->enclosingLayer()) {
1195 // This is valid because we want to invalidate the client in the display item list of the current backing.
1196 DisableCompositingQueryAsserts disabler;
1197 if (const DeprecatedPaintLayer* paintInvalidationLayer = enclosingLayer->enclosingLayerForPaintInvalidationCrossingFrameBoundaries())
1198 paintInvalidationLayer->layoutObject()->invalidateDisplayItemClientOnBacking(displayItemClient);
1200 enclosingLayer->setNeedsRepaint();
1204 void LayoutObject::invalidateDisplayItemClients(const LayoutBoxModelObject& paintInvalidationContainer) const
1206 paintInvalidationContainer.invalidateDisplayItemClientOnBacking(*this);
1208 if (DeprecatedPaintLayer* enclosingLayer = this->enclosingLayer())
1209 enclosingLayer->setNeedsRepaint();
1212 LayoutRect LayoutObject::boundsRectForPaintInvalidation(const LayoutBoxModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
1214 if (!paintInvalidationContainer)
1215 return computePaintInvalidationRect(paintInvalidationContainer, paintInvalidationState);
1216 return DeprecatedPaintLayer::computePaintInvalidationRect(this, paintInvalidationContainer->layer(), paintInvalidationState);
1219 const LayoutBoxModelObject* LayoutObject::invalidatePaintRectangleInternal(const LayoutRect& r) const
1221 RELEASE_ASSERT(isRooted());
1223 if (r.isEmpty())
1224 return nullptr;
1226 if (view()->document().printing())
1227 return nullptr; // Don't invalidate paints if we're printing.
1229 LayoutRect dirtyRect(r);
1231 const LayoutBoxModelObject& paintInvalidationContainer = containerForPaintInvalidationOnRootedTree();
1232 DeprecatedPaintLayer::mapRectToPaintInvalidationBacking(this, &paintInvalidationContainer, dirtyRect);
1233 invalidatePaintUsingContainer(paintInvalidationContainer, dirtyRect, PaintInvalidationRectangle);
1234 return &paintInvalidationContainer;
1237 void LayoutObject::invalidatePaintRectangle(const LayoutRect& r) const
1239 if (const LayoutBoxModelObject* paintInvalidationContainer = invalidatePaintRectangleInternal(r))
1240 invalidateDisplayItemClients(*paintInvalidationContainer);
1243 void LayoutObject::invalidateTreeIfNeeded(PaintInvalidationState& paintInvalidationState)
1245 ASSERT(!needsLayout());
1247 // If we didn't need paint invalidation then our children don't need as well.
1248 // Skip walking down the tree as everything should be fine below us.
1249 if (!shouldCheckForPaintInvalidation(paintInvalidationState))
1250 return;
1252 PaintInvalidationReason reason = invalidatePaintIfNeeded(paintInvalidationState, paintInvalidationState.paintInvalidationContainer());
1253 clearPaintInvalidationState(paintInvalidationState);
1255 if (reason == PaintInvalidationDelayedFull)
1256 paintInvalidationState.pushDelayedPaintInvalidationTarget(*this);
1258 invalidatePaintOfSubtreesIfNeeded(paintInvalidationState);
1261 void LayoutObject::invalidatePaintOfSubtreesIfNeeded(PaintInvalidationState& childPaintInvalidationState)
1263 for (LayoutObject* child = slowFirstChild(); child; child = child->nextSibling()) {
1264 if (!child->isOutOfFlowPositioned())
1265 child->invalidateTreeIfNeeded(childPaintInvalidationState);
1269 static PassRefPtr<TraceEvent::ConvertableToTraceFormat> jsonObjectForOldAndNewRects(const LayoutRect& oldRect, const LayoutPoint& oldLocation, const LayoutRect& newRect, const LayoutPoint& newLocation)
1271 RefPtr<TracedValue> value = TracedValue::create();
1272 addJsonObjectForRect(value.get(), "oldRect", oldRect);
1273 addJsonObjectForPoint(value.get(), "oldLocation", oldLocation);
1274 addJsonObjectForRect(value.get(), "newRect", newRect);
1275 addJsonObjectForPoint(value.get(), "newLocation", newLocation);
1276 return value;
1279 LayoutRect LayoutObject::selectionRectInViewCoordinates() const
1281 return selectionRectForPaintInvalidation(view());
1284 LayoutRect LayoutObject::previousSelectionRectForPaintInvalidation() const
1286 if (!selectionPaintInvalidationMap)
1287 return LayoutRect();
1289 return selectionPaintInvalidationMap->get(this);
1292 void LayoutObject::setPreviousSelectionRectForPaintInvalidation(const LayoutRect& selectionRect)
1294 if (!selectionPaintInvalidationMap) {
1295 if (selectionRect.isEmpty())
1296 return;
1297 selectionPaintInvalidationMap = new SelectionPaintInvalidationMap();
1300 if (selectionRect.isEmpty())
1301 selectionPaintInvalidationMap->remove(this);
1302 else
1303 selectionPaintInvalidationMap->set(this, selectionRect);
1306 // TODO(wangxianzhu): Remove this for slimming paint v2 because we won't care about paint invalidation rects.
1307 inline void LayoutObject::invalidateSelectionIfNeeded(const LayoutBoxModelObject& paintInvalidationContainer, PaintInvalidationReason invalidationReason)
1309 // Update selection rect when we are doing full invalidation (in case that the object is moved, composite status changed, etc.)
1310 // or shouldInvalidationSelection is set (in case that the selection itself changed).
1311 bool fullInvalidation = view()->doingFullPaintInvalidation() || isFullPaintInvalidationReason(invalidationReason);
1312 if (!fullInvalidation && !shouldInvalidateSelection())
1313 return;
1315 LayoutRect oldSelectionRect = previousSelectionRectForPaintInvalidation();
1316 LayoutRect newSelectionRect = selectionRectForPaintInvalidation(&paintInvalidationContainer);
1318 // Composited scrolling should not be included in the bounds and position tracking, because the graphics layer backing the scroller
1319 // does not move on scroll.
1320 if (paintInvalidationContainer.usesCompositedScrolling() && &paintInvalidationContainer != this) {
1321 LayoutSize inverseOffset(toLayoutBox(&paintInvalidationContainer)->scrolledContentOffset());
1322 newSelectionRect.move(inverseOffset);
1325 setPreviousSelectionRectForPaintInvalidation(newSelectionRect);
1327 if (shouldInvalidateSelection())
1328 invalidateDisplayItemClients(paintInvalidationContainer);
1330 if (fullInvalidation)
1331 return;
1333 fullyInvalidatePaint(paintInvalidationContainer, PaintInvalidationSelection, oldSelectionRect, newSelectionRect);
1336 PaintInvalidationReason LayoutObject::invalidatePaintIfNeeded(PaintInvalidationState& paintInvalidationState, const LayoutBoxModelObject& paintInvalidationContainer)
1338 LayoutView* v = view();
1339 if (v->document().printing())
1340 return PaintInvalidationNone; // Don't invalidate paints if we're printing.
1342 const LayoutRect oldBounds = previousPaintInvalidationRect();
1343 const LayoutPoint oldLocation = RuntimeEnabledFeatures::slimmingPaintV2Enabled() ? LayoutPoint() : previousPositionFromPaintInvalidationBacking();
1344 LayoutRect newBounds = boundsRectForPaintInvalidation(&paintInvalidationContainer, &paintInvalidationState);
1345 LayoutPoint newLocation = RuntimeEnabledFeatures::slimmingPaintV2Enabled() ? LayoutPoint() : DeprecatedPaintLayer::positionFromPaintInvalidationBacking(this, &paintInvalidationContainer, &paintInvalidationState);
1347 // Composited scrolling should not be included in the bounds and position tracking, because the graphics layer backing the scroller
1348 // does not move on scroll.
1349 if (paintInvalidationContainer.usesCompositedScrolling() && &paintInvalidationContainer != this) {
1350 LayoutSize inverseOffset(toLayoutBox(&paintInvalidationContainer)->scrolledContentOffset());
1351 newLocation.move(inverseOffset);
1352 newBounds.move(inverseOffset);
1355 setPreviousPaintInvalidationRect(newBounds);
1356 if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled())
1357 setPreviousPositionFromPaintInvalidationBacking(newLocation);
1359 PaintInvalidationReason invalidationReason = paintInvalidationReason(paintInvalidationContainer, oldBounds, oldLocation, newBounds, newLocation);
1361 // We need to invalidate the selection before checking for whether we are doing a full invalidation.
1362 // This is because we need to update the old rect regardless.
1363 invalidateSelectionIfNeeded(paintInvalidationContainer, invalidationReason);
1365 TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"), "LayoutObject::invalidatePaintIfNeeded()",
1366 "object", this->debugName().ascii(),
1367 "info", jsonObjectForOldAndNewRects(oldBounds, oldLocation, newBounds, newLocation));
1369 bool boxDecorationBackgroundObscured = boxDecorationBackgroundIsKnownToBeObscured();
1370 if (!isFullPaintInvalidationReason(invalidationReason) && boxDecorationBackgroundObscured != m_bitfields.lastBoxDecorationBackgroundObscured())
1371 invalidationReason = PaintInvalidationBackgroundObscurationChange;
1372 m_bitfields.setLastBoxDecorationBackgroundObscured(boxDecorationBackgroundObscured);
1374 if (invalidationReason == PaintInvalidationNone) {
1375 // TODO(trchen): Currently we don't keep track of paint offset of layout objects.
1376 // There are corner cases that the display items need to be invalidated for paint offset
1377 // mutation, but incurs no pixel difference (i.e. bounds stay the same) so no rect-based
1378 // invalidation is issued. See crbug.com/508383 and crbug.com/515977.
1379 // This is a workaround to force display items to update paint offset.
1380 if (paintInvalidationState.forcedSubtreeInvalidationWithinContainer())
1381 invalidateDisplayItemClients(paintInvalidationContainer);
1383 return invalidationReason;
1386 invalidateDisplayItemClients(paintInvalidationContainer);
1388 if (invalidationReason == PaintInvalidationIncremental) {
1389 incrementallyInvalidatePaint(paintInvalidationContainer, oldBounds, newBounds, newLocation);
1390 return invalidationReason;
1393 fullyInvalidatePaint(paintInvalidationContainer, invalidationReason, oldBounds, newBounds);
1395 return invalidationReason;
1398 PaintInvalidationReason LayoutObject::paintInvalidationReason(const LayoutBoxModelObject& paintInvalidationContainer,
1399 const LayoutRect& oldBounds, const LayoutPoint& oldPositionFromPaintInvalidationBacking,
1400 const LayoutRect& newBounds, const LayoutPoint& newPositionFromPaintInvalidationBacking) const
1402 // First check for InvalidationLocationChange to avoid it from being hidden by other
1403 // invalidation reasons because we'll need to force check for paint invalidation for
1404 // children when location of this object changed.
1405 if (newPositionFromPaintInvalidationBacking != oldPositionFromPaintInvalidationBacking)
1406 return PaintInvalidationLocationChange;
1408 if (shouldDoFullPaintInvalidation())
1409 return m_bitfields.fullPaintInvalidationReason();
1411 // The outline may change shape because of position change of descendants. For simplicity,
1412 // just force full paint invalidation if this object is marked for checking paint invalidation
1413 // for any reason.
1414 if (styleRef().hasOutline())
1415 return PaintInvalidationOutline;
1417 // If the bounds are the same then we know that none of the statements below
1418 // can match, so we can early out since we will not need to do any
1419 // invalidation.
1420 if (oldBounds == newBounds)
1421 return PaintInvalidationNone;
1423 // If we shifted, we don't know the exact reason so we are conservative and trigger a full invalidation. Shifting could
1424 // be caused by some layout property (left / top) or some in-flow layoutObject inserted / removed before us in the tree.
1425 if (newBounds.location() != oldBounds.location())
1426 return PaintInvalidationBoundsChange;
1428 // This covers the case where we mark containing blocks for layout
1429 // and they change size but don't have anything to paint. This is
1430 // a pretty common case for <body> as we add / remove children
1431 // (and the default background is done by FrameView).
1432 if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled() && skipInvalidationWhenLaidOutChildren())
1433 return PaintInvalidationNone;
1435 // If the size is zero on one of our bounds then we know we're going to have
1436 // to do a full invalidation of either old bounds or new bounds. If we fall
1437 // into the incremental invalidation we'll issue two invalidations instead
1438 // of one.
1439 if (oldBounds.isEmpty())
1440 return PaintInvalidationBecameVisible;
1441 if (newBounds.isEmpty())
1442 return PaintInvalidationBecameInvisible;
1444 return PaintInvalidationIncremental;
1447 void LayoutObject::adjustInvalidationRectForCompositedScrolling(LayoutRect& rect, const LayoutBoxModelObject& paintInvalidationContainer) const
1449 if (paintInvalidationContainer.usesCompositedScrolling() && &paintInvalidationContainer != this) {
1450 LayoutSize offset(-toLayoutBox(&paintInvalidationContainer)->scrolledContentOffset());
1451 rect.move(offset);
1455 LayoutRect LayoutObject::previousPaintInvalidationRectIncludingCompositedScrolling(const LayoutBoxModelObject& paintInvalidationContainer) const
1457 LayoutRect invalidationRect = previousPaintInvalidationRect();
1458 adjustInvalidationRectForCompositedScrolling(invalidationRect, paintInvalidationContainer);
1459 return invalidationRect;
1462 void LayoutObject::adjustPreviousPaintInvalidationForScrollIfNeeded(const DoubleSize& scrollDelta)
1464 if (containerForPaintInvalidation()->usesCompositedScrolling())
1465 return;
1466 m_previousPaintInvalidationRect.move(LayoutSize(scrollDelta));
1469 void LayoutObject::incrementallyInvalidatePaint(const LayoutBoxModelObject& paintInvalidationContainer, const LayoutRect& oldBounds, const LayoutRect& newBounds, const LayoutPoint& positionFromPaintInvalidationBacking)
1471 ASSERT(oldBounds.location() == newBounds.location());
1473 LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1474 if (deltaRight > 0) {
1475 LayoutRect invalidationRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height());
1476 adjustInvalidationRectForCompositedScrolling(invalidationRect, paintInvalidationContainer);
1477 invalidatePaintUsingContainer(paintInvalidationContainer, invalidationRect, PaintInvalidationIncremental);
1478 } else if (deltaRight < 0) {
1479 LayoutRect invalidationRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height());
1480 adjustInvalidationRectForCompositedScrolling(invalidationRect, paintInvalidationContainer);
1481 invalidatePaintUsingContainer(paintInvalidationContainer, invalidationRect, PaintInvalidationIncremental);
1484 LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1485 if (deltaBottom > 0) {
1486 LayoutRect invalidationRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom);
1487 adjustInvalidationRectForCompositedScrolling(invalidationRect, paintInvalidationContainer);
1488 invalidatePaintUsingContainer(paintInvalidationContainer, invalidationRect, PaintInvalidationIncremental);
1489 } else if (deltaBottom < 0) {
1490 LayoutRect invalidationRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom);
1491 adjustInvalidationRectForCompositedScrolling(invalidationRect, paintInvalidationContainer);
1492 invalidatePaintUsingContainer(paintInvalidationContainer, invalidationRect, PaintInvalidationIncremental);
1496 void LayoutObject::fullyInvalidatePaint(const LayoutBoxModelObject& paintInvalidationContainer, PaintInvalidationReason invalidationReason, const LayoutRect& oldBounds, const LayoutRect& newBounds)
1498 // Otherwise do full paint invalidation.
1499 LayoutRect invalidationRect = oldBounds;
1500 adjustInvalidationRectForCompositedScrolling(invalidationRect, paintInvalidationContainer);
1501 invalidatePaintUsingContainer(paintInvalidationContainer, invalidationRect, invalidationReason);
1502 if (newBounds != oldBounds) {
1503 invalidationRect = newBounds;
1504 adjustInvalidationRectForCompositedScrolling(invalidationRect, paintInvalidationContainer);
1505 invalidatePaintUsingContainer(paintInvalidationContainer, invalidationRect, invalidationReason);
1509 void LayoutObject::invalidatePaintForOverflow()
1513 void LayoutObject::invalidatePaintForOverflowIfNeeded()
1515 if (shouldInvalidateOverflowForPaint())
1516 invalidatePaintForOverflow();
1519 LayoutRect LayoutObject::absoluteClippedOverflowRect() const
1521 return clippedOverflowRectForPaintInvalidation(view());
1524 LayoutRect LayoutObject::clippedOverflowRectForPaintInvalidation(const LayoutBoxModelObject*, const PaintInvalidationState*) const
1526 ASSERT_NOT_REACHED();
1527 return LayoutRect();
1530 void LayoutObject::mapRectToPaintInvalidationBacking(const LayoutBoxModelObject* paintInvalidationContainer, LayoutRect& rect, const PaintInvalidationState* paintInvalidationState) const
1532 if (paintInvalidationContainer == this)
1533 return;
1535 if (paintInvalidationState && paintInvalidationState->canMapToContainer(paintInvalidationContainer)) {
1536 rect.move(paintInvalidationState->paintOffset());
1537 if (paintInvalidationState->isClipped())
1538 rect.intersect(paintInvalidationState->clipRect());
1539 return;
1542 if (LayoutObject* o = parent()) {
1543 if (o->hasOverflowClip()) {
1544 LayoutBox* boxParent = toLayoutBox(o);
1545 boxParent->applyCachedClipAndScrollOffsetForPaintInvalidation(rect);
1546 if (rect.isEmpty())
1547 return;
1550 o->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, paintInvalidationState);
1554 void LayoutObject::dirtyLinesFromChangedChild(LayoutObject*)
1558 #ifndef NDEBUG
1560 void LayoutObject::showTreeForThis() const
1562 if (node())
1563 node()->showTreeForThis();
1566 void LayoutObject::showLayoutTreeForThis() const
1568 showLayoutTree(this, 0);
1571 void LayoutObject::showLineTreeForThis() const
1573 if (containingBlock())
1574 containingBlock()->showLineTreeAndMark(0, 0, 0, 0, this);
1577 void LayoutObject::showLayoutObject() const
1579 showLayoutObject(0);
1582 void LayoutObject::showLayoutObject(int printedCharacters) const
1584 printedCharacters += fprintf(stderr, "%s %p", decoratedName().ascii().data(), this);
1586 if (isText() && toLayoutText(this)->isTextFragment())
1587 printedCharacters += fprintf(stderr, " \"%s\" ", toLayoutText(this)->text().ascii().data());
1589 if (virtualContinuation())
1590 printedCharacters += fprintf(stderr, " continuation=%p", virtualContinuation());
1592 if (node()) {
1593 if (printedCharacters)
1594 for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1595 fputc(' ', stderr);
1596 fputc('\t', stderr);
1597 node()->showNode();
1598 } else {
1599 fputc('\n', stderr);
1603 void LayoutObject::showLayoutTreeAndMark(const LayoutObject* markedObject1, const char* markedLabel1, const LayoutObject* markedObject2, const char* markedLabel2, int depth) const
1605 int printedCharacters = 0;
1606 if (markedObject1 == this && markedLabel1)
1607 printedCharacters += fprintf(stderr, "%s", markedLabel1);
1608 if (markedObject2 == this && markedLabel2)
1609 printedCharacters += fprintf(stderr, "%s", markedLabel2);
1610 for (; printedCharacters < depth * 2; printedCharacters++)
1611 fputc(' ', stderr);
1613 showLayoutObject(printedCharacters);
1615 for (const LayoutObject* child = slowFirstChild(); child; child = child->nextSibling())
1616 child->showLayoutTreeAndMark(markedObject1, markedLabel1, markedObject2, markedLabel2, depth + 1);
1619 #endif // NDEBUG
1621 bool LayoutObject::isSelectable() const
1623 return !isInert() && !(style()->userSelect() == SELECT_NONE && style()->userModify() == READ_ONLY);
1626 Color LayoutObject::selectionBackgroundColor() const
1628 if (!isSelectable())
1629 return Color::transparent;
1631 if (RefPtr<ComputedStyle> pseudoStyle = getUncachedPseudoStyleFromParentOrShadowHost())
1632 return resolveColor(*pseudoStyle, CSSPropertyBackgroundColor).blendWithWhite();
1633 return frame()->selection().isFocusedAndActive() ?
1634 LayoutTheme::theme().activeSelectionBackgroundColor() :
1635 LayoutTheme::theme().inactiveSelectionBackgroundColor();
1638 Color LayoutObject::selectionColor(int colorProperty, const GlobalPaintFlags globalPaintFlags) const
1640 // If the element is unselectable, or we are only painting the selection,
1641 // don't override the foreground color with the selection foreground color.
1642 if (!isSelectable() || (globalPaintFlags & GlobalPaintSelectionOnly))
1643 return resolveColor(colorProperty);
1645 if (RefPtr<ComputedStyle> pseudoStyle = getUncachedPseudoStyleFromParentOrShadowHost())
1646 return resolveColor(*pseudoStyle, colorProperty);
1647 if (!LayoutTheme::theme().supportsSelectionForegroundColors())
1648 return resolveColor(colorProperty);
1649 return frame()->selection().isFocusedAndActive() ?
1650 LayoutTheme::theme().activeSelectionForegroundColor() :
1651 LayoutTheme::theme().inactiveSelectionForegroundColor();
1654 Color LayoutObject::selectionForegroundColor(const GlobalPaintFlags globalPaintFlags) const
1656 return selectionColor(CSSPropertyWebkitTextFillColor, globalPaintFlags);
1659 Color LayoutObject::selectionEmphasisMarkColor(const GlobalPaintFlags globalPaintFlags) const
1661 return selectionColor(CSSPropertyWebkitTextEmphasisColor, globalPaintFlags);
1664 void LayoutObject::selectionStartEnd(int& spos, int& epos) const
1666 view()->selectionStartEnd(spos, epos);
1669 // Called when an object that was floating or positioned becomes a normal flow object
1670 // again. We have to make sure the layout tree updates as needed to accommodate the new
1671 // normal flow object.
1672 static inline void handleDynamicFloatPositionChange(LayoutObject* object)
1674 // We have gone from not affecting the inline status of the parent flow to suddenly
1675 // having an impact. See if there is a mismatch between the parent flow's
1676 // childrenInline() state and our state.
1677 object->setInline(object->style()->isDisplayInlineType());
1678 if (object->isInline() != object->parent()->childrenInline()) {
1679 if (!object->isInline()) {
1680 toLayoutBoxModelObject(object->parent())->childBecameNonInline(object);
1681 } else {
1682 // An anonymous block must be made to wrap this inline.
1683 LayoutBlock* block = toLayoutBlock(object->parent())->createAnonymousBlock();
1684 LayoutObjectChildList* childlist = object->parent()->virtualChildren();
1685 childlist->insertChildNode(object->parent(), block, object);
1686 block->children()->appendChildNode(block, childlist->removeChildNode(object->parent(), object));
1691 StyleDifference LayoutObject::adjustStyleDifference(StyleDifference diff) const
1693 if (diff.transformChanged() && isSVG())
1694 diff.setNeedsFullLayout();
1696 // If transform changed, and the layer does not paint into its own separate backing, then we need to invalidate paints.
1697 if (diff.transformChanged()) {
1698 // Text nodes share style with their parents but transforms don't apply to them,
1699 // hence the !isText() check.
1700 if (!isText() && (!hasLayer() || !toLayoutBoxModelObject(this)->layer()->hasStyleDeterminedDirectCompositingReasons()))
1701 diff.setNeedsPaintInvalidationLayer();
1704 // If opacity or zIndex changed, and the layer does not paint into its own separate backing, then we need to invalidate paints (also
1705 // ignoring text nodes)
1706 if (diff.opacityChanged() || diff.zIndexChanged()) {
1707 if (!isText() && (!hasLayer() || !toLayoutBoxModelObject(this)->layer()->hasStyleDeterminedDirectCompositingReasons()))
1708 diff.setNeedsPaintInvalidationLayer();
1711 // If filter changed, and the layer does not paint into its own separate backing or it paints with filters, then we need to invalidate paints.
1712 if (diff.filterChanged() && hasLayer()) {
1713 DeprecatedPaintLayer* layer = toLayoutBoxModelObject(this)->layer();
1714 if (!layer->hasStyleDeterminedDirectCompositingReasons() || layer->paintsWithFilters())
1715 diff.setNeedsPaintInvalidationLayer();
1718 // If backdrop filter changed, and the layer does not paint into its own separate backing or it paints with filters, then we need to invalidate paints.
1719 if (diff.backdropFilterChanged() && hasLayer()) {
1720 DeprecatedPaintLayer* layer = toLayoutBoxModelObject(this)->layer();
1721 if (!layer->hasStyleDeterminedDirectCompositingReasons() || layer->paintsWithBackdropFilters())
1722 diff.setNeedsPaintInvalidationLayer();
1725 if (diff.textOrColorChanged() && !diff.needsPaintInvalidation()) {
1726 if (style()->hasBorder() || style()->hasOutline()
1727 || style()->isBackgroundColorCurrentColor()
1728 || (isText() && !toLayoutText(this)->isAllCollapsibleWhitespace()))
1729 diff.setNeedsPaintInvalidationObject();
1732 // The answer to layerTypeRequired() for plugins, iframes, and canvas can change without the actual
1733 // style changing, since it depends on whether we decide to composite these elements. When the
1734 // layer status of one of these elements changes, we need to force a layout.
1735 if (!diff.needsFullLayout() && style() && isBoxModelObject()) {
1736 bool requiresLayer = toLayoutBoxModelObject(this)->layerTypeRequired() != NoDeprecatedPaintLayer;
1737 if (hasLayer() != requiresLayer)
1738 diff.setNeedsFullLayout();
1741 // If we have no layer(), just treat a PaintInvalidationLayer hint as a normal paint invalidation.
1742 if (diff.needsPaintInvalidationLayer() && !hasLayer()) {
1743 diff.clearNeedsPaintInvalidation();
1744 diff.setNeedsPaintInvalidationObject();
1747 return diff;
1750 void LayoutObject::setPseudoStyle(PassRefPtr<ComputedStyle> pseudoStyle)
1752 ASSERT(pseudoStyle->styleType() == BEFORE || pseudoStyle->styleType() == AFTER || pseudoStyle->styleType() == FIRST_LETTER);
1754 // FIXME: We should consider just making all pseudo items use an inherited style.
1756 // Images are special and must inherit the pseudoStyle so the width and height of
1757 // the pseudo element doesn't change the size of the image. In all other cases we
1758 // can just share the style.
1760 // Quotes are also LayoutInline, so we need to create an inherited style to avoid
1761 // getting an inline with positioning or an invalid display.
1763 if (isImage() || isQuote()) {
1764 RefPtr<ComputedStyle> style = ComputedStyle::create();
1765 style->inheritFrom(*pseudoStyle);
1766 setStyle(style.release());
1767 return;
1770 setStyle(pseudoStyle);
1773 void LayoutObject::firstLineStyleDidChange(const ComputedStyle& oldStyle, const ComputedStyle& newStyle)
1775 StyleDifference diff = oldStyle.visualInvalidationDiff(newStyle);
1776 if (diff.hasDifference()) {
1777 // TODO(rune@opera.com): We should use the diff to determine whether a repaint vs. layout
1778 // is needed, but for now just assume a layout will be required. The diff code
1779 // in LayoutObject::setStyle would need to be factored out so that it could be reused.
1780 setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(LayoutInvalidationReason::StyleChange);
1784 void LayoutObject::markContainingBlocksForOverflowRecalc()
1786 for (LayoutBlock* container = containingBlock(); container && !container->childNeedsOverflowRecalcAfterStyleChange(); container = container->containingBlock())
1787 container->setChildNeedsOverflowRecalcAfterStyleChange();
1790 void LayoutObject::setNeedsOverflowRecalcAfterStyleChange()
1792 bool neededRecalc = needsOverflowRecalcAfterStyleChange();
1793 setSelfNeedsOverflowRecalcAfterStyleChange();
1794 if (!neededRecalc)
1795 markContainingBlocksForOverflowRecalc();
1798 void LayoutObject::setStyle(PassRefPtr<ComputedStyle> style)
1800 ASSERT(style);
1802 if (m_style == style) {
1803 // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
1804 // style sharing is disabled for them. That should ensure that we never hit this code path.
1805 ASSERT(!isLayoutIFrame() && !isEmbeddedObject() && !isCanvas());
1806 return;
1809 StyleDifference diff;
1810 if (m_style)
1811 diff = m_style->visualInvalidationDiff(*style);
1813 diff = adjustStyleDifference(diff);
1815 styleWillChange(diff, *style);
1817 RefPtr<ComputedStyle> oldStyle = m_style.release();
1818 setStyleInternal(style);
1820 updateFillImages(oldStyle ? &oldStyle->backgroundLayers() : 0, m_style->backgroundLayers());
1821 updateFillImages(oldStyle ? &oldStyle->maskLayers() : 0, m_style->maskLayers());
1823 updateImage(oldStyle ? oldStyle->borderImage().image() : 0, m_style->borderImage().image());
1824 updateImage(oldStyle ? oldStyle->maskBoxImage().image() : 0, m_style->maskBoxImage().image());
1826 updateShapeImage(oldStyle ? oldStyle->shapeOutside() : 0, m_style->shapeOutside());
1828 bool doesNotNeedLayoutOrPaintInvalidation = !m_parent;
1830 styleDidChange(diff, oldStyle.get());
1832 // FIXME: |this| might be destroyed here. This can currently happen for a LayoutTextFragment when
1833 // its first-letter block gets an update in LayoutTextFragment::styleDidChange. For LayoutTextFragment(s),
1834 // we will safely bail out with the doesNotNeedLayoutOrPaintInvalidation flag. We might want to broaden
1835 // this condition in the future as we move layoutObject changes out of layout and into style changes.
1836 if (doesNotNeedLayoutOrPaintInvalidation)
1837 return;
1839 // Now that the layer (if any) has been updated, we need to adjust the diff again,
1840 // check whether we should layout now, and decide if we need to invalidate paints.
1841 StyleDifference updatedDiff = adjustStyleDifference(diff);
1843 if (!diff.needsFullLayout()) {
1844 if (updatedDiff.needsFullLayout())
1845 setNeedsLayoutAndPrefWidthsRecalc(LayoutInvalidationReason::StyleChange);
1846 else if (updatedDiff.needsPositionedMovementLayout())
1847 setNeedsPositionedMovementLayout();
1850 if (diff.transformChanged() && !needsLayout()) {
1851 if (LayoutBlock* container = containingBlock())
1852 container->setNeedsOverflowRecalcAfterStyleChange();
1855 if (updatedDiff.needsPaintInvalidationLayer())
1856 setShouldDoFullPaintInvalidationIncludingNonCompositingDescendants();
1857 else if (diff.needsPaintInvalidationObject() || updatedDiff.needsPaintInvalidationObject())
1858 setShouldDoFullPaintInvalidation();
1861 void LayoutObject::styleWillChange(StyleDifference diff, const ComputedStyle& newStyle)
1863 if (m_style) {
1864 // If our z-index changes value or our visibility changes,
1865 // we need to dirty our stacking context's z-order list.
1866 bool visibilityChanged = m_style->visibility() != newStyle.visibility()
1867 || m_style->zIndex() != newStyle.zIndex()
1868 || m_style->hasAutoZIndex() != newStyle.hasAutoZIndex();
1869 if (visibilityChanged) {
1870 document().setAnnotatedRegionsDirty(true);
1871 if (AXObjectCache* cache = document().existingAXObjectCache())
1872 cache->childrenChanged(parent());
1875 // Keep layer hierarchy visibility bits up to date if visibility changes.
1876 if (m_style->visibility() != newStyle.visibility()) {
1877 // We might not have an enclosing layer yet because we might not be in the tree.
1878 if (DeprecatedPaintLayer* layer = enclosingLayer())
1879 layer->potentiallyDirtyVisibleContentStatus(newStyle.visibility());
1882 if (isFloating() && (m_style->floating() != newStyle.floating())) {
1883 // For changes in float styles, we need to conceivably remove ourselves
1884 // from the floating objects list.
1885 toLayoutBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1886 } else if (isOutOfFlowPositioned() && (m_style->position() != newStyle.position())) {
1887 // For changes in positioning styles, we need to conceivably remove ourselves
1888 // from the positioned objects list.
1889 toLayoutBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1892 s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
1893 && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
1894 && parent() && (parent()->isLayoutBlockFlow() || parent()->isLayoutInline());
1896 // Clearing these bits is required to avoid leaving stale layoutObjects.
1897 // FIXME: We shouldn't need that hack if our logic was totally correct.
1898 if (diff.needsLayout()) {
1899 setFloating(false);
1900 clearPositionedState();
1902 } else {
1903 s_affectsParentBlock = false;
1906 // Elements with non-auto touch-action will send a SetTouchAction message
1907 // on touchstart in EventHandler::handleTouchEvent, and so effectively have
1908 // a touchstart handler that must be reported.
1910 // Since a CSS property cannot be applied directly to a text node, a
1911 // handler will have already been added for its parent so ignore it.
1912 TouchAction oldTouchAction = m_style ? m_style->touchAction() : TouchActionAuto;
1913 if (node() && !node()->isTextNode() && (oldTouchAction == TouchActionAuto) != (newStyle.touchAction() == TouchActionAuto)) {
1914 EventHandlerRegistry& registry = document().frameHost()->eventHandlerRegistry();
1915 if (newStyle.touchAction() != TouchActionAuto)
1916 registry.didAddEventHandler(*node(), EventHandlerRegistry::TouchEvent);
1917 else
1918 registry.didRemoveEventHandler(*node(), EventHandlerRegistry::TouchEvent);
1922 static bool areNonIdenticalCursorListsEqual(const ComputedStyle* a, const ComputedStyle* b)
1924 ASSERT(a->cursors() != b->cursors());
1925 return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
1928 static inline bool areCursorsEqual(const ComputedStyle* a, const ComputedStyle* b)
1930 return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
1933 void LayoutObject::styleDidChange(StyleDifference diff, const ComputedStyle* oldStyle)
1935 if (s_affectsParentBlock)
1936 handleDynamicFloatPositionChange(this);
1938 if (!m_parent)
1939 return;
1941 if (diff.needsFullLayout()) {
1942 LayoutCounter::layoutObjectStyleChanged(*this, oldStyle, *m_style);
1944 // If the object already needs layout, then setNeedsLayout won't do
1945 // any work. But if the containing block has changed, then we may need
1946 // to mark the new containing blocks for layout. The change that can
1947 // directly affect the containing block of this object is a change to
1948 // the position style.
1949 if (needsLayout() && oldStyle->position() != m_style->position())
1950 markContainerChainForLayout();
1952 // Ditto.
1953 if (needsOverflowRecalcAfterStyleChange() && oldStyle->position() != m_style->position())
1954 markContainingBlocksForOverflowRecalc();
1956 setNeedsLayoutAndPrefWidthsRecalc(LayoutInvalidationReason::StyleChange);
1957 } else if (diff.needsPositionedMovementLayout()) {
1958 setNeedsPositionedMovementLayout();
1961 // Don't check for paint invalidation here; we need to wait until the layer has been
1962 // updated by subclasses before we know if we have to invalidate paints (in setStyle()).
1964 if (oldStyle && !areCursorsEqual(oldStyle, style())) {
1965 if (LocalFrame* frame = this->frame()) {
1966 // Cursor update scheduling is done by the local root, which is the main frame if there
1967 // are no RemoteFrame ancestors in the frame tree. Use of localFrameRoot() is
1968 // discouraged but will change when cursor update scheduling is moved from EventHandler
1969 // to PageEventHandler.
1970 frame->localFrameRoot()->eventHandler().scheduleCursorUpdate();
1975 void LayoutObject::propagateStyleToAnonymousChildren(bool blockChildrenOnly)
1977 // FIXME: We could save this call when the change only affected non-inherited properties.
1978 for (LayoutObject* child = slowFirstChild(); child; child = child->nextSibling()) {
1979 if (!child->isAnonymous() || child->style()->styleType() != NOPSEUDO)
1980 continue;
1982 if (blockChildrenOnly && !child->isLayoutBlock())
1983 continue;
1985 if (child->isLayoutFullScreen() || child->isLayoutFullScreenPlaceholder())
1986 continue;
1988 RefPtr<ComputedStyle> newStyle = ComputedStyle::createAnonymousStyleWithDisplay(styleRef(), child->style()->display());
1990 // Preserve the position style of anonymous block continuations as they can have relative position when
1991 // they contain block descendants of relative positioned inlines.
1992 if (child->isInFlowPositioned() && toLayoutBlock(child)->isAnonymousBlockContinuation())
1993 newStyle->setPosition(child->style()->position());
1995 updateAnonymousChildStyle(*child, *newStyle);
1997 child->setStyle(newStyle.release());
2001 void LayoutObject::updateFillImages(const FillLayer* oldLayers, const FillLayer& newLayers)
2003 // Optimize the common case
2004 if (oldLayers && !oldLayers->next() && !newLayers.next() && (oldLayers->image() == newLayers.image()))
2005 return;
2007 // Go through the new layers and addClients first, to avoid removing all clients of an image.
2008 for (const FillLayer* currNew = &newLayers; currNew; currNew = currNew->next()) {
2009 if (currNew->image())
2010 currNew->image()->addClient(this);
2013 for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
2014 if (currOld->image())
2015 currOld->image()->removeClient(this);
2019 void LayoutObject::updateImage(StyleImage* oldImage, StyleImage* newImage)
2021 if (oldImage != newImage) {
2022 if (oldImage)
2023 oldImage->removeClient(this);
2024 if (newImage)
2025 newImage->addClient(this);
2029 void LayoutObject::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
2031 if (oldShapeValue || newShapeValue)
2032 updateImage(oldShapeValue ? oldShapeValue->image() : 0, newShapeValue ? newShapeValue->image() : 0);
2035 LayoutRect LayoutObject::viewRect() const
2037 return view()->viewRect();
2040 FloatPoint LayoutObject::localToAbsolute(const FloatPoint& localPoint, MapCoordinatesFlags mode) const
2042 TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2043 mapLocalToContainer(0, transformState, mode | ApplyContainerFlip);
2044 transformState.flatten();
2046 return transformState.lastPlanarPoint();
2049 FloatPoint LayoutObject::absoluteToLocal(const FloatPoint& containerPoint, MapCoordinatesFlags mode) const
2051 TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
2052 mapAbsoluteToLocalPoint(mode, transformState);
2053 transformState.flatten();
2055 return transformState.lastPlanarPoint();
2058 FloatQuad LayoutObject::absoluteToLocalQuad(const FloatQuad& quad, MapCoordinatesFlags mode) const
2060 TransformState transformState(TransformState::UnapplyInverseTransformDirection, quad.boundingBox().center(), quad);
2061 mapAbsoluteToLocalPoint(mode, transformState);
2062 transformState.flatten();
2063 return transformState.lastPlanarQuad();
2066 void LayoutObject::mapLocalToContainer(const LayoutBoxModelObject* paintInvalidationContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed, const PaintInvalidationState* paintInvalidationState) const
2068 if (paintInvalidationContainer == this)
2069 return;
2071 LayoutObject* o = parent();
2072 if (!o)
2073 return;
2075 // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2076 LayoutPoint centerPoint = roundedLayoutPoint(transformState.mappedPoint());
2077 if (mode & ApplyContainerFlip && o->isBox()) {
2078 if (o->style()->isFlippedBlocksWritingMode())
2079 transformState.move(toLayoutBox(o)->flipForWritingMode(roundedLayoutPoint(transformState.mappedPoint())) - centerPoint);
2080 mode &= ~ApplyContainerFlip;
2083 transformState.move(o->columnOffset(roundedLayoutPoint(transformState.mappedPoint())));
2085 if (o->hasOverflowClip())
2086 transformState.move(-toLayoutBox(o)->scrolledContentOffset());
2088 o->mapLocalToContainer(paintInvalidationContainer, transformState, mode, wasFixed, paintInvalidationState);
2091 const LayoutObject* LayoutObject::pushMappingToContainer(const LayoutBoxModelObject* ancestorToStopAt, LayoutGeometryMap& geometryMap) const
2093 ASSERT_NOT_REACHED();
2094 return nullptr;
2097 void LayoutObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2099 LayoutObject* o = parent();
2100 if (o) {
2101 o->mapAbsoluteToLocalPoint(mode, transformState);
2102 if (o->hasOverflowClip())
2103 transformState.move(toLayoutBox(o)->scrolledContentOffset());
2107 bool LayoutObject::shouldUseTransformFromContainer(const LayoutObject* containerObject) const
2109 // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
2110 // so check the layer's transform directly.
2111 return (hasLayer() && toLayoutBoxModelObject(this)->layer()->transform()) || (containerObject && containerObject->style()->hasPerspective());
2114 void LayoutObject::getTransformFromContainer(const LayoutObject* containerObject, const LayoutSize& offsetInContainer, TransformationMatrix& transform) const
2116 transform.makeIdentity();
2117 transform.translate(offsetInContainer.width().toFloat(), offsetInContainer.height().toFloat());
2118 DeprecatedPaintLayer* layer = hasLayer() ? toLayoutBoxModelObject(this)->layer() : 0;
2119 if (layer && layer->transform())
2120 transform.multiply(layer->currentTransform());
2122 if (containerObject && containerObject->hasLayer() && containerObject->style()->hasPerspective()) {
2123 // Perpsective on the container affects us, so we have to factor it in here.
2124 ASSERT(containerObject->hasLayer());
2125 FloatPoint perspectiveOrigin = toLayoutBoxModelObject(containerObject)->layer()->perspectiveOrigin();
2127 TransformationMatrix perspectiveMatrix;
2128 perspectiveMatrix.applyPerspective(containerObject->style()->perspective());
2130 transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
2131 transform = perspectiveMatrix * transform;
2132 transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
2136 FloatQuad LayoutObject::localToContainerQuad(const FloatQuad& localQuad, const LayoutBoxModelObject* paintInvalidationContainer, MapCoordinatesFlags mode, bool* wasFixed) const
2138 // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
2139 // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
2140 TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), localQuad);
2141 mapLocalToContainer(paintInvalidationContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
2142 transformState.flatten();
2144 return transformState.lastPlanarQuad();
2147 FloatPoint LayoutObject::localToContainerPoint(const FloatPoint& localPoint, const LayoutBoxModelObject* paintInvalidationContainer, MapCoordinatesFlags mode, bool* wasFixed, const PaintInvalidationState* paintInvalidationState) const
2149 TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2150 mapLocalToContainer(paintInvalidationContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed, paintInvalidationState);
2151 transformState.flatten();
2153 return transformState.lastPlanarPoint();
2156 FloatPoint LayoutObject::localToInvalidationBackingPoint(const LayoutPoint& localPoint, DeprecatedPaintLayer** backingLayer)
2158 const LayoutBoxModelObject& paintInvalidationContainer = containerForPaintInvalidationOnRootedTree();
2159 ASSERT(paintInvalidationContainer.layer());
2161 if (backingLayer)
2162 *backingLayer = paintInvalidationContainer.layer();
2163 FloatPoint containerPoint = localToContainerPoint(FloatPoint(localPoint), &paintInvalidationContainer, TraverseDocumentBoundaries);
2165 // A layoutObject can have no invalidation backing if it is from a detached frame,
2166 // or when forced compositing is disabled.
2167 if (paintInvalidationContainer.layer()->compositingState() == NotComposited)
2168 return containerPoint;
2170 DeprecatedPaintLayer::mapPointToPaintBackingCoordinates(&paintInvalidationContainer, containerPoint);
2171 return containerPoint;
2174 LayoutSize LayoutObject::offsetFromContainer(const LayoutObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
2176 ASSERT(o == container());
2178 LayoutSize offset = o->columnOffset(point);
2180 if (o->hasOverflowClip())
2181 offset -= toLayoutBox(o)->scrolledContentOffset();
2183 if (offsetDependsOnPoint)
2184 *offsetDependsOnPoint = o->isLayoutFlowThread();
2186 return offset;
2189 LayoutSize LayoutObject::offsetFromAncestorContainer(const LayoutObject* container) const
2191 if (container == this)
2192 return LayoutSize();
2194 LayoutSize offset;
2195 LayoutPoint referencePoint;
2196 const LayoutObject* currContainer = this;
2197 do {
2198 const LayoutObject* nextContainer = currContainer->container();
2199 ASSERT(nextContainer); // This means we reached the top without finding container.
2200 if (!nextContainer)
2201 break;
2202 ASSERT(!currContainer->hasTransformRelatedProperty());
2203 LayoutSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
2204 offset += currentOffset;
2205 referencePoint.move(currentOffset);
2206 currContainer = nextContainer;
2207 } while (currContainer != container);
2209 return offset;
2212 LayoutRect LayoutObject::localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine)
2214 if (extraWidthToEndOfLine)
2215 *extraWidthToEndOfLine = 0;
2217 return LayoutRect();
2220 void LayoutObject::computeLayerHitTestRects(LayerHitTestRects& layerRects) const
2222 // Figure out what layer our container is in. Any offset (or new layer) for this
2223 // layoutObject within it's container will be applied in addLayerHitTestRects.
2224 LayoutPoint layerOffset;
2225 const DeprecatedPaintLayer* currentLayer = nullptr;
2227 if (!hasLayer()) {
2228 LayoutObject* container = this->container();
2229 currentLayer = container->enclosingLayer();
2230 if (container && currentLayer->layoutObject() != container) {
2231 layerOffset.move(container->offsetFromAncestorContainer(currentLayer->layoutObject()));
2232 // If the layer itself is scrolled, we have to undo the subtraction of its scroll
2233 // offset since we want the offset relative to the scrolling content, not the
2234 // element itself.
2235 if (currentLayer->layoutObject()->hasOverflowClip())
2236 layerOffset.move(currentLayer->layoutBox()->scrolledContentOffset());
2240 this->addLayerHitTestRects(layerRects, currentLayer, layerOffset, LayoutRect());
2243 void LayoutObject::addLayerHitTestRects(LayerHitTestRects& layerRects, const DeprecatedPaintLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
2245 ASSERT(currentLayer);
2246 ASSERT(currentLayer == this->enclosingLayer());
2248 // Compute the rects for this layoutObject only and add them to the results.
2249 // Note that we could avoid passing the offset and instead adjust each result, but this
2250 // seems slightly simpler.
2251 Vector<LayoutRect> ownRects;
2252 LayoutRect newContainerRect;
2253 computeSelfHitTestRects(ownRects, layerOffset);
2255 // When we get to have a lot of rects on a layer, the performance cost of tracking those
2256 // rects outweighs the benefit of doing compositor thread hit testing.
2257 // FIXME: This limit needs to be low due to the O(n^2) algorithm in
2258 // WebLayer::setTouchEventHandlerRegion - crbug.com/300282.
2259 const size_t maxRectsPerLayer = 100;
2261 LayerHitTestRects::iterator iter = layerRects.find(currentLayer);
2262 Vector<LayoutRect>* iterValue;
2263 if (iter == layerRects.end())
2264 iterValue = &layerRects.add(currentLayer, Vector<LayoutRect>()).storedValue->value;
2265 else
2266 iterValue = &iter->value;
2267 for (size_t i = 0; i < ownRects.size(); i++) {
2268 if (!containerRect.contains(ownRects[i])) {
2269 iterValue->append(ownRects[i]);
2270 if (iterValue->size() > maxRectsPerLayer) {
2271 // Just mark the entire layer instead, and switch to walking the layer
2272 // tree instead of the layout tree.
2273 layerRects.remove(currentLayer);
2274 currentLayer->addLayerHitTestRects(layerRects);
2275 return;
2277 if (newContainerRect.isEmpty())
2278 newContainerRect = ownRects[i];
2281 if (newContainerRect.isEmpty())
2282 newContainerRect = containerRect;
2284 // If it's possible for children to have rects outside our bounds, then we need to descend into
2285 // the children and compute them.
2286 // Ideally there would be other cases where we could detect that children couldn't have rects
2287 // outside our bounds and prune the tree walk.
2288 // Note that we don't use Region here because Union is O(N) - better to just keep a list of
2289 // partially redundant rectangles. If we find examples where this is expensive, then we could
2290 // rewrite Region to be more efficient. See https://bugs.webkit.org/show_bug.cgi?id=100814.
2291 if (!isLayoutView()) {
2292 for (LayoutObject* curr = slowFirstChild(); curr; curr = curr->nextSibling()) {
2293 curr->addLayerHitTestRects(layerRects, currentLayer, layerOffset, newContainerRect);
2298 bool LayoutObject::isRooted() const
2300 const LayoutObject* object = this;
2301 while (object->parent() && !object->hasLayer())
2302 object = object->parent();
2303 if (object->hasLayer())
2304 return toLayoutBoxModelObject(object)->layer()->root()->isRootLayer();
2305 return false;
2308 RespectImageOrientationEnum LayoutObject::shouldRespectImageOrientation() const
2310 // Respect the image's orientation if it's being used as a full-page image or
2311 // it's an <img> and the setting to respect it everywhere is set or the <img>
2312 // has image-orientation: from-image style. FIXME: crbug.com/498233
2313 if (document().isImageDocument())
2314 return RespectImageOrientation;
2316 if (!isHTMLImageElement(node()))
2317 return DoNotRespectImageOrientation;
2319 if (document().settings() && document().settings()->shouldRespectImageOrientation())
2320 return RespectImageOrientation;
2322 if (style() && style()->respectImageOrientation() == RespectImageOrientation)
2323 return RespectImageOrientation;
2325 return DoNotRespectImageOrientation;
2328 LayoutObject* LayoutObject::container(const LayoutBoxModelObject* paintInvalidationContainer, bool* paintInvalidationContainerSkipped) const
2330 if (paintInvalidationContainerSkipped)
2331 *paintInvalidationContainerSkipped = false;
2333 LayoutObject* o = parent();
2335 if (isTextOrSVGChild())
2336 return o;
2338 EPosition pos = m_style->position();
2339 if (pos == FixedPosition)
2340 return containerForFixedPosition(paintInvalidationContainer, paintInvalidationContainerSkipped);
2342 if (pos == AbsolutePosition) {
2343 // We technically just want our containing block, but
2344 // we may not have one if we're part of an uninstalled
2345 // subtree. We'll climb as high as we can though.
2346 while (o) {
2347 if (o->style()->position() != StaticPosition)
2348 break;
2350 if (o->canContainFixedPositionObjects())
2351 break;
2353 if (paintInvalidationContainerSkipped && o == paintInvalidationContainer)
2354 *paintInvalidationContainerSkipped = true;
2356 o = o->parent();
2358 } else if (isColumnSpanAll()) {
2359 LayoutObject* multicolContainer = spannerPlaceholder()->container();
2360 if (paintInvalidationContainerSkipped && paintInvalidationContainer) {
2361 // We jumped directly from the spanner to the multicol container. Need to check if
2362 // we skipped |paintInvalidationContainer| on the way.
2363 for (LayoutObject* walker = parent(); walker && walker != multicolContainer; walker = walker->parent()) {
2364 if (walker == paintInvalidationContainer) {
2365 *paintInvalidationContainerSkipped = true;
2366 break;
2370 return multicolContainer;
2373 return o;
2376 LayoutObject* LayoutObject::containerCrossingFrameBoundaries() const
2378 return isLayoutView() ? frame()->ownerLayoutObject() : container();
2381 bool LayoutObject::isSelectionBorder() const
2383 SelectionState st = selectionState();
2384 return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
2387 inline void LayoutObject::clearLayoutRootIfNeeded() const
2389 if (FrameView* view = frameView()) {
2390 if (!documentBeingDestroyed())
2391 view->clearLayoutSubtreeRoot(*this);
2395 void LayoutObject::willBeDestroyed()
2397 // Destroy any leftover anonymous children.
2398 LayoutObjectChildList* children = virtualChildren();
2399 if (children)
2400 children->destroyLeftoverChildren();
2402 if (LocalFrame* frame = this->frame()) {
2403 // If this layoutObject is being autoscrolled, stop the autoscrolling.
2404 if (frame->page())
2405 frame->page()->autoscrollController().stopAutoscrollIfNeeded(this);
2408 // For accessibility management, notify the parent of the imminent change to its child set.
2409 // We do it now, before remove(), while the parent pointer is still available.
2410 if (AXObjectCache* cache = document().existingAXObjectCache())
2411 cache->childrenChanged(this->parent());
2413 remove();
2415 // The remove() call above may invoke axObjectCache()->childrenChanged() on the parent, which may require the AX layout
2416 // object for this layoutObject. So we remove the AX layout object now, after the layoutObject is removed.
2417 if (AXObjectCache* cache = document().existingAXObjectCache())
2418 cache->remove(this);
2420 // If this layoutObject had a parent, remove should have destroyed any counters
2421 // attached to this layoutObject and marked the affected other counters for
2422 // reevaluation. This apparently redundant check is here for the case when
2423 // this layoutObject had no parent at the time remove() was called.
2425 if (hasCounterNodeMap())
2426 LayoutCounter::destroyCounterNodes(*this);
2428 // Remove the handler if node had touch-action set. Handlers are not added
2429 // for text nodes so don't try removing for one too. Need to check if
2430 // m_style is null in cases of partial construction. Any handler we added
2431 // previously may have already been removed by the Document independently.
2432 if (node() && !node()->isTextNode() && m_style && m_style->touchAction() != TouchActionAuto) {
2433 EventHandlerRegistry& registry = document().frameHost()->eventHandlerRegistry();
2434 if (registry.eventHandlerTargets(EventHandlerRegistry::TouchEvent)->contains(node()))
2435 registry.didRemoveEventHandler(*node(), EventHandlerRegistry::TouchEvent);
2438 setAncestorLineBoxDirty(false);
2440 if (selectionPaintInvalidationMap)
2441 selectionPaintInvalidationMap->remove(this);
2443 clearLayoutRootIfNeeded();
2445 if (m_style) {
2446 for (const FillLayer* bgLayer = &m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
2447 if (StyleImage* backgroundImage = bgLayer->image())
2448 backgroundImage->removeClient(this);
2451 for (const FillLayer* maskLayer = &m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
2452 if (StyleImage* maskImage = maskLayer->image())
2453 maskImage->removeClient(this);
2456 if (StyleImage* borderImage = m_style->borderImage().image())
2457 borderImage->removeClient(this);
2459 if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
2460 maskBoxImage->removeClient(this);
2462 removeShapeImageClient(m_style->shapeOutside());
2464 ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeLayoutObject(this);
2466 if (frameView())
2467 setIsSlowRepaintObject(false);
2470 void LayoutObject::insertedIntoTree()
2472 // FIXME: We should ASSERT(isRooted()) here but generated content makes some out-of-order insertion.
2474 // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
2475 // and don't have a layer attached to ourselves.
2476 DeprecatedPaintLayer* layer = nullptr;
2477 if (slowFirstChild() || hasLayer()) {
2478 layer = parent()->enclosingLayer();
2479 addLayers(layer);
2482 // If |this| is visible but this object was not, tell the layer it has some visible content
2483 // that needs to be drawn and layer visibility optimization can't be used
2484 if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2485 if (!layer)
2486 layer = parent()->enclosingLayer();
2487 if (layer)
2488 layer->dirtyVisibleContentStatus();
2491 if (parent()->childrenInline())
2492 parent()->dirtyLinesFromChangedChild(this);
2494 if (LayoutFlowThread* flowThread = flowThreadContainingBlock())
2495 flowThread->flowThreadDescendantWasInserted(this);
2498 void LayoutObject::willBeRemovedFromTree()
2500 // FIXME: We should ASSERT(isRooted()) but we have some out-of-order removals which would need to be fixed first.
2502 // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
2503 DeprecatedPaintLayer* layer = nullptr;
2504 if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2505 layer = parent()->enclosingLayer();
2506 if (layer)
2507 layer->dirtyVisibleContentStatus();
2510 // Keep our layer hierarchy updated.
2511 if (slowFirstChild() || hasLayer()) {
2512 if (!layer)
2513 layer = parent()->enclosingLayer();
2514 removeLayers(layer);
2517 if (isOutOfFlowPositioned() && parent()->childrenInline())
2518 parent()->dirtyLinesFromChangedChild(this);
2520 removeFromLayoutFlowThread();
2522 // Update cached boundaries in SVG layoutObjects if a child is removed.
2523 if (parent()->isSVG())
2524 parent()->setNeedsBoundariesUpdate();
2527 void LayoutObject::removeFromLayoutFlowThread()
2529 if (!isInsideFlowThread())
2530 return;
2532 // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2533 // It's only until later when we actually destroy it and remove all the children from it.
2534 // Currently, that happens for firstLetter elements and list markers.
2535 // Pass in the flow thread so that we don't have to look it up for all the children.
2536 // If we're a column spanner, we need to use our parent to find the flow thread, since a spanner
2537 // doesn't have the flow thread in its containing block chain. We still need to notify the flow
2538 // thread when the layoutObject removed happens to be a spanner, so that we get rid of the spanner
2539 // placeholder, and column sets around the placeholder get merged.
2540 LayoutFlowThread* flowThread = isColumnSpanAll() ? parent()->flowThreadContainingBlock() : flowThreadContainingBlock();
2541 removeFromLayoutFlowThreadRecursive(flowThread);
2544 void LayoutObject::removeFromLayoutFlowThreadRecursive(LayoutFlowThread* layoutFlowThread)
2546 if (const LayoutObjectChildList* children = virtualChildren()) {
2547 for (LayoutObject* child = children->firstChild(); child; child = child->nextSibling()) {
2548 if (child->isLayoutFlowThread())
2549 continue; // Don't descend into inner fragmentation contexts.
2550 child->removeFromLayoutFlowThreadRecursive(child->isLayoutFlowThread() ? toLayoutFlowThread(child) : layoutFlowThread);
2554 if (layoutFlowThread && layoutFlowThread != this)
2555 layoutFlowThread->flowThreadDescendantWillBeRemoved(this);
2556 setIsInsideFlowThread(false);
2557 RELEASE_ASSERT(!spannerPlaceholder());
2560 void LayoutObject::destroyAndCleanupAnonymousWrappers()
2562 // If the tree is destroyed, there is no need for a clean-up phase.
2563 if (documentBeingDestroyed()) {
2564 destroy();
2565 return;
2568 LayoutObject* destroyRoot = this;
2569 for (LayoutObject* destroyRootParent = destroyRoot->parent(); destroyRootParent && destroyRootParent->isAnonymous(); destroyRoot = destroyRootParent, destroyRootParent = destroyRootParent->parent()) {
2570 // Anonymous block continuations are tracked and destroyed elsewhere (see the bottom of LayoutBlock::removeChild)
2571 if (destroyRootParent->isLayoutBlock() && toLayoutBlock(destroyRootParent)->isAnonymousBlockContinuation())
2572 break;
2573 // A flow thread is tracked by its containing block. Whether its children are removed or not is irrelevant.
2574 if (destroyRootParent->isLayoutFlowThread())
2575 break;
2577 if (destroyRootParent->slowFirstChild() != destroyRoot || destroyRootParent->slowLastChild() != destroyRoot)
2578 break; // Need to keep the anonymous parent, since it won't become empty by the removal of this layoutObject.
2581 destroyRoot->destroy();
2583 // WARNING: |this| is deleted here.
2586 void LayoutObject::destroy()
2588 willBeDestroyed();
2589 delete this;
2592 void LayoutObject::removeShapeImageClient(ShapeValue* shapeValue)
2594 if (!shapeValue)
2595 return;
2596 if (StyleImage* shapeImage = shapeValue->image())
2597 shapeImage->removeClient(this);
2600 PositionWithAffinity LayoutObject::positionForPoint(const LayoutPoint&)
2602 return createPositionWithAffinity(caretMinOffset());
2605 void LayoutObject::updateDragState(bool dragOn)
2607 bool valueChanged = (dragOn != isDragging());
2608 setIsDragging(dragOn);
2609 if (valueChanged && node()) {
2610 if (node()->isElementNode() && toElement(node())->childrenOrSiblingsAffectedByDrag())
2611 node()->setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::Drag));
2612 else if (style()->affectedByDrag())
2613 node()->setNeedsStyleRecalc(LocalStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::Drag));
2615 for (LayoutObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
2616 curr->updateDragState(dragOn);
2619 CompositingState LayoutObject::compositingState() const
2621 return hasLayer() ? toLayoutBoxModelObject(this)->layer()->compositingState() : NotComposited;
2624 CompositingReasons LayoutObject::additionalCompositingReasons() const
2626 return CompositingReasonNone;
2629 bool LayoutObject::hitTest(HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
2631 bool inside = false;
2632 if (hitTestFilter != HitTestSelf) {
2633 // First test the foreground layer (lines and inlines).
2634 inside = nodeAtPoint(result, locationInContainer, accumulatedOffset, HitTestForeground);
2636 // Test floats next.
2637 if (!inside)
2638 inside = nodeAtPoint(result, locationInContainer, accumulatedOffset, HitTestFloat);
2640 // Finally test to see if the mouse is in the background (within a child block's background).
2641 if (!inside)
2642 inside = nodeAtPoint(result, locationInContainer, accumulatedOffset, HitTestChildBlockBackgrounds);
2645 // See if the mouse is inside us but not any of our descendants
2646 if (hitTestFilter != HitTestDescendants && !inside)
2647 inside = nodeAtPoint(result, locationInContainer, accumulatedOffset, HitTestBlockBackground);
2649 return inside;
2652 void LayoutObject::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
2654 if (result.innerNode())
2655 return;
2657 Node* node = this->node();
2659 // If we hit the anonymous layoutObjects inside generated content we should
2660 // actually hit the generated content so walk up to the PseudoElement.
2661 if (!node && parent() && parent()->isBeforeOrAfterContent()) {
2662 for (LayoutObject* layoutObject = parent(); layoutObject && !node; layoutObject = layoutObject->parent())
2663 node = layoutObject->node();
2666 if (node)
2667 result.setNodeAndPosition(node, point);
2670 bool LayoutObject::nodeAtPoint(HitTestResult&, const HitTestLocation& /*locationInContainer*/, const LayoutPoint& /*accumulatedOffset*/, HitTestAction)
2672 return false;
2675 void LayoutObject::scheduleRelayout()
2677 if (isLayoutView()) {
2678 FrameView* view = toLayoutView(this)->frameView();
2679 if (view)
2680 view->scheduleRelayout();
2681 } else {
2682 if (isRooted()) {
2683 if (LayoutView* layoutView = view()) {
2684 if (FrameView* frameView = layoutView->frameView())
2685 frameView->scheduleRelayoutOfSubtree(this);
2691 void LayoutObject::forceLayout()
2693 setSelfNeedsLayout(true);
2694 setShouldDoFullPaintInvalidation();
2695 layout();
2698 // FIXME: Does this do anything different than forceLayout given that we don't walk
2699 // the containing block chain. If not, we should change all callers to use forceLayout.
2700 void LayoutObject::forceChildLayout()
2702 setNormalChildNeedsLayout(true);
2703 layout();
2706 enum StyleCacheState {
2707 Cached,
2708 Uncached
2711 static PassRefPtr<ComputedStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const LayoutObject* layoutObject, ComputedStyle* style)
2713 const LayoutObject* layoutObjectForFirstLineStyle = layoutObject;
2714 if (layoutObject->isBeforeOrAfterContent())
2715 layoutObjectForFirstLineStyle = layoutObject->parent();
2717 if (layoutObjectForFirstLineStyle->isLayoutBlockFlow() || layoutObjectForFirstLineStyle->isLayoutButton()) {
2718 if (LayoutBlock* firstLineBlock = layoutObjectForFirstLineStyle->firstLineBlock()) {
2719 if (type == Cached)
2720 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
2721 return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == layoutObject ? style : 0);
2723 } else if (!layoutObjectForFirstLineStyle->isAnonymous() && layoutObjectForFirstLineStyle->isLayoutInline()
2724 && !layoutObjectForFirstLineStyle->node()->isFirstLetterPseudoElement()) {
2725 const ComputedStyle* parentStyle = layoutObjectForFirstLineStyle->parent()->firstLineStyle();
2726 if (parentStyle != layoutObjectForFirstLineStyle->parent()->style()) {
2727 if (type == Cached) {
2728 // A first-line style is in effect. Cache a first-line style for ourselves.
2729 layoutObjectForFirstLineStyle->mutableStyleRef().setHasPseudoStyle(FIRST_LINE_INHERITED);
2730 return layoutObjectForFirstLineStyle->getCachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle);
2732 return layoutObjectForFirstLineStyle->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), parentStyle, style);
2735 return nullptr;
2738 PassRefPtr<ComputedStyle> LayoutObject::uncachedFirstLineStyle(ComputedStyle* style) const
2740 if (!document().styleEngine().usesFirstLineRules())
2741 return nullptr;
2743 ASSERT(!isText());
2745 return firstLineStyleForCachedUncachedType(Uncached, this, style);
2748 ComputedStyle* LayoutObject::cachedFirstLineStyle() const
2750 ASSERT(document().styleEngine().usesFirstLineRules());
2752 if (RefPtr<ComputedStyle> style = firstLineStyleForCachedUncachedType(Cached, isText() ? parent() : this, m_style.get()))
2753 return style.get();
2755 return m_style.get();
2758 ComputedStyle* LayoutObject::getCachedPseudoStyle(PseudoId pseudo, const ComputedStyle* parentStyle) const
2760 if (pseudo < FIRST_INTERNAL_PSEUDOID && !style()->hasPseudoStyle(pseudo))
2761 return nullptr;
2763 ComputedStyle* cachedStyle = style()->getCachedPseudoStyle(pseudo);
2764 if (cachedStyle)
2765 return cachedStyle;
2767 RefPtr<ComputedStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
2768 if (result)
2769 return mutableStyleRef().addCachedPseudoStyle(result.release());
2770 return nullptr;
2773 PassRefPtr<ComputedStyle> LayoutObject::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, const ComputedStyle* parentStyle, const ComputedStyle* ownStyle) const
2775 if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style()->hasPseudoStyle(pseudoStyleRequest.pseudoId))
2776 return nullptr;
2778 if (!parentStyle) {
2779 ASSERT(!ownStyle);
2780 parentStyle = style();
2783 if (!node())
2784 return nullptr;
2786 Element* element = Traversal<Element>::firstAncestorOrSelf(*node());
2787 if (!element)
2788 return nullptr;
2790 if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
2791 RefPtr<ComputedStyle> result = document().ensureStyleResolver().styleForElement(element, parentStyle, DisallowStyleSharing);
2792 result->setStyleType(FIRST_LINE_INHERITED);
2793 return result.release();
2796 return document().ensureStyleResolver().pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
2799 PassRefPtr<ComputedStyle> LayoutObject::getUncachedPseudoStyleFromParentOrShadowHost() const
2801 if (!node())
2802 return nullptr;
2804 if (ShadowRoot* root = node()->containingShadowRoot()) {
2805 if (root->type() == ShadowRootType::UserAgent) {
2806 if (Element* shadowHost = node()->shadowHost()) {
2807 return shadowHost->layoutObject()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
2812 return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
2815 void LayoutObject::getTextDecorations(unsigned decorations, AppliedTextDecoration& underline, AppliedTextDecoration& overline, AppliedTextDecoration& linethrough, bool quirksMode, bool firstlineStyle)
2817 LayoutObject* curr = this;
2818 const ComputedStyle* styleToUse = nullptr;
2819 unsigned currDecs = TextDecorationNone;
2820 Color resultColor;
2821 TextDecorationStyle resultStyle;
2822 do {
2823 styleToUse = curr->style(firstlineStyle);
2824 currDecs = styleToUse->textDecoration();
2825 currDecs &= decorations;
2826 resultColor = styleToUse->visitedDependentColor(CSSPropertyTextDecorationColor);
2827 resultStyle = styleToUse->textDecorationStyle();
2828 // Parameter 'decorations' is cast as an int to enable the bitwise operations below.
2829 if (currDecs) {
2830 if (currDecs & TextDecorationUnderline) {
2831 decorations &= ~TextDecorationUnderline;
2832 underline.color = resultColor;
2833 underline.style = resultStyle;
2835 if (currDecs & TextDecorationOverline) {
2836 decorations &= ~TextDecorationOverline;
2837 overline.color = resultColor;
2838 overline.style = resultStyle;
2840 if (currDecs & TextDecorationLineThrough) {
2841 decorations &= ~TextDecorationLineThrough;
2842 linethrough.color = resultColor;
2843 linethrough.style = resultStyle;
2846 if (curr->isRubyText())
2847 return;
2848 curr = curr->parent();
2849 if (curr && curr->isAnonymousBlock() && toLayoutBlock(curr)->continuation())
2850 curr = toLayoutBlock(curr)->continuation();
2851 } while (curr && decorations && (!quirksMode || !curr->node() || (!isHTMLAnchorElement(*curr->node()) && !isHTMLFontElement(*curr->node()))));
2853 // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
2854 if (decorations && curr) {
2855 styleToUse = curr->style(firstlineStyle);
2856 resultColor = styleToUse->visitedDependentColor(CSSPropertyTextDecorationColor);
2857 if (decorations & TextDecorationUnderline) {
2858 underline.color = resultColor;
2859 underline.style = resultStyle;
2861 if (decorations & TextDecorationOverline) {
2862 overline.color = resultColor;
2863 overline.style = resultStyle;
2865 if (decorations & TextDecorationLineThrough) {
2866 linethrough.color = resultColor;
2867 linethrough.style = resultStyle;
2872 void LayoutObject::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
2874 // Convert the style regions to absolute coordinates.
2875 if (style()->visibility() != VISIBLE || !isBox())
2876 return;
2878 if (style()->getDraggableRegionMode() == DraggableRegionNone)
2879 return;
2881 LayoutBox* box = toLayoutBox(this);
2882 FloatRect localBounds(FloatPoint(), FloatSize(box->size()));
2883 FloatRect absBounds = localToAbsoluteQuad(localBounds).boundingBox();
2885 AnnotatedRegionValue region;
2886 region.draggable = style()->getDraggableRegionMode() == DraggableRegionDrag;
2887 region.bounds = LayoutRect(absBounds);
2888 regions.append(region);
2891 bool LayoutObject::willRenderImage(ImageResource*)
2893 // Without visibility we won't render (and therefore don't care about animation).
2894 if (style()->visibility() != VISIBLE)
2895 return false;
2897 // We will not render a new image when Active DOM is suspended
2898 if (document().activeDOMObjectsAreSuspended())
2899 return false;
2901 // If we're not in a window (i.e., we're dormant from being in a background tab)
2902 // then we don't want to render either.
2903 return document().view()->isVisible();
2906 bool LayoutObject::getImageAnimationPolicy(ImageResource*, ImageAnimationPolicy& policy)
2908 if (!document().settings())
2909 return false;
2910 policy = document().settings()->imageAnimationPolicy();
2911 return true;
2914 int LayoutObject::caretMinOffset() const
2916 return 0;
2919 int LayoutObject::caretMaxOffset() const
2921 if (isReplaced())
2922 return node() ? std::max(1U, node()->countChildren()) : 1;
2923 if (isHR())
2924 return 1;
2925 return 0;
2928 int LayoutObject::previousOffset(int current) const
2930 return current - 1;
2933 int LayoutObject::previousOffsetForBackwardDeletion(int current) const
2935 return current - 1;
2938 int LayoutObject::nextOffset(int current) const
2940 return current + 1;
2943 bool LayoutObject::isInert() const
2945 const LayoutObject* layoutObject = this;
2946 while (!layoutObject->node())
2947 layoutObject = layoutObject->parent();
2948 return layoutObject->node()->isInert();
2951 void LayoutObject::imageChanged(ImageResource* image, const IntRect* rect)
2953 ASSERT(m_node);
2954 imageChanged(static_cast<WrappedImagePtr>(image), rect);
2957 Element* LayoutObject::offsetParent() const
2959 if (isDocumentElement() || isBody())
2960 return nullptr;
2962 if (isOutOfFlowPositioned() && style()->position() == FixedPosition)
2963 return nullptr;
2965 float effectiveZoom = style()->effectiveZoom();
2966 Node* node = nullptr;
2967 for (LayoutObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
2968 // Spec: http://www.w3.org/TR/cssom-view/#offset-attributes
2970 node = ancestor->node();
2972 if (!node)
2973 continue;
2975 if (ancestor->isPositioned())
2976 break;
2978 if (isHTMLBodyElement(*node))
2979 break;
2981 if (!isPositioned() && (isHTMLTableElement(*node) || isHTMLTableCellElement(*node)))
2982 break;
2984 // Webkit specific extension where offsetParent stops at zoom level changes.
2985 if (effectiveZoom != ancestor->style()->effectiveZoom())
2986 break;
2989 return node && node->isElementNode() ? toElement(node) : nullptr;
2992 PositionWithAffinity LayoutObject::createPositionWithAffinity(int offset, TextAffinity affinity)
2994 // If this is a non-anonymous layoutObject in an editable area, then it's simple.
2995 if (Node* node = nonPseudoNode()) {
2996 if (!node->hasEditableStyle()) {
2997 // If it can be found, we prefer a visually equivalent position that is editable.
2998 const Position position = Position(node, offset);
2999 Position candidate = mostForwardCaretPosition(position, CanCrossEditingBoundary);
3000 if (candidate.anchorNode()->hasEditableStyle())
3001 return PositionWithAffinity(candidate, affinity);
3002 candidate = mostBackwardCaretPosition(position, CanCrossEditingBoundary);
3003 if (candidate.anchorNode()->hasEditableStyle())
3004 return PositionWithAffinity(candidate, affinity);
3006 // FIXME: Eliminate legacy editing positions
3007 return PositionWithAffinity(Position::editingPositionOf(node, offset), affinity);
3010 // We don't want to cross the boundary between editable and non-editable
3011 // regions of the document, but that is either impossible or at least
3012 // extremely unlikely in any normal case because we stop as soon as we
3013 // find a single non-anonymous layoutObject.
3015 // Find a nearby non-anonymous layoutObject.
3016 LayoutObject* child = this;
3017 while (LayoutObject* parent = child->parent()) {
3018 // Find non-anonymous content after.
3019 for (LayoutObject* layoutObject = child->nextInPreOrder(parent); layoutObject; layoutObject = layoutObject->nextInPreOrder(parent)) {
3020 if (Node* node = layoutObject->nonPseudoNode())
3021 return PositionWithAffinity(firstPositionInOrBeforeNode(node));
3024 // Find non-anonymous content before.
3025 for (LayoutObject* layoutObject = child->previousInPreOrder(); layoutObject; layoutObject = layoutObject->previousInPreOrder()) {
3026 if (layoutObject == parent)
3027 break;
3028 if (Node* node = layoutObject->nonPseudoNode())
3029 return PositionWithAffinity(lastPositionInOrAfterNode(node));
3032 // Use the parent itself unless it too is anonymous.
3033 if (Node* node = parent->nonPseudoNode())
3034 return PositionWithAffinity(firstPositionInOrBeforeNode(node));
3036 // Repeat at the next level up.
3037 child = parent;
3040 // Everything was anonymous. Give up.
3041 return PositionWithAffinity();
3044 PositionWithAffinity LayoutObject::createPositionWithAffinity(int offset)
3046 return createPositionWithAffinity(offset, TextAffinity::Downstream);
3049 PositionWithAffinity LayoutObject::createPositionWithAffinity(const Position& position)
3051 if (position.isNotNull())
3052 return PositionWithAffinity(position);
3054 ASSERT(!node());
3055 return createPositionWithAffinity(0);
3058 CursorDirective LayoutObject::getCursor(const LayoutPoint&, Cursor&) const
3060 return SetCursorBasedOnStyle;
3063 bool LayoutObject::canUpdateSelectionOnRootLineBoxes() const
3065 if (needsLayout())
3066 return false;
3068 const LayoutBlock* containingBlock = this->containingBlock();
3069 return containingBlock ? !containingBlock->needsLayout() : false;
3072 void LayoutObject::setNeedsBoundariesUpdate()
3074 if (LayoutObject* layoutObject = parent())
3075 layoutObject->setNeedsBoundariesUpdate();
3078 FloatRect LayoutObject::objectBoundingBox() const
3080 ASSERT_NOT_REACHED();
3081 return FloatRect();
3084 FloatRect LayoutObject::strokeBoundingBox() const
3086 ASSERT_NOT_REACHED();
3087 return FloatRect();
3090 // Returns the smallest rectangle enclosing all of the painted content
3091 // respecting clipping, masking, filters, opacity, stroke-width and markers
3092 FloatRect LayoutObject::paintInvalidationRectInLocalCoordinates() const
3094 ASSERT_NOT_REACHED();
3095 return FloatRect();
3098 AffineTransform LayoutObject::localTransform() const
3100 static const AffineTransform identity;
3101 return identity;
3104 const AffineTransform& LayoutObject::localToParentTransform() const
3106 static const AffineTransform identity;
3107 return identity;
3110 bool LayoutObject::nodeAtFloatPoint(HitTestResult&, const FloatPoint&, HitTestAction)
3112 ASSERT_NOT_REACHED();
3113 return false;
3116 bool LayoutObject::isRelayoutBoundaryForInspector() const
3118 return objectIsRelayoutBoundary(this);
3121 static PaintInvalidationReason documentLifecycleBasedPaintInvalidationReason(const DocumentLifecycle& documentLifecycle)
3123 switch (documentLifecycle.state()) {
3124 case DocumentLifecycle::InStyleRecalc:
3125 return PaintInvalidationStyleChange;
3126 case DocumentLifecycle::InPreLayout:
3127 case DocumentLifecycle::InPerformLayout:
3128 case DocumentLifecycle::AfterPerformLayout:
3129 return PaintInvalidationForcedByLayout;
3130 case DocumentLifecycle::InCompositingUpdate:
3131 return PaintInvalidationCompositingUpdate;
3132 default:
3133 return PaintInvalidationFull;
3137 inline void LayoutObject::markContainerChainForPaintInvalidation()
3139 // Setting layer-needs-repaint doesn't mean we'll fully repaint the layer, but
3140 // means we won't skip painting of the whole layer with a CachedSubsequenceDisplayItem.
3141 // This is to ensure we'll check paint offset changes of the objects on the layer.
3142 // We'll still use cached display items for non-invalidated objects on the layer.
3143 if (DeprecatedPaintLayer* enclosingLayer = this->enclosingLayer())
3144 enclosingLayer->setNeedsRepaint();
3146 for (LayoutObject* container = this->containerCrossingFrameBoundaries(); container && !container->shouldCheckForPaintInvalidationRegardlessOfPaintInvalidationState(); container = container->containerCrossingFrameBoundaries())
3147 container->m_bitfields.setChildShouldCheckForPaintInvalidation(true);
3150 void LayoutObject::setShouldInvalidateSelection()
3152 if (!canUpdateSelectionOnRootLineBoxes())
3153 return;
3155 m_bitfields.setShouldInvalidateSelection(true);
3156 markContainerChainForPaintInvalidation();
3159 void LayoutObject::setShouldDoFullPaintInvalidation(PaintInvalidationReason reason)
3161 // Only full invalidation reasons are allowed.
3162 ASSERT(isFullPaintInvalidationReason(reason));
3164 bool isUpgradingDelayedFullToFull = m_bitfields.fullPaintInvalidationReason() == PaintInvalidationDelayedFull && reason != PaintInvalidationDelayedFull;
3166 if (m_bitfields.fullPaintInvalidationReason() == PaintInvalidationNone || isUpgradingDelayedFullToFull) {
3167 if (reason == PaintInvalidationFull)
3168 reason = documentLifecycleBasedPaintInvalidationReason(document().lifecycle());
3169 m_bitfields.setFullPaintInvalidationReason(reason);
3172 if (!isUpgradingDelayedFullToFull) {
3173 ASSERT(document().lifecycle().state() != DocumentLifecycle::InPaintInvalidation);
3174 frame()->page()->animator().scheduleVisualUpdate(); // In case that this is called outside of FrameView::updateLayoutAndStyleForPainting().
3175 markContainerChainForPaintInvalidation();
3179 void LayoutObject::setMayNeedPaintInvalidation()
3181 if (mayNeedPaintInvalidation())
3182 return;
3183 m_bitfields.setMayNeedPaintInvalidation(true);
3184 markContainerChainForPaintInvalidation();
3185 frame()->page()->animator().scheduleVisualUpdate(); // In case that this is called outside of FrameView::updateLayoutAndStyleForPainting().
3188 void LayoutObject::clearPaintInvalidationState(const PaintInvalidationState& paintInvalidationState)
3190 // paintInvalidationStateIsDirty should be kept in sync with the
3191 // booleans that are cleared below.
3192 ASSERT(paintInvalidationState.forcedSubtreeInvalidationWithinContainer() || paintInvalidationStateIsDirty());
3193 clearShouldDoFullPaintInvalidation();
3194 m_bitfields.setChildShouldCheckForPaintInvalidation(false);
3195 m_bitfields.setNeededLayoutBecauseOfChildren(false);
3196 m_bitfields.setShouldInvalidateOverflowForPaint(false);
3197 m_bitfields.setMayNeedPaintInvalidation(false);
3198 m_bitfields.setShouldInvalidateSelection(false);
3201 bool LayoutObject::isAllowedToModifyLayoutTreeStructure(Document& document)
3203 return DeprecatedDisableModifyLayoutTreeStructureAsserts::canModifyLayoutTreeStateInAnyState()
3204 || document.lifecycle().stateAllowsLayoutTreeMutations();
3207 DeprecatedDisableModifyLayoutTreeStructureAsserts::DeprecatedDisableModifyLayoutTreeStructureAsserts()
3208 : m_disabler(gModifyLayoutTreeStructureAnyState, true)
3212 bool DeprecatedDisableModifyLayoutTreeStructureAsserts::canModifyLayoutTreeStateInAnyState()
3214 return gModifyLayoutTreeStructureAnyState;
3217 DisablePaintInvalidationStateAsserts::DisablePaintInvalidationStateAsserts()
3218 : m_disabler(gDisablePaintInvalidationStateAsserts, true)
3222 namespace {
3224 // TODO(trchen): Use std::function<void, LayoutObject&> and lambda when available.
3225 class LayoutObjectTraversalFunctor {
3226 public:
3227 virtual void operator()(LayoutObject&) const = 0;
3230 void traverseNonCompositingDescendants(LayoutObject&, const LayoutObjectTraversalFunctor&);
3232 void findNonCompositedDescendantLayerToTraverse(LayoutObject& object, const LayoutObjectTraversalFunctor& functor)
3234 LayoutObject* descendant = object.nextInPreOrder(&object);
3235 while (descendant) {
3236 // Case 1: If the descendant has no layer, keep searching until we find a layer.
3237 if (!descendant->hasLayer()) {
3238 descendant = descendant->nextInPreOrder(&object);
3239 continue;
3241 // Case 2: The descendant has a layer and is not composited.
3242 // The invalidation container of its subtree is our parent,
3243 // thus recur into the subtree.
3244 if (!descendant->isPaintInvalidationContainer()) {
3245 traverseNonCompositingDescendants(*descendant, functor);
3246 descendant = descendant->nextInPreOrderAfterChildren(&object);
3247 continue;
3249 // Case 3: The descendant is an invalidation container and is a stacking context.
3250 // No objects in the subtree can have invalidation container outside of it,
3251 // thus skip the whole subtree.
3252 if (descendant->styleRef().isStackingContext()) {
3253 descendant = descendant->nextInPreOrderAfterChildren(&object);
3254 continue;
3256 // Case 4: The descendant is an invalidation container but not a stacking context.
3257 // This is the same situation as the root, thus keep searching.
3258 descendant = descendant->nextInPreOrder(&object);
3262 void traverseNonCompositingDescendants(LayoutObject& object, const LayoutObjectTraversalFunctor& functor)
3264 functor(object);
3265 LayoutObject* descendant = object.nextInPreOrder(&object);
3266 while (descendant) {
3267 if (!descendant->isPaintInvalidationContainer()) {
3268 functor(*descendant);
3269 descendant = descendant->nextInPreOrder(&object);
3270 continue;
3272 if (descendant->styleRef().isStackingContext()) {
3273 descendant = descendant->nextInPreOrderAfterChildren(&object);
3274 continue;
3277 // If a paint invalidation container is not a stacking context,
3278 // some of its descendants may belong to the parent container.
3279 findNonCompositedDescendantLayerToTraverse(*descendant, functor);
3280 descendant = descendant->nextInPreOrderAfterChildren(&object);
3284 } // unnamed namespace
3286 void LayoutObject::invalidateDisplayItemClientForNonCompositingDescendantsOf(const LayoutObject& object) const
3288 // Not using enclosingCompositedContainer() directly because this object may be in an orphaned subtree.
3289 const DeprecatedPaintLayer* enclosingLayer = this->enclosingLayer();
3290 if (!enclosingLayer)
3291 return;
3293 // This is valid because we want to invalidate the client in the display item list of the current backing.
3294 DisableCompositingQueryAsserts disabler;
3295 const DeprecatedPaintLayer* paintInvalidationLayer = enclosingLayer->enclosingLayerForPaintInvalidationCrossingFrameBoundaries();
3296 if (!paintInvalidationLayer)
3297 return;
3299 class Functor : public LayoutObjectTraversalFunctor {
3300 public:
3301 explicit Functor(const LayoutBoxModelObject& paintInvalidationContainer) : m_paintInvalidationContainer(paintInvalidationContainer) { }
3302 void operator()(LayoutObject& object) const override
3304 object.invalidateDisplayItemClients(m_paintInvalidationContainer);
3306 private:
3307 const LayoutBoxModelObject& m_paintInvalidationContainer;
3310 const LayoutBoxModelObject& paintInvalidationContainer = *paintInvalidationLayer->layoutObject();
3311 traverseNonCompositingDescendants(const_cast<LayoutObject&>(object), Functor(paintInvalidationContainer));
3314 void LayoutObject::invalidatePaintIncludingNonCompositingDescendants()
3316 class Functor : public LayoutObjectTraversalFunctor {
3317 public:
3318 explicit Functor(const LayoutBoxModelObject& paintInvalidationContainer) : m_paintInvalidationContainer(paintInvalidationContainer) { }
3319 void operator()(LayoutObject& object) const override
3321 LayoutRect invalidationRect = object.previousPaintInvalidationRect();
3322 object.adjustInvalidationRectForCompositedScrolling(invalidationRect, m_paintInvalidationContainer);
3323 object.invalidatePaintUsingContainer(m_paintInvalidationContainer, invalidationRect, PaintInvalidationLayer);
3324 object.invalidateDisplayItemClients(m_paintInvalidationContainer);
3326 private:
3327 const LayoutBoxModelObject& m_paintInvalidationContainer;
3330 // Since we're only painting non-composited layers, we know that they all share the same paintInvalidationContainer.
3331 const LayoutBoxModelObject& paintInvalidationContainer = containerForPaintInvalidationOnRootedTree();
3332 traverseNonCompositingDescendants(*this, Functor(paintInvalidationContainer));
3335 // FIXME: If we had a flag to force invalidations in a whole subtree, we could get rid of this function (crbug.com/410097).
3336 void LayoutObject::setShouldDoFullPaintInvalidationIncludingNonCompositingDescendants()
3338 class Functor : public LayoutObjectTraversalFunctor {
3339 public:
3340 void operator()(LayoutObject& object) const override
3342 object.setShouldDoFullPaintInvalidation();
3346 // Need to access the current compositing status.
3347 DisableCompositingQueryAsserts disabler;
3348 traverseNonCompositingDescendants(*this, Functor());
3351 void LayoutObject::setIsSlowRepaintObject(bool isSlowRepaintObject)
3353 ASSERT(frameView());
3354 if (m_bitfields.isSlowRepaintObject() == isSlowRepaintObject)
3355 return;
3356 m_bitfields.setIsSlowRepaintObject(isSlowRepaintObject);
3357 if (isSlowRepaintObject)
3358 frameView()->addSlowRepaintObject();
3359 else
3360 frameView()->removeSlowRepaintObject();
3363 } // namespace blink
3365 #ifndef NDEBUG
3367 void showTree(const blink::LayoutObject* object)
3369 if (object)
3370 object->showTreeForThis();
3371 else
3372 fprintf(stderr, "Cannot showTree. Root is (nil)\n");
3375 void showLineTree(const blink::LayoutObject* object)
3377 if (object)
3378 object->showLineTreeForThis();
3379 else
3380 fprintf(stderr, "Cannot showLineTree. Root is (nil)\n");
3383 void showLayoutTree(const blink::LayoutObject* object1)
3385 showLayoutTree(object1, 0);
3388 void showLayoutTree(const blink::LayoutObject* object1, const blink::LayoutObject* object2)
3390 if (object1) {
3391 const blink::LayoutObject* root = object1;
3392 while (root->parent())
3393 root = root->parent();
3394 root->showLayoutTreeAndMark(object1, "*", object2, "-", 0);
3395 } else {
3396 fprintf(stderr, "Cannot showLayoutTree. Root is (nil)\n");
3400 #endif