2 * Copyright (C) 2006 Apple Computer, Inc.
3 * Copyright (C) 2006 Alexander Kellett <lypanov@kde.org>
4 * Copyright (C) 2006 Oliver Hunt <ojh16@student.canterbury.ac.nz>
5 * Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
6 * Copyright (C) 2008 Rob Buis <buis@kde.org>
7 * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
8 * Copyright (C) Research In Motion Limited 2010-2012. All rights reserved.
9 * Copyright (C) 2012 Google Inc.
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public License
22 * along with this library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
29 #include "core/rendering/svg/RenderSVGText.h"
31 #include "core/editing/PositionWithAffinity.h"
32 #include "core/rendering/HitTestRequest.h"
33 #include "core/rendering/HitTestResult.h"
34 #include "core/rendering/PaintInfo.h"
35 #include "core/rendering/PointerEventsHitRules.h"
36 #include "core/rendering/style/ShadowList.h"
37 #include "core/rendering/svg/RenderSVGInline.h"
38 #include "core/rendering/svg/RenderSVGInlineText.h"
39 #include "core/rendering/svg/RenderSVGResource.h"
40 #include "core/rendering/svg/RenderSVGRoot.h"
41 #include "core/rendering/svg/SVGRenderSupport.h"
42 #include "core/rendering/svg/SVGResourcesCache.h"
43 #include "core/rendering/svg/SVGRootInlineBox.h"
44 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
45 #include "core/svg/SVGLengthList.h"
46 #include "core/svg/SVGTextElement.h"
47 #include "core/svg/SVGTransformList.h"
48 #include "core/svg/SVGURIReference.h"
49 #include "platform/FloatConversion.h"
50 #include "platform/fonts/FontCache.h"
51 #include "platform/fonts/SimpleFontData.h"
52 #include "platform/geometry/FloatQuad.h"
53 #include "platform/geometry/TransformState.h"
54 #include "platform/graphics/GraphicsContextStateSaver.h"
58 RenderSVGText::RenderSVGText(SVGTextElement* node)
59 : RenderSVGBlock(node)
60 , m_needsReordering(false)
61 , m_needsPositioningValuesUpdate(false)
62 , m_needsTransformUpdate(true)
63 , m_needsTextMetricsUpdate(false)
67 RenderSVGText::~RenderSVGText()
69 ASSERT(m_layoutAttributes.isEmpty());
72 bool RenderSVGText::isChildAllowed(RenderObject* child, RenderStyle*) const
74 return child->isSVGInline() || (child->isText() && SVGRenderSupport::isRenderableTextNode(child));
77 RenderSVGText* RenderSVGText::locateRenderSVGTextAncestor(RenderObject* start)
80 while (start && !start->isSVGText())
81 start = start->parent();
82 if (!start || !start->isSVGText())
84 return toRenderSVGText(start);
87 const RenderSVGText* RenderSVGText::locateRenderSVGTextAncestor(const RenderObject* start)
90 while (start && !start->isSVGText())
91 start = start->parent();
92 if (!start || !start->isSVGText())
94 return toRenderSVGText(start);
97 void RenderSVGText::mapRectToPaintInvalidationBacking(const RenderLayerModelObject* paintInvalidationContainer, LayoutRect& rect, ViewportConstrainedPosition, const PaintInvalidationState* paintInvalidationState) const
99 FloatRect paintInvalidationRect = rect;
100 computeFloatRectForPaintInvalidation(paintInvalidationContainer, paintInvalidationRect, paintInvalidationState);
101 rect = enclosingLayoutRect(paintInvalidationRect);
104 static inline void collectLayoutAttributes(RenderObject* text, Vector<SVGTextLayoutAttributes*>& attributes)
106 for (RenderObject* descendant = text; descendant; descendant = descendant->nextInPreOrder(text)) {
107 if (descendant->isSVGInlineText())
108 attributes.append(toRenderSVGInlineText(descendant)->layoutAttributes());
112 static inline bool findPreviousAndNextAttributes(RenderSVGText* root, RenderSVGInlineText* locateElement, SVGTextLayoutAttributes*& previous, SVGTextLayoutAttributes*& next)
115 ASSERT(locateElement);
116 bool stopAfterNext = false;
117 RenderObject* current = root->firstChild();
119 if (current->isSVGInlineText()) {
120 RenderSVGInlineText* text = toRenderSVGInlineText(current);
121 if (locateElement != text) {
123 next = text->layoutAttributes();
127 previous = text->layoutAttributes();
129 stopAfterNext = true;
131 } else if (current->isSVGInline()) {
132 // Descend into text content (if possible).
133 if (RenderObject* child = toRenderSVGInline(current)->firstChild()) {
139 current = current->nextInPreOrderAfterChildren(root);
144 inline bool RenderSVGText::shouldHandleSubtreeMutations() const
146 if (beingDestroyed() || !everHadLayout()) {
147 ASSERT(m_layoutAttributes.isEmpty());
148 ASSERT(!m_layoutAttributesBuilder.numberOfTextPositioningElements());
154 void RenderSVGText::subtreeChildWasAdded(RenderObject* child)
157 if (!shouldHandleSubtreeMutations() || documentBeingDestroyed())
160 // Always protect the cache before clearing text positioning elements when the cache will subsequently be rebuilt.
161 FontCachePurgePreventer fontCachePurgePreventer;
163 // The positioning elements cache doesn't include the new 'child' yet. Clear the
164 // cache, as the next buildLayoutAttributesForTextRenderer() call rebuilds it.
165 m_layoutAttributesBuilder.clearTextPositioningElements();
167 if (!child->isSVGInlineText() && !child->isSVGInline())
170 // Detect changes in layout attributes and only measure those text parts that have changed!
171 Vector<SVGTextLayoutAttributes*> newLayoutAttributes;
172 collectLayoutAttributes(this, newLayoutAttributes);
173 if (newLayoutAttributes.isEmpty()) {
174 ASSERT(m_layoutAttributes.isEmpty());
178 // Compare m_layoutAttributes with newLayoutAttributes to figure out which attribute got added.
179 size_t size = newLayoutAttributes.size();
180 SVGTextLayoutAttributes* attributes = 0;
181 for (size_t i = 0; i < size; ++i) {
182 attributes = newLayoutAttributes[i];
183 if (m_layoutAttributes.find(attributes) == kNotFound) {
184 // Every time this is invoked, there's only a single new entry in the newLayoutAttributes list, compared to the old in m_layoutAttributes.
185 SVGTextLayoutAttributes* previous = 0;
186 SVGTextLayoutAttributes* next = 0;
187 ASSERT_UNUSED(child, attributes->context() == child);
188 findPreviousAndNextAttributes(this, attributes->context(), previous, next);
191 m_layoutAttributesBuilder.buildLayoutAttributesForTextRenderer(previous->context());
192 m_layoutAttributesBuilder.buildLayoutAttributesForTextRenderer(attributes->context());
194 m_layoutAttributesBuilder.buildLayoutAttributesForTextRenderer(next->context());
200 // Verify that m_layoutAttributes only differs by a maximum of one entry.
201 for (size_t i = 0; i < size; ++i)
202 ASSERT(m_layoutAttributes.find(newLayoutAttributes[i]) != kNotFound || newLayoutAttributes[i] == attributes);
205 m_layoutAttributes = newLayoutAttributes;
208 static inline void checkLayoutAttributesConsistency(RenderSVGText* text, Vector<SVGTextLayoutAttributes*>& expectedLayoutAttributes)
211 Vector<SVGTextLayoutAttributes*> newLayoutAttributes;
212 collectLayoutAttributes(text, newLayoutAttributes);
213 ASSERT(newLayoutAttributes == expectedLayoutAttributes);
217 void RenderSVGText::willBeDestroyed()
219 m_layoutAttributes.clear();
220 m_layoutAttributesBuilder.clearTextPositioningElements();
222 RenderSVGBlock::willBeDestroyed();
225 void RenderSVGText::subtreeChildWillBeRemoved(RenderObject* child, Vector<SVGTextLayoutAttributes*, 2>& affectedAttributes)
228 if (!shouldHandleSubtreeMutations())
231 checkLayoutAttributesConsistency(this, m_layoutAttributes);
233 // The positioning elements cache depends on the size of each text renderer in the
234 // subtree. If this changes, clear the cache. It's going to be rebuilt below.
235 m_layoutAttributesBuilder.clearTextPositioningElements();
236 if (m_layoutAttributes.isEmpty() || !child->isSVGInlineText())
239 // This logic requires that the 'text' child is still inserted in the tree.
240 RenderSVGInlineText* text = toRenderSVGInlineText(child);
241 SVGTextLayoutAttributes* previous = 0;
242 SVGTextLayoutAttributes* next = 0;
243 if (!documentBeingDestroyed())
244 findPreviousAndNextAttributes(this, text, previous, next);
247 affectedAttributes.append(previous);
249 affectedAttributes.append(next);
251 size_t position = m_layoutAttributes.find(text->layoutAttributes());
252 ASSERT(position != kNotFound);
253 m_layoutAttributes.remove(position);
256 void RenderSVGText::subtreeChildWasRemoved(const Vector<SVGTextLayoutAttributes*, 2>& affectedAttributes)
258 if (!shouldHandleSubtreeMutations() || documentBeingDestroyed()) {
259 ASSERT(affectedAttributes.isEmpty());
263 // This is called immediately after subtreeChildWillBeDestroyed, once the RenderSVGInlineText::willBeDestroyed() method
264 // passes on to the base class, which removes us from the render tree. At this point we can update the layout attributes.
265 unsigned size = affectedAttributes.size();
266 for (unsigned i = 0; i < size; ++i)
267 m_layoutAttributesBuilder.buildLayoutAttributesForTextRenderer(affectedAttributes[i]->context());
270 void RenderSVGText::subtreeStyleDidChange()
272 if (!shouldHandleSubtreeMutations() || documentBeingDestroyed())
275 checkLayoutAttributesConsistency(this, m_layoutAttributes);
277 // Only update the metrics cache, but not the text positioning element cache
278 // nor the layout attributes cached in the leaf #text renderers.
279 FontCachePurgePreventer fontCachePurgePreventer;
280 for (RenderObject* descendant = firstChild(); descendant; descendant = descendant->nextInPreOrder(this)) {
281 if (descendant->isSVGInlineText())
282 m_layoutAttributesBuilder.rebuildMetricsForTextRenderer(toRenderSVGInlineText(descendant));
286 void RenderSVGText::subtreeTextDidChange(RenderSVGInlineText* text)
289 ASSERT(!beingDestroyed());
290 if (!everHadLayout()) {
291 ASSERT(m_layoutAttributes.isEmpty());
292 ASSERT(!m_layoutAttributesBuilder.numberOfTextPositioningElements());
296 // Always protect the cache before clearing text positioning elements when the cache will subsequently be rebuilt.
297 FontCachePurgePreventer fontCachePurgePreventer;
299 // The positioning elements cache depends on the size of each text renderer in the
300 // subtree. If this changes, clear the cache. It's going to be rebuilt below.
301 m_layoutAttributesBuilder.clearTextPositioningElements();
303 checkLayoutAttributesConsistency(this, m_layoutAttributes);
304 for (RenderObject* descendant = text; descendant; descendant = descendant->nextInPreOrder(text)) {
305 if (descendant->isSVGInlineText())
306 m_layoutAttributesBuilder.buildLayoutAttributesForTextRenderer(toRenderSVGInlineText(descendant));
310 static inline void updateFontInAllDescendants(RenderObject* start, SVGTextLayoutAttributesBuilder* builder = 0)
312 for (RenderObject* descendant = start; descendant; descendant = descendant->nextInPreOrder(start)) {
313 if (!descendant->isSVGInlineText())
315 RenderSVGInlineText* text = toRenderSVGInlineText(descendant);
316 text->updateScaledFont();
318 builder->rebuildMetricsForTextRenderer(text);
322 void RenderSVGText::layout()
324 ASSERT(needsLayout());
326 subtreeStyleDidChange();
328 bool updateCachedBoundariesInParents = false;
329 if (m_needsTransformUpdate) {
330 m_localTransform = toSVGTextElement(node())->animatedLocalTransform();
331 m_needsTransformUpdate = false;
332 updateCachedBoundariesInParents = true;
335 if (!everHadLayout()) {
336 // When laying out initially, collect all layout attributes, build the character data map,
337 // and propogate resulting SVGLayoutAttributes to all RenderSVGInlineText children in the subtree.
338 ASSERT(m_layoutAttributes.isEmpty());
339 collectLayoutAttributes(this, m_layoutAttributes);
340 updateFontInAllDescendants(this);
341 m_layoutAttributesBuilder.buildLayoutAttributesForForSubtree(this);
343 m_needsReordering = true;
344 m_needsTextMetricsUpdate = false;
345 m_needsPositioningValuesUpdate = false;
346 updateCachedBoundariesInParents = true;
347 } else if (m_needsPositioningValuesUpdate) {
348 // When the x/y/dx/dy/rotate lists change, recompute the layout attributes, and eventually
349 // update the on-screen font objects as well in all descendants.
350 if (m_needsTextMetricsUpdate) {
351 updateFontInAllDescendants(this);
352 m_needsTextMetricsUpdate = false;
355 m_layoutAttributesBuilder.buildLayoutAttributesForForSubtree(this);
356 m_needsReordering = true;
357 m_needsPositioningValuesUpdate = false;
358 updateCachedBoundariesInParents = true;
359 } else if (m_needsTextMetricsUpdate || SVGRenderSupport::findTreeRootObject(this)->isLayoutSizeChanged()) {
360 // If the root layout size changed (eg. window size changes) or the transform to the root
361 // context has changed then recompute the on-screen font size.
362 updateFontInAllDescendants(this, &m_layoutAttributesBuilder);
364 ASSERT(!m_needsReordering);
365 ASSERT(!m_needsPositioningValuesUpdate);
366 m_needsTextMetricsUpdate = false;
367 updateCachedBoundariesInParents = true;
370 checkLayoutAttributesConsistency(this, m_layoutAttributes);
372 // Reduced version of RenderBlock::layoutBlock(), which only takes care of SVG text.
373 // All if branches that could cause early exit in RenderBlocks layoutBlock() method are turned into assertions.
375 ASSERT(!simplifiedLayout());
376 ASSERT(!scrollsOverflow());
377 ASSERT(!hasControlClip());
378 ASSERT(!hasColumns());
379 ASSERT(!positionedObjects());
381 ASSERT(!isAnonymousBlock());
384 setChildrenInline(true);
386 // FIXME: We need to find a way to only layout the child boxes, if needed.
387 FloatRect oldBoundaries = objectBoundingBox();
388 ASSERT(childrenInline());
390 rebuildFloatsFromIntruding();
392 LayoutUnit beforeEdge = borderBefore() + paddingBefore();
393 LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
394 setLogicalHeight(beforeEdge);
396 LayoutUnit paintInvalidationLogicalTop = 0;
397 LayoutUnit paintInvalidationLogicalBottom = 0;
398 layoutInlineChildren(true, paintInvalidationLogicalTop, paintInvalidationLogicalBottom, afterEdge);
400 if (m_needsReordering)
401 m_needsReordering = false;
403 if (!updateCachedBoundariesInParents)
404 updateCachedBoundariesInParents = oldBoundaries != objectBoundingBox();
406 // Invalidate all resources of this client if our layout changed.
407 if (everHadLayout() && selfNeedsLayout())
408 SVGResourcesCache::clientLayoutChanged(this);
410 // If our bounds changed, notify the parents.
411 if (updateCachedBoundariesInParents)
412 RenderSVGBlock::setNeedsBoundariesUpdate();
417 RootInlineBox* RenderSVGText::createRootInlineBox()
419 RootInlineBox* box = new SVGRootInlineBox(*this);
420 box->setHasVirtualLogicalHeight();
424 bool RenderSVGText::nodeAtFloatPoint(const HitTestRequest& request, HitTestResult& result, const FloatPoint& pointInParent, HitTestAction hitTestAction)
426 PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_TEXT_HITTESTING, request, style()->pointerEvents());
427 bool isVisible = (style()->visibility() == VISIBLE);
428 if (isVisible || !hitRules.requireVisible) {
429 if ((hitRules.canHitBoundingBox && !objectBoundingBox().isEmpty())
430 || (hitRules.canHitStroke && (style()->svgStyle().hasStroke() || !hitRules.requireStroke))
431 || (hitRules.canHitFill && (style()->svgStyle().hasFill() || !hitRules.requireFill))) {
432 FloatPoint localPoint;
433 if (!SVGRenderSupport::transformToUserSpaceAndCheckClipping(this, localToParentTransform(), pointInParent, localPoint))
436 if (hitRules.canHitBoundingBox && !objectBoundingBox().contains(localPoint))
439 HitTestLocation hitTestLocation(LayoutPoint(flooredIntPoint(localPoint)));
440 return RenderBlock::nodeAtPoint(request, result, hitTestLocation, LayoutPoint(), hitTestAction);
447 PositionWithAffinity RenderSVGText::positionForPoint(const LayoutPoint& pointInContents)
449 RootInlineBox* rootBox = firstRootBox();
451 return createPositionWithAffinity(0, DOWNSTREAM);
453 ASSERT(!rootBox->nextRootBox());
454 ASSERT(childrenInline());
456 InlineBox* closestBox = toSVGRootInlineBox(rootBox)->closestLeafChildForPosition(pointInContents);
458 return createPositionWithAffinity(0, DOWNSTREAM);
460 return closestBox->renderer().positionForPoint(LayoutPoint(pointInContents.x(), closestBox->y()));
463 void RenderSVGText::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
465 quads.append(localToAbsoluteQuad(strokeBoundingBox(), 0 /* mode */, wasFixed));
468 void RenderSVGText::paint(PaintInfo& paintInfo, const LayoutPoint&)
470 if (paintInfo.phase != PaintPhaseForeground
471 && paintInfo.phase != PaintPhaseSelection)
474 PaintInfo blockInfo(paintInfo);
475 GraphicsContextStateSaver stateSaver(*blockInfo.context, false);
476 const AffineTransform& localTransform = localToParentTransform();
477 if (!localTransform.isIdentity()) {
479 blockInfo.applyTransform(localTransform, false);
481 RenderBlock::paint(blockInfo, LayoutPoint());
483 // Paint the outlines, if any
484 if (paintInfo.phase == PaintPhaseForeground) {
485 blockInfo.phase = PaintPhaseSelfOutline;
486 RenderBlock::paint(blockInfo, LayoutPoint());
490 FloatRect RenderSVGText::strokeBoundingBox() const
492 FloatRect strokeBoundaries = objectBoundingBox();
493 const SVGRenderStyle& svgStyle = style()->svgStyle();
494 if (!svgStyle.hasStroke())
495 return strokeBoundaries;
498 ASSERT(node()->isSVGElement());
499 SVGLengthContext lengthContext(toSVGElement(node()));
500 strokeBoundaries.inflate(svgStyle.strokeWidth()->value(lengthContext));
501 return strokeBoundaries;
504 FloatRect RenderSVGText::paintInvalidationRectInLocalCoordinates() const
506 FloatRect paintInvalidationRect = strokeBoundingBox();
507 SVGRenderSupport::intersectPaintInvalidationRectWithResources(this, paintInvalidationRect);
509 if (const ShadowList* textShadow = style()->textShadow())
510 textShadow->adjustRectForShadow(paintInvalidationRect);
512 return paintInvalidationRect;
515 void RenderSVGText::addChild(RenderObject* child, RenderObject* beforeChild)
517 RenderSVGBlock::addChild(child, beforeChild);
519 SVGResourcesCache::clientWasAddedToTree(child, child->style());
520 subtreeChildWasAdded(child);
523 void RenderSVGText::removeChild(RenderObject* child)
525 SVGResourcesCache::clientWillBeRemovedFromTree(child);
527 Vector<SVGTextLayoutAttributes*, 2> affectedAttributes;
528 FontCachePurgePreventer fontCachePurgePreventer;
529 subtreeChildWillBeRemoved(child, affectedAttributes);
530 RenderSVGBlock::removeChild(child);
531 subtreeChildWasRemoved(affectedAttributes);