2 * Copyright (C) 2013 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "core/rendering/TextAutosizer.h"
34 #include "core/dom/Document.h"
35 #include "core/frame/FrameView.h"
36 #include "core/frame/LocalFrame.h"
37 #include "core/frame/Settings.h"
38 #include "core/html/HTMLTextAreaElement.h"
39 #include "core/page/Page.h"
40 #include "core/rendering/InlineIterator.h"
41 #include "core/rendering/RenderBlock.h"
42 #include "core/rendering/RenderListItem.h"
43 #include "core/rendering/RenderListMarker.h"
44 #include "core/rendering/RenderTableCell.h"
45 #include "core/rendering/RenderView.h"
47 #ifdef AUTOSIZING_DOM_DEBUG_INFO
48 #include "core/dom/ExecutionContextTask.h"
53 #ifdef AUTOSIZING_DOM_DEBUG_INFO
54 class WriteDebugInfoTask : public ExecutionContextTask {
56 WriteDebugInfoTask(PassRefPtrWillBeRawPtr<Element> element, AtomicString value)
62 virtual void performTask(ExecutionContext*)
64 m_element->setAttribute("data-autosizing", m_value, ASSERT_NO_EXCEPTION);
68 RefPtrWillBePersistent<Element> m_element;
72 static void writeDebugInfo(RenderObject* renderer, const AtomicString& output)
74 Node* node = renderer->node();
77 if (node->isDocumentNode())
78 node = toDocument(node)->documentElement();
79 if (!node->isElementNode())
81 node->document().postTask(adoptPtr(new WriteDebugInfoTask(toElement(node), output)));
84 void TextAutosizer::writeClusterDebugInfo(Cluster* cluster)
86 String explanation = "";
87 if (cluster->m_flags & SUPPRESSING) {
88 explanation = "[suppressed]";
89 } else if (!(cluster->m_flags & (INDEPENDENT | WIDER_OR_NARROWER))) {
90 explanation = "[inherited]";
91 } else if (cluster->m_supercluster) {
92 explanation = "[supercluster]";
93 } else if (!clusterHasEnoughTextToAutosize(cluster)) {
94 explanation = "[insufficient-text]";
96 const RenderBlock* widthProvider = clusterWidthProvider(cluster->m_root);
97 if (cluster->m_hasTableAncestor && cluster->m_multiplier < multiplierFromBlock(widthProvider)) {
98 explanation = "[table-ancestor-limited]";
100 explanation = String::format("[from width %d of %s]",
101 static_cast<int>(widthFromBlock(widthProvider)), widthProvider->debugName().utf8().data());
104 String pageInfo = "";
105 if (cluster->m_root->isRenderView()) {
106 pageInfo = String::format("; pageinfo: bm %f * (lw %d / fw %d)",
107 m_pageInfo.m_baseMultiplier, m_pageInfo.m_layoutWidth, m_pageInfo.m_frameWidth);
109 float multiplier = cluster->m_flags & SUPPRESSING ? 1.0 : cluster->m_multiplier;
110 writeDebugInfo(const_cast<RenderBlock*>(cluster->m_root),
111 AtomicString(String::format("cluster: %f %s%s", multiplier,
112 explanation.utf8().data(), pageInfo.utf8().data())));
116 static const RenderObject* parentElementRenderer(const RenderObject* renderer)
118 // At style recalc, the renderer's parent may not be attached,
119 // so we need to obtain this from the DOM tree.
120 const Node* node = renderer->node();
124 for (node = node->parentNode(); node; node = node->parentNode()) {
125 if (node->isElementNode())
126 return node->renderer();
131 static bool isNonTextAreaFormControl(const RenderObject* renderer)
133 const Node* node = renderer ? renderer->node() : 0;
134 if (!node || !node->isElementNode())
136 const Element* element = toElement(node);
138 return (element->isFormControlElement() && !isHTMLTextAreaElement(element));
141 static bool isPotentialClusterRoot(const RenderObject* renderer)
143 // "Potential cluster roots" are the smallest unit for which we can
144 // enable/disable text autosizing.
145 // - Must not be inline, as different multipliers on one line looks terrible.
146 // Exceptions are inline-block and alike elements (inline-table, -webkit-inline-*),
147 // as they often contain entire multi-line columns of text.
148 // - Must not be normal list items, as items in the same list should look
149 // consistent, unless they are floating or position:absolute/fixed.
150 Node* node = renderer->generatingNode();
151 if (node && !node->hasChildren())
153 if (!renderer->isRenderBlock())
155 if (renderer->isInline() && !renderer->style()->isDisplayReplacedType())
157 if (renderer->isListItem())
158 return (renderer->isFloating() || renderer->isOutOfFlowPositioned());
163 static bool isIndependentDescendant(const RenderBlock* renderer)
165 ASSERT(isPotentialClusterRoot(renderer));
167 RenderBlock* containingBlock = renderer->containingBlock();
168 return renderer->isRenderView()
169 || renderer->isFloating()
170 || renderer->isOutOfFlowPositioned()
171 || renderer->isTableCell()
172 || renderer->isTableCaption()
173 || renderer->isFlexibleBoxIncludingDeprecated()
174 || renderer->hasColumns()
175 || (containingBlock && containingBlock->isHorizontalWritingMode() != renderer->isHorizontalWritingMode())
176 || renderer->style()->isDisplayReplacedType()
177 || renderer->isTextArea()
178 || renderer->style()->userModify() != READ_ONLY;
181 static bool blockIsRowOfLinks(const RenderBlock* block)
183 // A "row of links" is a block for which:
184 // 1. It does not contain non-link text elements longer than 3 characters
185 // 2. It contains a minimum of 3 inline links and all links should
186 // have the same specified font size.
187 // 3. It should not contain <br> elements.
188 // 4. It should contain only inline elements unless they are containers,
189 // children of link elements or children of sub-containers.
191 RenderObject* renderer = block->firstChild();
192 float matchingFontSize = -1;
195 if (!isPotentialClusterRoot(renderer)) {
196 if (renderer->isText() && toRenderText(renderer)->text().impl()->stripWhiteSpace()->length() > 3)
198 if (!renderer->isInline() || renderer->isBR())
201 if (renderer->style()->isLink()) {
203 if (matchingFontSize < 0)
204 matchingFontSize = renderer->style()->specifiedFontSize();
205 else if (matchingFontSize != renderer->style()->specifiedFontSize())
208 // Skip traversing descendants of the link.
209 renderer = renderer->nextInPreOrderAfterChildren(block);
212 renderer = renderer->nextInPreOrder(block);
215 return (linkCount >= 3);
218 static bool blockHeightConstrained(const RenderBlock* block)
220 // FIXME: Propagate constrainedness down the tree, to avoid inefficiently walking back up from each box.
221 // FIXME: This code needs to take into account vertical writing modes.
222 // FIXME: Consider additional heuristics, such as ignoring fixed heights if the content is already overflowing before autosizing kicks in.
223 for (; block; block = block->containingBlock()) {
224 RenderStyle* style = block->style();
225 if (style->overflowY() >= OSCROLL)
227 if (style->height().isSpecified() || style->maxHeight().isSpecified() || block->isOutOfFlowPositioned()) {
228 // Some sites (e.g. wikipedia) set their html and/or body elements to height:100%,
229 // without intending to constrain the height of the content within them.
230 return !block->isDocumentElement() && !block->isBody();
232 if (block->isFloating())
238 static bool blockOrImmediateChildrenAreFormControls(const RenderBlock* block)
240 if (isNonTextAreaFormControl(block))
242 const RenderObject* renderer = block->firstChild();
244 if (isNonTextAreaFormControl(renderer))
246 renderer = renderer->nextSibling();
252 // Some blocks are not autosized even if their parent cluster wants them to.
253 static bool blockSuppressesAutosizing(const RenderBlock* block)
255 if (blockOrImmediateChildrenAreFormControls(block))
258 if (blockIsRowOfLinks(block))
261 // Don't autosize block-level text that can't wrap (as it's likely to
262 // expand sideways and break the page's layout).
263 if (!block->style()->autoWrap())
266 if (blockHeightConstrained(block))
272 static bool hasExplicitWidth(const RenderBlock* block)
274 // FIXME: This heuristic may need to be expanded to other ways a block can be wider or narrower
275 // than its parent containing block.
276 return block->style() && block->style()->width().isSpecified();
279 TextAutosizer::TextAutosizer(const Document* document)
280 : m_document(document)
281 , m_firstBlockToBeginLayout(0)
283 , m_blocksThatHaveBegunLayout()
287 , m_fingerprintMapper()
289 , m_updatePageInfoDeferred(false)
293 void TextAutosizer::record(const RenderBlock* block)
295 if (!m_pageInfo.m_settingEnabled)
298 ASSERT(!m_blocksThatHaveBegunLayout.contains(block));
300 if (!classifyBlock(block, INDEPENDENT | EXPLICIT_WIDTH))
303 if (Fingerprint fingerprint = computeFingerprint(block))
304 m_fingerprintMapper.addTentativeClusterRoot(block, fingerprint);
307 void TextAutosizer::destroy(const RenderBlock* block)
309 if (!m_pageInfo.m_settingEnabled)
312 ASSERT(!m_blocksThatHaveBegunLayout.contains(block));
314 if (m_fingerprintMapper.remove(block) && m_firstBlockToBeginLayout) {
315 // RenderBlock with a fingerprint was destroyed during layout.
316 // Clear the cluster stack and the supercluster map to avoid stale pointers.
317 // Speculative fix for http://crbug.com/369485.
318 m_firstBlockToBeginLayout = 0;
319 m_clusterStack.clear();
320 m_superclusters.clear();
324 TextAutosizer::BeginLayoutBehavior TextAutosizer::prepareForLayout(const RenderBlock* block)
327 m_blocksThatHaveBegunLayout.add(block);
330 if (!m_firstBlockToBeginLayout) {
331 m_firstBlockToBeginLayout = block;
332 prepareClusterStack(block->parent());
333 } else if (block == currentCluster()->m_root) {
334 // Ignore beginLayout on the same block twice.
335 // This can happen with paginated overflow.
339 return ContinueLayout;
342 void TextAutosizer::prepareClusterStack(const RenderObject* renderer)
346 prepareClusterStack(renderer->parent());
348 if (renderer->isRenderBlock()) {
349 const RenderBlock* block = toRenderBlock(renderer);
351 m_blocksThatHaveBegunLayout.add(block);
353 if (Cluster* cluster = maybeCreateCluster(block))
354 m_clusterStack.append(adoptPtr(cluster));
358 void TextAutosizer::beginLayout(RenderBlock* block)
360 ASSERT(shouldHandleLayout());
362 if (prepareForLayout(block) == StopLayout)
365 if (Cluster* cluster = maybeCreateCluster(block))
366 m_clusterStack.append(adoptPtr(cluster));
368 // Cells in auto-layout tables are handled separately by inflateAutoTable.
369 bool isAutoTableCell = block->isTableCell() && !toRenderTableCell(block)->table()->style()->isFixedTableLayout();
370 if (!isAutoTableCell && !m_clusterStack.isEmpty())
374 void TextAutosizer::inflateListItem(RenderListItem* listItem, RenderListMarker* listItemMarker)
376 if (!shouldHandleLayout())
378 ASSERT(listItem && listItemMarker);
380 if (prepareForLayout(listItem) == StopLayout)
383 // Force the LI to be inside the DBCAT when computing the multiplier.
384 // This guarantees that the DBCAT has entered layout, so we can ask for its width.
385 // It also makes sense because the list marker is autosized like a text node.
386 float multiplier = clusterMultiplier(currentCluster());
388 applyMultiplier(listItem, multiplier);
389 applyMultiplier(listItemMarker, multiplier);
392 void TextAutosizer::inflateAutoTable(RenderTable* table)
395 ASSERT(!table->style()->isFixedTableLayout());
396 ASSERT(table->containingBlock());
398 Cluster* cluster = currentCluster();
399 if (cluster->m_root != table)
402 // Pre-inflate cells that have enough text so that their inflated preferred widths will be used
403 // for column sizing.
404 for (RenderObject* section = table->firstChild(); section; section = section->nextSibling()) {
405 if (!section->isTableSection())
407 for (RenderTableRow* row = toRenderTableSection(section)->firstRow(); row; row = row->nextRow()) {
408 for (RenderTableCell* cell = row->firstCell(); cell; cell = cell->nextCell()) {
409 if (!cell->needsLayout())
413 inflate(cell, DescendToInnerBlocks);
420 void TextAutosizer::endLayout(RenderBlock* block)
422 ASSERT(shouldHandleLayout());
424 if (block == m_firstBlockToBeginLayout) {
425 m_firstBlockToBeginLayout = 0;
426 m_clusterStack.clear();
427 m_superclusters.clear();
428 m_stylesRetainedDuringLayout.clear();
430 m_blocksThatHaveBegunLayout.clear();
432 // Tables can create two layout scopes for the same block so the isEmpty
433 // check below is needed to guard against endLayout being called twice.
434 } else if (!m_clusterStack.isEmpty() && currentCluster()->m_root == block) {
435 m_clusterStack.removeLast();
439 float TextAutosizer::inflate(RenderObject* parent, InflateBehavior behavior, float multiplier)
441 Cluster* cluster = currentCluster();
442 bool hasTextChild = false;
444 RenderObject* child = 0;
445 if (parent->isRenderBlock() && (parent->childrenInline() || behavior == DescendToInnerBlocks))
446 child = toRenderBlock(parent)->firstChild();
447 else if (parent->isRenderInline())
448 child = toRenderInline(parent)->firstChild();
451 if (child->isText()) {
453 // We only calculate this multiplier on-demand to ensure the parent block of this text
454 // has entered layout.
456 multiplier = cluster->m_flags & SUPPRESSING ? 1.0f : clusterMultiplier(cluster);
457 applyMultiplier(child, multiplier);
458 // FIXME: Investigate why MarkOnlyThis is sufficient.
459 if (parent->isRenderInline())
460 child->setPreferredLogicalWidthsDirty(MarkOnlyThis);
461 } else if (child->isRenderInline()) {
462 multiplier = inflate(child, behavior, multiplier);
463 } else if (child->isRenderBlock() && behavior == DescendToInnerBlocks
464 && !classifyBlock(child, INDEPENDENT | EXPLICIT_WIDTH | SUPPRESSING)) {
465 multiplier = inflate(child, behavior, multiplier);
467 child = child->nextSibling();
471 applyMultiplier(parent, multiplier); // Parent handles line spacing.
472 } else if (!parent->isListItem()) {
473 // For consistency, a block with no immediate text child should always have a
474 // multiplier of 1 (except for list items which are handled in inflateListItem).
475 applyMultiplier(parent, 1);
480 bool TextAutosizer::shouldHandleLayout() const
482 return m_pageInfo.m_settingEnabled && m_pageInfo.m_pageNeedsAutosizing && !m_updatePageInfoDeferred;
485 void TextAutosizer::updatePageInfoInAllFrames()
487 ASSERT(!m_document->frame() || m_document->frame()->isMainFrame());
489 for (Frame* frame = m_document->frame(); frame; frame = frame->tree().traverseNext()) {
490 if (!frame->isLocalFrame())
492 if (TextAutosizer* textAutosizer = toLocalFrame(frame)->document()->textAutosizer())
493 textAutosizer->updatePageInfo();
497 void TextAutosizer::updatePageInfo()
499 if (m_updatePageInfoDeferred || !m_document->page() || !m_document->settings())
502 PageInfo previousPageInfo(m_pageInfo);
503 m_pageInfo.m_settingEnabled = m_document->settings()->textAutosizingEnabled();
505 if (!m_pageInfo.m_settingEnabled || m_document->printing()) {
506 m_pageInfo.m_pageNeedsAutosizing = false;
508 RenderView* renderView = m_document->renderView();
509 bool horizontalWritingMode = isHorizontalWritingMode(renderView->style()->writingMode());
511 LocalFrame* mainFrame = m_document->page()->deprecatedLocalMainFrame();
512 IntSize frameSize = m_document->settings()->textAutosizingWindowSizeOverride();
513 if (frameSize.isEmpty())
514 frameSize = mainFrame->view()->unscaledVisibleContentSize(IncludeScrollbars);
515 m_pageInfo.m_frameWidth = horizontalWritingMode ? frameSize.width() : frameSize.height();
517 IntSize layoutSize = mainFrame->view()->layoutSize();
518 m_pageInfo.m_layoutWidth = horizontalWritingMode ? layoutSize.width() : layoutSize.height();
520 // Compute the base font scale multiplier based on device and accessibility settings.
521 m_pageInfo.m_baseMultiplier = m_document->settings()->accessibilityFontScaleFactor();
522 // If the page has a meta viewport or @viewport, don't apply the device scale adjustment.
523 const ViewportDescription& viewportDescription = mainFrame->document()->viewportDescription();
524 if (!viewportDescription.isSpecifiedByAuthor()) {
525 float deviceScaleAdjustment = m_document->settings()->deviceScaleAdjustment();
526 m_pageInfo.m_baseMultiplier *= deviceScaleAdjustment;
529 m_pageInfo.m_pageNeedsAutosizing = !!m_pageInfo.m_frameWidth
530 && (m_pageInfo.m_baseMultiplier * (static_cast<float>(m_pageInfo.m_layoutWidth) / m_pageInfo.m_frameWidth) > 1.0f);
533 if (m_pageInfo.m_pageNeedsAutosizing) {
534 // If page info has changed, multipliers may have changed. Force a layout to recompute them.
535 if (m_pageInfo.m_frameWidth != previousPageInfo.m_frameWidth
536 || m_pageInfo.m_layoutWidth != previousPageInfo.m_layoutWidth
537 || m_pageInfo.m_baseMultiplier != previousPageInfo.m_baseMultiplier
538 || m_pageInfo.m_settingEnabled != previousPageInfo.m_settingEnabled)
539 setAllTextNeedsLayout();
540 } else if (previousPageInfo.m_hasAutosized) {
541 // If we are no longer autosizing the page, we won't do anything during the next layout.
542 // Set all the multipliers back to 1 now.
544 m_pageInfo.m_hasAutosized = false;
548 void TextAutosizer::resetMultipliers()
550 RenderObject* renderer = m_document->renderView();
552 if (RenderStyle* style = renderer->style()) {
553 if (style->textAutosizingMultiplier() != 1)
554 applyMultiplier(renderer, 1, LayoutNeeded);
556 renderer = renderer->nextInPreOrder();
560 void TextAutosizer::setAllTextNeedsLayout()
562 RenderObject* renderer = m_document->renderView();
564 if (renderer->isText())
565 renderer->setNeedsLayoutAndFullPaintInvalidation();
566 renderer = renderer->nextInPreOrder();
570 TextAutosizer::BlockFlags TextAutosizer::classifyBlock(const RenderObject* renderer, BlockFlags mask)
572 if (!renderer->isRenderBlock())
575 const RenderBlock* block = toRenderBlock(renderer);
576 BlockFlags flags = 0;
578 if (isPotentialClusterRoot(block)) {
579 if (mask & POTENTIAL_ROOT)
580 flags |= POTENTIAL_ROOT;
582 if ((mask & INDEPENDENT) && (isIndependentDescendant(block) || block->isTable()))
583 flags |= INDEPENDENT;
585 if ((mask & EXPLICIT_WIDTH) && hasExplicitWidth(block))
586 flags |= EXPLICIT_WIDTH;
588 if ((mask & SUPPRESSING) && blockSuppressesAutosizing(block))
589 flags |= SUPPRESSING;
594 bool TextAutosizer::clusterWouldHaveEnoughTextToAutosize(const RenderBlock* root, const RenderBlock* widthProvider)
596 Cluster hypotheticalCluster(root, classifyBlock(root), 0);
597 return clusterHasEnoughTextToAutosize(&hypotheticalCluster, widthProvider);
600 bool TextAutosizer::clusterHasEnoughTextToAutosize(Cluster* cluster, const RenderBlock* widthProvider)
602 if (cluster->m_hasEnoughTextToAutosize != UnknownAmountOfText)
603 return cluster->m_hasEnoughTextToAutosize == HasEnoughText;
605 const RenderBlock* root = cluster->m_root;
607 widthProvider = clusterWidthProvider(root);
609 // TextAreas and user-modifiable areas get a free pass to autosize regardless of text content.
610 if (root->isTextArea() || (root->style() && root->style()->userModify() != READ_ONLY)) {
611 cluster->m_hasEnoughTextToAutosize = HasEnoughText;
615 if (cluster->m_flags & SUPPRESSING) {
616 cluster->m_hasEnoughTextToAutosize = NotEnoughText;
620 // 4 lines of text is considered enough to autosize.
621 float minimumTextLengthToAutosize = widthFromBlock(widthProvider) * 4;
624 RenderObject* descendant = root->firstChild();
626 if (descendant->isRenderBlock()) {
627 if (classifyBlock(descendant, INDEPENDENT | SUPPRESSING)) {
628 descendant = descendant->nextInPreOrderAfterChildren(root);
631 } else if (descendant->isText()) {
632 // Note: Using text().stripWhiteSpace().length() instead of renderedTextLength() because
633 // the lineboxes will not be built until layout. These values can be different.
634 // Note: This is an approximation assuming each character is 1em wide.
635 length += toRenderText(descendant)->text().stripWhiteSpace().length() * descendant->style()->specifiedFontSize();
637 if (length >= minimumTextLengthToAutosize) {
638 cluster->m_hasEnoughTextToAutosize = HasEnoughText;
642 descendant = descendant->nextInPreOrder(root);
645 cluster->m_hasEnoughTextToAutosize = NotEnoughText;
649 TextAutosizer::Fingerprint TextAutosizer::getFingerprint(const RenderObject* renderer)
651 Fingerprint result = m_fingerprintMapper.get(renderer);
653 result = computeFingerprint(renderer);
654 m_fingerprintMapper.add(renderer, result);
659 TextAutosizer::Fingerprint TextAutosizer::computeFingerprint(const RenderObject* renderer)
661 Node* node = renderer->generatingNode();
662 if (!node || !node->isElementNode())
665 FingerprintSourceData data;
666 if (const RenderObject* parent = parentElementRenderer(renderer))
667 data.m_parentHash = getFingerprint(parent);
669 data.m_qualifiedNameHash = QualifiedNameHash::hash(toElement(node)->tagQName());
671 if (RenderStyle* style = renderer->style()) {
672 data.m_packedStyleProperties = style->direction();
673 data.m_packedStyleProperties |= (style->position() << 1);
674 data.m_packedStyleProperties |= (style->floating() << 4);
675 data.m_packedStyleProperties |= (style->display() << 6);
676 data.m_packedStyleProperties |= (style->width().type() << 11);
677 // packedStyleProperties effectively using 15 bits now.
679 // consider for adding: writing mode, padding.
681 data.m_width = style->width().getFloatValue();
684 // Use nodeIndex as a rough approximation of column number
685 // (it's too early to call RenderTableCell::col).
686 // FIXME: account for colspan
687 if (renderer->isTableCell())
688 data.m_column = renderer->node()->nodeIndex();
690 return StringHasher::computeHash<UChar>(
691 static_cast<const UChar*>(static_cast<const void*>(&data)),
692 sizeof data / sizeof(UChar));
695 TextAutosizer::Cluster* TextAutosizer::maybeCreateCluster(const RenderBlock* block)
697 BlockFlags flags = classifyBlock(block);
698 if (!(flags & POTENTIAL_ROOT))
701 Cluster* parentCluster = m_clusterStack.isEmpty() ? 0 : currentCluster();
702 ASSERT(parentCluster || block->isRenderView());
704 // If a non-independent block would not alter the SUPPRESSING flag, it doesn't need to be a cluster.
705 bool parentSuppresses = parentCluster && (parentCluster->m_flags & SUPPRESSING);
706 if (!(flags & INDEPENDENT) && !(flags & EXPLICIT_WIDTH) && !!(flags & SUPPRESSING) == parentSuppresses)
709 Cluster* cluster = new Cluster(block, flags, parentCluster, getSupercluster(block));
710 #ifdef AUTOSIZING_DOM_DEBUG_INFO
711 // Non-SUPPRESSING clusters are annotated in clusterMultiplier.
712 if (flags & SUPPRESSING)
713 writeClusterDebugInfo(cluster);
718 TextAutosizer::Supercluster* TextAutosizer::getSupercluster(const RenderBlock* block)
720 Fingerprint fingerprint = m_fingerprintMapper.get(block);
724 BlockSet* roots = m_fingerprintMapper.getTentativeClusterRoots(fingerprint);
725 if (!roots || roots->size() < 2 || !roots->contains(block))
728 SuperclusterMap::AddResult addResult = m_superclusters.add(fingerprint, PassOwnPtr<Supercluster>());
729 if (!addResult.isNewEntry)
730 return addResult.storedValue->value.get();
732 Supercluster* supercluster = new Supercluster(roots);
733 addResult.storedValue->value = adoptPtr(supercluster);
737 float TextAutosizer::clusterMultiplier(Cluster* cluster)
739 if (cluster->m_multiplier)
740 return cluster->m_multiplier;
742 // FIXME: why does isWiderOrNarrowerDescendant crash on independent clusters?
743 if (!(cluster->m_flags & INDEPENDENT) && isWiderOrNarrowerDescendant(cluster))
744 cluster->m_flags |= WIDER_OR_NARROWER;
746 if (cluster->m_flags & (INDEPENDENT | WIDER_OR_NARROWER)) {
747 if (cluster->m_supercluster)
748 cluster->m_multiplier = superclusterMultiplier(cluster);
749 else if (clusterHasEnoughTextToAutosize(cluster))
750 cluster->m_multiplier = multiplierFromBlock(clusterWidthProvider(cluster->m_root));
752 cluster->m_multiplier = 1.0f;
754 cluster->m_multiplier = cluster->m_parent ? clusterMultiplier(cluster->m_parent) : 1.0f;
757 #ifdef AUTOSIZING_DOM_DEBUG_INFO
758 writeClusterDebugInfo(cluster);
761 ASSERT(cluster->m_multiplier);
762 return cluster->m_multiplier;
765 bool TextAutosizer::superclusterHasEnoughTextToAutosize(Supercluster* supercluster, const RenderBlock* widthProvider)
767 if (supercluster->m_hasEnoughTextToAutosize != UnknownAmountOfText)
768 return supercluster->m_hasEnoughTextToAutosize == HasEnoughText;
770 BlockSet::iterator end = supercluster->m_roots->end();
771 for (BlockSet::iterator it = supercluster->m_roots->begin(); it != end; ++it) {
772 if (clusterWouldHaveEnoughTextToAutosize(*it, widthProvider)) {
773 supercluster->m_hasEnoughTextToAutosize = HasEnoughText;
777 supercluster->m_hasEnoughTextToAutosize = NotEnoughText;
781 float TextAutosizer::superclusterMultiplier(Cluster* cluster)
783 Supercluster* supercluster = cluster->m_supercluster;
784 if (!supercluster->m_multiplier) {
785 const RenderBlock* widthProvider = maxClusterWidthProvider(cluster->m_supercluster, cluster->m_root);
786 supercluster->m_multiplier = superclusterHasEnoughTextToAutosize(supercluster, widthProvider)
787 ? multiplierFromBlock(widthProvider) : 1.0f;
789 ASSERT(supercluster->m_multiplier);
790 return supercluster->m_multiplier;
793 const RenderBlock* TextAutosizer::clusterWidthProvider(const RenderBlock* root)
795 if (root->isTable() || root->isTableCell())
798 return deepestBlockContainingAllText(root);
801 const RenderBlock* TextAutosizer::maxClusterWidthProvider(const Supercluster* supercluster, const RenderBlock* currentRoot)
803 const RenderBlock* result = clusterWidthProvider(currentRoot);
804 float maxWidth = widthFromBlock(result);
806 const BlockSet* roots = supercluster->m_roots;
807 for (BlockSet::iterator it = roots->begin(); it != roots->end(); ++it) {
808 const RenderBlock* widthProvider = clusterWidthProvider(*it);
809 if (widthProvider->needsLayout())
811 float width = widthFromBlock(widthProvider);
812 if (width > maxWidth) {
814 result = widthProvider;
817 RELEASE_ASSERT(result);
821 float TextAutosizer::widthFromBlock(const RenderBlock* block)
823 RELEASE_ASSERT(block);
824 RELEASE_ASSERT(block->style());
826 if (!(block->isTable() || block->isTableCell() || block->isListItem()))
827 return block->contentLogicalWidth().toFloat();
829 if (!block->containingBlock())
832 // Tables may be inflated before computing their preferred widths. Try several methods to
833 // obtain a width, and fall back on a containing block's width.
834 for (; block; block = block->containingBlock()) {
836 Length specifiedWidth = block->isTableCell()
837 ? toRenderTableCell(block)->styleOrColLogicalWidth() : block->style()->logicalWidth();
838 if (specifiedWidth.isFixed()) {
839 if ((width = specifiedWidth.value()) > 0)
842 if (specifiedWidth.isPercent()) {
843 if (float containerWidth = block->containingBlock()->contentLogicalWidth().toFloat()) {
844 if ((width = floatValueForLength(specifiedWidth, containerWidth)) > 0)
848 if ((width = block->contentLogicalWidth().toFloat()) > 0)
854 float TextAutosizer::multiplierFromBlock(const RenderBlock* block)
856 // If block->needsLayout() is false, it does not need to be in m_blocksThatHaveBegunLayout.
857 // This can happen during layout of a positioned object if the cluster's DBCAT is deeper
858 // than the positioned object's containing block, and wasn't marked as needing layout.
859 ASSERT(m_blocksThatHaveBegunLayout.contains(block) || !block->needsLayout());
861 // Block width, in CSS pixels.
862 float blockWidth = widthFromBlock(block);
863 float multiplier = m_pageInfo.m_frameWidth ? std::min(blockWidth, static_cast<float>(m_pageInfo.m_layoutWidth)) / m_pageInfo.m_frameWidth : 1.0f;
865 return std::max(m_pageInfo.m_baseMultiplier * multiplier, 1.0f);
868 const RenderBlock* TextAutosizer::deepestBlockContainingAllText(Cluster* cluster)
870 if (!cluster->m_deepestBlockContainingAllText)
871 cluster->m_deepestBlockContainingAllText = deepestBlockContainingAllText(cluster->m_root);
873 return cluster->m_deepestBlockContainingAllText;
876 // FIXME: Refactor this to look more like TextAutosizer::deepestCommonAncestor.
877 const RenderBlock* TextAutosizer::deepestBlockContainingAllText(const RenderBlock* root)
879 size_t firstDepth = 0;
880 const RenderObject* firstTextLeaf = findTextLeaf(root, firstDepth, First);
884 size_t lastDepth = 0;
885 const RenderObject* lastTextLeaf = findTextLeaf(root, lastDepth, Last);
886 ASSERT(lastTextLeaf);
888 // Equalize the depths if necessary. Only one of the while loops below will get executed.
889 const RenderObject* firstNode = firstTextLeaf;
890 const RenderObject* lastNode = lastTextLeaf;
891 while (firstDepth > lastDepth) {
892 firstNode = firstNode->parent();
895 while (lastDepth > firstDepth) {
896 lastNode = lastNode->parent();
900 // Go up from both nodes until the parent is the same. Both pointers will point to the LCA then.
901 while (firstNode != lastNode) {
902 firstNode = firstNode->parent();
903 lastNode = lastNode->parent();
906 if (firstNode->isRenderBlock())
907 return toRenderBlock(firstNode);
909 // containingBlock() should never leave the cluster, since it only skips ancestors when finding
910 // the container of position:absolute/fixed blocks, and those cannot exist between a cluster and
911 // its text node's lowest common ancestor as isAutosizingCluster would have made them into their
912 // own independent cluster.
913 const RenderBlock* containingBlock = firstNode->containingBlock();
914 if (!containingBlock)
917 ASSERT(containingBlock->isDescendantOf(root));
918 return containingBlock;
921 const RenderObject* TextAutosizer::findTextLeaf(const RenderObject* parent, size_t& depth, TextLeafSearch firstOrLast)
923 // List items are treated as text due to the marker.
924 // The actual renderer for the marker (RenderListMarker) may not be in the tree yet since it is added during layout.
925 if (parent->isListItem())
928 if (parent->isText())
932 const RenderObject* child = (firstOrLast == First) ? parent->slowFirstChild() : parent->slowLastChild();
934 // Note: At this point clusters may not have been created for these blocks so we cannot rely
935 // on m_clusters. Instead, we use a best-guess about whether the block will become a cluster.
936 if (!classifyBlock(child, INDEPENDENT)) {
937 if (const RenderObject* leaf = findTextLeaf(child, depth, firstOrLast))
940 child = (firstOrLast == First) ? child->nextSibling() : child->previousSibling();
947 void TextAutosizer::applyMultiplier(RenderObject* renderer, float multiplier, RelayoutBehavior relayoutBehavior)
949 ASSERT(renderer && renderer->style());
950 RenderStyle* currentStyle = renderer->style();
951 if (currentStyle->textAutosizingMultiplier() == multiplier)
954 // We need to clone the render style to avoid breaking style sharing.
955 RefPtr<RenderStyle> style = RenderStyle::clone(currentStyle);
956 style->setTextAutosizingMultiplier(multiplier);
959 switch (relayoutBehavior) {
960 case AlreadyInLayout:
961 // Don't free currentStyle until the end of the layout pass. This allows other parts of the system
962 // to safely hold raw RenderStyle* pointers during layout, e.g. BreakingContext::m_currentStyle.
963 m_stylesRetainedDuringLayout.append(currentStyle);
965 renderer->setStyleInternal(style.release());
966 renderer->setNeedsLayoutAndFullPaintInvalidation();
970 renderer->setStyle(style.release());
975 m_pageInfo.m_hasAutosized = true;
978 bool TextAutosizer::isWiderOrNarrowerDescendant(Cluster* cluster)
980 // FIXME: Why do we return true when hasExplicitWidth returns false??
981 if (!cluster->m_parent || !hasExplicitWidth(cluster->m_root))
984 const RenderBlock* parentDeepestBlockContainingAllText = deepestBlockContainingAllText(cluster->m_parent);
985 ASSERT(m_blocksThatHaveBegunLayout.contains(cluster->m_root));
986 ASSERT(m_blocksThatHaveBegunLayout.contains(parentDeepestBlockContainingAllText));
988 float contentWidth = cluster->m_root->contentLogicalWidth().toFloat();
989 float clusterTextWidth = parentDeepestBlockContainingAllText->contentLogicalWidth().toFloat();
991 // Clusters with a root that is wider than the deepestBlockContainingAllText of their parent
992 // autosize independently of their parent.
993 if (contentWidth > clusterTextWidth)
996 // Clusters with a root that is significantly narrower than the deepestBlockContainingAllText of
997 // their parent autosize independently of their parent.
998 static float narrowWidthDifference = 200;
999 if (clusterTextWidth - contentWidth > narrowWidthDifference)
1005 TextAutosizer::Cluster* TextAutosizer::currentCluster() const
1007 ASSERT_WITH_SECURITY_IMPLICATION(!m_clusterStack.isEmpty());
1008 return m_clusterStack.last().get();
1012 void TextAutosizer::FingerprintMapper::assertMapsAreConsistent()
1014 // For each fingerprint -> block mapping in m_blocksForFingerprint we should have an associated
1015 // map from block -> fingerprint in m_fingerprints.
1016 ReverseFingerprintMap::iterator end = m_blocksForFingerprint.end();
1017 for (ReverseFingerprintMap::iterator fingerprintIt = m_blocksForFingerprint.begin(); fingerprintIt != end; ++fingerprintIt) {
1018 Fingerprint fingerprint = fingerprintIt->key;
1019 BlockSet* blocks = fingerprintIt->value.get();
1020 for (BlockSet::iterator blockIt = blocks->begin(); blockIt != blocks->end(); ++blockIt) {
1021 const RenderBlock* block = (*blockIt);
1022 ASSERT(m_fingerprints.get(block) == fingerprint);
1028 void TextAutosizer::FingerprintMapper::add(const RenderObject* renderer, Fingerprint fingerprint)
1032 m_fingerprints.set(renderer, fingerprint);
1034 assertMapsAreConsistent();
1038 void TextAutosizer::FingerprintMapper::addTentativeClusterRoot(const RenderBlock* block, Fingerprint fingerprint)
1040 add(block, fingerprint);
1042 ReverseFingerprintMap::AddResult addResult = m_blocksForFingerprint.add(fingerprint, PassOwnPtr<BlockSet>());
1043 if (addResult.isNewEntry)
1044 addResult.storedValue->value = adoptPtr(new BlockSet);
1045 addResult.storedValue->value->add(block);
1047 assertMapsAreConsistent();
1051 bool TextAutosizer::FingerprintMapper::remove(const RenderObject* renderer)
1053 Fingerprint fingerprint = m_fingerprints.take(renderer);
1054 if (!fingerprint || !renderer->isRenderBlock())
1057 ReverseFingerprintMap::iterator blocksIter = m_blocksForFingerprint.find(fingerprint);
1058 if (blocksIter == m_blocksForFingerprint.end())
1061 BlockSet& blocks = *blocksIter->value;
1062 blocks.remove(toRenderBlock(renderer));
1063 if (blocks.isEmpty())
1064 m_blocksForFingerprint.remove(blocksIter);
1066 assertMapsAreConsistent();
1071 TextAutosizer::Fingerprint TextAutosizer::FingerprintMapper::get(const RenderObject* renderer)
1073 return m_fingerprints.get(renderer);
1076 TextAutosizer::BlockSet* TextAutosizer::FingerprintMapper::getTentativeClusterRoots(Fingerprint fingerprint)
1078 return m_blocksForFingerprint.get(fingerprint);
1081 TextAutosizer::LayoutScope::LayoutScope(RenderBlock* block)
1082 : m_textAutosizer(block->document().textAutosizer())
1085 if (!m_textAutosizer)
1088 if (m_textAutosizer->shouldHandleLayout())
1089 m_textAutosizer->beginLayout(m_block);
1091 m_textAutosizer = 0;
1094 TextAutosizer::LayoutScope::~LayoutScope()
1096 if (m_textAutosizer)
1097 m_textAutosizer->endLayout(m_block);
1101 TextAutosizer::TableLayoutScope::TableLayoutScope(RenderTable* table)
1102 : LayoutScope(table)
1104 if (m_textAutosizer) {
1105 ASSERT(m_textAutosizer->shouldHandleLayout());
1106 m_textAutosizer->inflateAutoTable(table);
1110 TextAutosizer::DeferUpdatePageInfo::DeferUpdatePageInfo(Page* page)
1111 : m_mainFrame(page->deprecatedLocalMainFrame())
1113 if (TextAutosizer* textAutosizer = m_mainFrame->document()->textAutosizer()) {
1114 ASSERT(!textAutosizer->m_updatePageInfoDeferred);
1115 textAutosizer->m_updatePageInfoDeferred = true;
1119 TextAutosizer::DeferUpdatePageInfo::~DeferUpdatePageInfo()
1121 if (TextAutosizer* textAutosizer = m_mainFrame->document()->textAutosizer()) {
1122 ASSERT(textAutosizer->m_updatePageInfoDeferred);
1123 textAutosizer->m_updatePageInfoDeferred = false;
1124 textAutosizer->updatePageInfoInAllFrames();
1128 float TextAutosizer::computeAutosizedFontSize(float specifiedSize, float multiplier)
1130 // Somewhat arbitrary "pleasant" font size.
1131 const float pleasantSize = 16;
1133 // Multiply fonts that the page author has specified to be larger than
1134 // pleasantSize by less and less, until huge fonts are not increased at all.
1135 // For specifiedSize between 0 and pleasantSize we directly apply the
1136 // multiplier; hence for specifiedSize == pleasantSize, computedSize will be
1137 // multiplier * pleasantSize. For greater specifiedSizes we want to
1138 // gradually fade out the multiplier, so for every 1px increase in
1139 // specifiedSize beyond pleasantSize we will only increase computedSize
1140 // by gradientAfterPleasantSize px until we meet the
1141 // computedSize = specifiedSize line, after which we stay on that line (so
1142 // then every 1px increase in specifiedSize increases computedSize by 1px).
1143 const float gradientAfterPleasantSize = 0.5;
1146 if (specifiedSize <= pleasantSize) {
1147 computedSize = multiplier * specifiedSize;
1149 computedSize = multiplier * pleasantSize + gradientAfterPleasantSize * (specifiedSize - pleasantSize);
1150 if (computedSize < specifiedSize)
1151 computedSize = specifiedSize;
1153 return computedSize;
1156 void TextAutosizer::trace(Visitor* visitor)
1158 visitor->trace(m_document);
1161 } // namespace blink