2 * (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 2000 Dirk Mueller (mueller@kde.org)
4 * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
5 * Copyright (C) 2006 Andrew Wellington (proton@wiretapped.net)
6 * Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
26 #include "RenderText.h"
28 #include "AXObjectCache.h"
29 #include "EllipsisBox.h"
30 #include "FloatQuad.h"
31 #include "FontTranscoder.h"
32 #include "FrameView.h"
33 #include "Hyphenation.h"
34 #include "InlineTextBox.h"
36 #include "RenderArena.h"
37 #include "RenderBlock.h"
38 #include "RenderCombineText.h"
39 #include "RenderLayer.h"
40 #include "RenderView.h"
43 #include "TextBreakIterator.h"
44 #include "TextResourceDecoder.h"
45 #include "VisiblePosition.h"
46 #include "break_lines.h"
47 #include <wtf/text/StringBuffer.h>
48 #include <wtf/unicode/CharacterNames.h>
52 using namespace Unicode;
56 struct SameSizeAsRenderText : public RenderObject {
57 uint32_t bitfields : 16;
63 COMPILE_ASSERT(sizeof(RenderText) == sizeof(SameSizeAsRenderText), RenderText_should_stay_small);
65 class SecureTextTimer;
66 typedef HashMap<RenderText*, SecureTextTimer*> SecureTextTimerMap;
67 static SecureTextTimerMap* gSecureTextTimers = 0;
69 class SecureTextTimer : public TimerBase {
71 SecureTextTimer(RenderText* renderText)
72 : m_renderText(renderText)
73 , m_lastTypedCharacterOffset(-1)
77 void restartWithNewText(unsigned lastTypedCharacterOffset)
79 m_lastTypedCharacterOffset = lastTypedCharacterOffset;
80 if (Settings* settings = m_renderText->document()->settings())
81 startOneShot(settings->passwordEchoDurationInSeconds());
83 void invalidate() { m_lastTypedCharacterOffset = -1; }
84 unsigned lastTypedCharacterOffset() { return m_lastTypedCharacterOffset; }
89 ASSERT(gSecureTextTimers->contains(m_renderText));
90 m_renderText->setText(m_renderText->text(), true /* forcing setting text as it may be masked later */);
93 RenderText* m_renderText;
94 int m_lastTypedCharacterOffset;
97 static void makeCapitalized(String* string, UChar previous)
102 unsigned length = string->length();
103 const UChar* characters = string->characters();
105 if (length >= numeric_limits<unsigned>::max())
108 StringBuffer<UChar> stringWithPrevious(length + 1);
109 stringWithPrevious[0] = previous == noBreakSpace ? ' ' : previous;
110 for (unsigned i = 1; i < length + 1; i++) {
111 // Replace   with a real space since ICU no longer treats   as a word separator.
112 if (characters[i - 1] == noBreakSpace)
113 stringWithPrevious[i] = ' ';
115 stringWithPrevious[i] = characters[i - 1];
118 TextBreakIterator* boundary = wordBreakIterator(stringWithPrevious.characters(), length + 1);
122 StringBuffer<UChar> data(length);
125 int32_t startOfWord = textBreakFirst(boundary);
126 for (endOfWord = textBreakNext(boundary); endOfWord != TextBreakDone; startOfWord = endOfWord, endOfWord = textBreakNext(boundary)) {
127 if (startOfWord) // Ignore first char of previous string
128 data[startOfWord - 1] = characters[startOfWord - 1] == noBreakSpace ? noBreakSpace : toTitleCase(stringWithPrevious[startOfWord]);
129 for (int i = startOfWord + 1; i < endOfWord; i++)
130 data[i - 1] = characters[i - 1];
133 *string = String::adopt(data);
136 RenderText::RenderText(Node* node, PassRefPtr<StringImpl> str)
137 : RenderObject(!node || node->isDocumentNode() ? 0 : node)
139 , m_linesDirty(false)
140 , m_containsReversedText(false)
141 , m_knownToHaveNoOverflowAndNoFallbackFonts(false)
142 , m_needsTranscoding(false)
152 // FIXME: Some clients of RenderText (and subclasses) pass Document as node to create anonymous renderer.
153 // They should be switched to passing null and using setDocumentForAnonymous.
154 if (node && node->isDocumentNode())
155 setDocumentForAnonymous(toDocument(node));
157 m_isAllASCII = m_text.containsOnlyASCII();
158 m_canUseSimpleFontCodePath = computeCanUseSimpleFontCodePath();
161 view()->frameView()->incrementVisuallyNonEmptyCharacterCount(m_text.length());
166 RenderText::~RenderText()
168 ASSERT(!m_firstTextBox);
169 ASSERT(!m_lastTextBox);
174 const char* RenderText::renderName() const
179 bool RenderText::isTextFragment() const
184 bool RenderText::isWordBreak() const
189 void RenderText::updateNeedsTranscoding()
191 const TextEncoding* encoding = document()->decoder() ? &document()->decoder()->encoding() : 0;
192 m_needsTranscoding = fontTranscoder().needsTranscoding(style()->font().fontDescription(), encoding);
195 void RenderText::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
197 // There is no need to ever schedule repaints from a style change of a text run, since
198 // we already did this for the parent of the text run.
199 // We do have to schedule layouts, though, since a style change can force us to
201 if (diff == StyleDifferenceLayout) {
202 setNeedsLayoutAndPrefWidthsRecalc();
203 m_knownToHaveNoOverflowAndNoFallbackFonts = false;
206 RenderStyle* newStyle = style();
207 bool needsResetText = false;
209 updateNeedsTranscoding();
210 needsResetText = m_needsTranscoding;
211 } else if (oldStyle->font().needsTranscoding() != newStyle->font().needsTranscoding() || (newStyle->font().needsTranscoding() && oldStyle->font().firstFamily() != newStyle->font().firstFamily())) {
212 updateNeedsTranscoding();
213 needsResetText = true;
216 ETextTransform oldTransform = oldStyle ? oldStyle->textTransform() : TTNONE;
217 ETextSecurity oldSecurity = oldStyle ? oldStyle->textSecurity() : TSNONE;
218 if (needsResetText || oldTransform != newStyle->textTransform() || oldSecurity != newStyle->textSecurity())
222 void RenderText::removeAndDestroyTextBoxes()
224 if (!documentBeingDestroyed()) {
225 if (firstTextBox()) {
227 RootInlineBox* next = firstTextBox()->root()->nextRootBox();
231 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
234 parent()->dirtyLinesFromChangedChild(this);
239 void RenderText::willBeDestroyed()
241 if (SecureTextTimer* secureTextTimer = gSecureTextTimers ? gSecureTextTimers->take(this) : 0)
242 delete secureTextTimer;
244 removeAndDestroyTextBoxes();
245 RenderObject::willBeDestroyed();
248 void RenderText::extractTextBox(InlineTextBox* box)
252 m_lastTextBox = box->prevTextBox();
253 if (box == m_firstTextBox)
255 if (box->prevTextBox())
256 box->prevTextBox()->setNextTextBox(0);
257 box->setPreviousTextBox(0);
258 for (InlineTextBox* curr = box; curr; curr = curr->nextTextBox())
259 curr->setExtracted();
264 void RenderText::attachTextBox(InlineTextBox* box)
269 m_lastTextBox->setNextTextBox(box);
270 box->setPreviousTextBox(m_lastTextBox);
272 m_firstTextBox = box;
273 InlineTextBox* last = box;
274 for (InlineTextBox* curr = box; curr; curr = curr->nextTextBox()) {
275 curr->setExtracted(false);
278 m_lastTextBox = last;
283 void RenderText::removeTextBox(InlineTextBox* box)
287 if (box == m_firstTextBox)
288 m_firstTextBox = box->nextTextBox();
289 if (box == m_lastTextBox)
290 m_lastTextBox = box->prevTextBox();
291 if (box->nextTextBox())
292 box->nextTextBox()->setPreviousTextBox(box->prevTextBox());
293 if (box->prevTextBox())
294 box->prevTextBox()->setNextTextBox(box->nextTextBox());
299 void RenderText::deleteTextBoxes()
301 if (firstTextBox()) {
302 RenderArena* arena = renderArena();
304 for (InlineTextBox* curr = firstTextBox(); curr; curr = next) {
305 next = curr->nextTextBox();
306 curr->destroy(arena);
308 m_firstTextBox = m_lastTextBox = 0;
312 PassRefPtr<StringImpl> RenderText::originalText() const
315 return (e && e->isTextNode()) ? toText(e)->dataImpl() : 0;
318 void RenderText::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
320 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
321 rects.append(enclosingIntRect(FloatRect(accumulatedOffset + box->topLeft(), box->size())));
324 static FloatRect localQuadForTextBox(InlineTextBox* box, unsigned start, unsigned end, bool useSelectionHeight)
326 unsigned realEnd = min(box->end() + 1, end);
327 LayoutRect r = box->localSelectionRect(start, realEnd);
329 if (!useSelectionHeight) {
330 // Change the height and y position (or width and x for vertical text)
331 // because selectionRect uses selection-specific values.
332 if (box->isHorizontal()) {
333 r.setHeight(box->logicalHeight());
336 r.setWidth(box->logicalWidth());
345 void RenderText::absoluteRectsForRange(Vector<IntRect>& rects, unsigned start, unsigned end, bool useSelectionHeight, bool* wasFixed)
347 // Work around signed/unsigned issues. This function takes unsigneds, and is often passed UINT_MAX
348 // to mean "all the way to the end". InlineTextBox coordinates are unsigneds, so changing this
349 // function to take ints causes various internal mismatches. But selectionRect takes ints, and
350 // passing UINT_MAX to it causes trouble. Ideally we'd change selectionRect to take unsigneds, but
351 // that would cause many ripple effects, so for now we'll just clamp our unsigned parameters to INT_MAX.
352 ASSERT(end == UINT_MAX || end <= INT_MAX);
353 ASSERT(start <= INT_MAX);
354 start = min(start, static_cast<unsigned>(INT_MAX));
355 end = min(end, static_cast<unsigned>(INT_MAX));
357 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
358 // Note: box->end() returns the index of the last character, not the index past it
359 if (start <= box->start() && box->end() < end) {
360 FloatRect r = box->calculateBoundaries();
361 if (useSelectionHeight) {
362 LayoutRect selectionRect = box->localSelectionRect(start, end);
363 if (box->isHorizontal()) {
364 r.setHeight(selectionRect.height());
365 r.setY(selectionRect.y());
367 r.setWidth(selectionRect.width());
368 r.setX(selectionRect.x());
371 rects.append(localToAbsoluteQuad(r, 0, wasFixed).enclosingBoundingBox());
373 // FIXME: This code is wrong. It's converting local to absolute twice. http://webkit.org/b/65722
374 FloatRect rect = localQuadForTextBox(box, start, end, useSelectionHeight);
376 rects.append(localToAbsoluteQuad(rect, 0, wasFixed).enclosingBoundingBox());
381 static IntRect ellipsisRectForBox(InlineTextBox* box, unsigned startPos, unsigned endPos)
386 unsigned short truncation = box->truncation();
387 if (truncation == cNoTruncation)
391 if (EllipsisBox* ellipsis = box->root()->ellipsisBox()) {
392 int ellipsisStartPosition = max<int>(startPos - box->start(), 0);
393 int ellipsisEndPosition = min<int>(endPos - box->start(), box->len());
395 // The ellipsis should be considered to be selected if the end of
396 // the selection is past the beginning of the truncation and the
397 // beginning of the selection is before or at the beginning of the truncation.
398 if (ellipsisEndPosition >= truncation && ellipsisStartPosition <= truncation)
399 return ellipsis->selectionRect();
405 void RenderText::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed, ClippingOption option) const
407 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
408 FloatRect boundaries = box->calculateBoundaries();
410 // Shorten the width of this text box if it ends in an ellipsis.
411 // FIXME: ellipsisRectForBox should switch to return FloatRect soon with the subpixellayout branch.
412 IntRect ellipsisRect = (option == ClipToEllipsis) ? ellipsisRectForBox(box, 0, textLength()) : IntRect();
413 if (!ellipsisRect.isEmpty()) {
414 if (style()->isHorizontalWritingMode())
415 boundaries.setWidth(ellipsisRect.maxX() - boundaries.x());
417 boundaries.setHeight(ellipsisRect.maxY() - boundaries.y());
419 quads.append(localToAbsoluteQuad(boundaries, 0, wasFixed));
423 void RenderText::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
425 absoluteQuads(quads, wasFixed, NoClipping);
428 void RenderText::absoluteQuadsForRange(Vector<FloatQuad>& quads, unsigned start, unsigned end, bool useSelectionHeight, bool* wasFixed)
430 // Work around signed/unsigned issues. This function takes unsigneds, and is often passed UINT_MAX
431 // to mean "all the way to the end". InlineTextBox coordinates are unsigneds, so changing this
432 // function to take ints causes various internal mismatches. But selectionRect takes ints, and
433 // passing UINT_MAX to it causes trouble. Ideally we'd change selectionRect to take unsigneds, but
434 // that would cause many ripple effects, so for now we'll just clamp our unsigned parameters to INT_MAX.
435 ASSERT(end == UINT_MAX || end <= INT_MAX);
436 ASSERT(start <= INT_MAX);
437 start = min(start, static_cast<unsigned>(INT_MAX));
438 end = min(end, static_cast<unsigned>(INT_MAX));
440 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
441 // Note: box->end() returns the index of the last character, not the index past it
442 if (start <= box->start() && box->end() < end) {
443 FloatRect r = box->calculateBoundaries();
444 if (useSelectionHeight) {
445 LayoutRect selectionRect = box->localSelectionRect(start, end);
446 if (box->isHorizontal()) {
447 r.setHeight(selectionRect.height());
448 r.setY(selectionRect.y());
450 r.setWidth(selectionRect.width());
451 r.setX(selectionRect.x());
454 quads.append(localToAbsoluteQuad(r, 0, wasFixed));
456 FloatRect rect = localQuadForTextBox(box, start, end, useSelectionHeight);
458 quads.append(localToAbsoluteQuad(rect, 0, wasFixed));
463 InlineTextBox* RenderText::findNextInlineTextBox(int offset, int& pos) const
465 // The text runs point to parts of the RenderText's m_text
466 // (they don't include '\n')
467 // Find the text run that includes the character at offset
468 // and return pos, which is the position of the char in the run.
473 InlineTextBox* s = m_firstTextBox;
475 while (offset > off && s->nextTextBox()) {
476 s = s->nextTextBox();
477 off = s->start() + s->len();
479 // we are now in the correct text run
480 pos = (offset > off ? s->len() : s->len() - (off - offset) );
484 enum ShouldAffinityBeDownstream { AlwaysDownstream, AlwaysUpstream, UpstreamIfPositionIsNotAtStart };
486 static bool lineDirectionPointFitsInBox(int pointLineDirection, InlineTextBox* box, ShouldAffinityBeDownstream& shouldAffinityBeDownstream)
488 shouldAffinityBeDownstream = AlwaysDownstream;
490 // the x coordinate is equal to the left edge of this box
491 // the affinity must be downstream so the position doesn't jump back to the previous line
492 // except when box is the first box in the line
493 if (pointLineDirection <= box->logicalLeft()) {
494 shouldAffinityBeDownstream = !box->prevLeafChild() ? UpstreamIfPositionIsNotAtStart : AlwaysDownstream;
498 // and the x coordinate is to the left of the right edge of this box
499 // check to see if position goes in this box
500 if (pointLineDirection < box->logicalRight()) {
501 shouldAffinityBeDownstream = UpstreamIfPositionIsNotAtStart;
505 // box is first on line
506 // and the x coordinate is to the left of the first text box left edge
507 if (!box->prevLeafChildIgnoringLineBreak() && pointLineDirection < box->logicalLeft())
510 if (!box->nextLeafChildIgnoringLineBreak()) {
511 // box is last on line
512 // and the x coordinate is to the right of the last text box right edge
513 // generate VisiblePosition, use UPSTREAM affinity if possible
514 shouldAffinityBeDownstream = UpstreamIfPositionIsNotAtStart;
521 static VisiblePosition createVisiblePositionForBox(const InlineBox* box, int offset, ShouldAffinityBeDownstream shouldAffinityBeDownstream)
523 EAffinity affinity = VP_DEFAULT_AFFINITY;
524 switch (shouldAffinityBeDownstream) {
525 case AlwaysDownstream:
526 affinity = DOWNSTREAM;
529 affinity = VP_UPSTREAM_IF_POSSIBLE;
531 case UpstreamIfPositionIsNotAtStart:
532 affinity = offset > box->caretMinOffset() ? VP_UPSTREAM_IF_POSSIBLE : DOWNSTREAM;
535 return box->renderer()->createVisiblePosition(offset, affinity);
538 static VisiblePosition createVisiblePositionAfterAdjustingOffsetForBiDi(const InlineTextBox* box, int offset, ShouldAffinityBeDownstream shouldAffinityBeDownstream)
541 ASSERT(box->renderer());
544 if (offset && static_cast<unsigned>(offset) < box->len())
545 return createVisiblePositionForBox(box, box->start() + offset, shouldAffinityBeDownstream);
547 bool positionIsAtStartOfBox = !offset;
548 if (positionIsAtStartOfBox == box->isLeftToRightDirection()) {
549 // offset is on the left edge
551 const InlineBox* prevBox = box->prevLeafChildIgnoringLineBreak();
552 if ((prevBox && prevBox->bidiLevel() == box->bidiLevel())
553 || box->renderer()->containingBlock()->style()->direction() == box->direction()) // FIXME: left on 12CBA
554 return createVisiblePositionForBox(box, box->caretLeftmostOffset(), shouldAffinityBeDownstream);
556 if (prevBox && prevBox->bidiLevel() > box->bidiLevel()) {
557 // e.g. left of B in aDC12BAb
558 const InlineBox* leftmostBox;
560 leftmostBox = prevBox;
561 prevBox = leftmostBox->prevLeafChildIgnoringLineBreak();
562 } while (prevBox && prevBox->bidiLevel() > box->bidiLevel());
563 return createVisiblePositionForBox(leftmostBox, leftmostBox->caretRightmostOffset(), shouldAffinityBeDownstream);
566 if (!prevBox || prevBox->bidiLevel() < box->bidiLevel()) {
567 // e.g. left of D in aDC12BAb
568 const InlineBox* rightmostBox;
569 const InlineBox* nextBox = box;
571 rightmostBox = nextBox;
572 nextBox = rightmostBox->nextLeafChildIgnoringLineBreak();
573 } while (nextBox && nextBox->bidiLevel() >= box->bidiLevel());
574 return createVisiblePositionForBox(rightmostBox,
575 box->isLeftToRightDirection() ? rightmostBox->caretMaxOffset() : rightmostBox->caretMinOffset(), shouldAffinityBeDownstream);
578 return createVisiblePositionForBox(box, box->caretRightmostOffset(), shouldAffinityBeDownstream);
581 const InlineBox* nextBox = box->nextLeafChildIgnoringLineBreak();
582 if ((nextBox && nextBox->bidiLevel() == box->bidiLevel())
583 || box->renderer()->containingBlock()->style()->direction() == box->direction())
584 return createVisiblePositionForBox(box, box->caretRightmostOffset(), shouldAffinityBeDownstream);
586 // offset is on the right edge
587 if (nextBox && nextBox->bidiLevel() > box->bidiLevel()) {
588 // e.g. right of C in aDC12BAb
589 const InlineBox* rightmostBox;
591 rightmostBox = nextBox;
592 nextBox = rightmostBox->nextLeafChildIgnoringLineBreak();
593 } while (nextBox && nextBox->bidiLevel() > box->bidiLevel());
594 return createVisiblePositionForBox(rightmostBox, rightmostBox->caretLeftmostOffset(), shouldAffinityBeDownstream);
597 if (!nextBox || nextBox->bidiLevel() < box->bidiLevel()) {
598 // e.g. right of A in aDC12BAb
599 const InlineBox* leftmostBox;
600 const InlineBox* prevBox = box;
602 leftmostBox = prevBox;
603 prevBox = leftmostBox->prevLeafChildIgnoringLineBreak();
604 } while (prevBox && prevBox->bidiLevel() >= box->bidiLevel());
605 return createVisiblePositionForBox(leftmostBox,
606 box->isLeftToRightDirection() ? leftmostBox->caretMinOffset() : leftmostBox->caretMaxOffset(), shouldAffinityBeDownstream);
609 return createVisiblePositionForBox(box, box->caretLeftmostOffset(), shouldAffinityBeDownstream);
612 VisiblePosition RenderText::positionForPoint(const LayoutPoint& point)
614 if (!firstTextBox() || textLength() == 0)
615 return createVisiblePosition(0, DOWNSTREAM);
617 LayoutUnit pointLineDirection = firstTextBox()->isHorizontal() ? point.x() : point.y();
618 LayoutUnit pointBlockDirection = firstTextBox()->isHorizontal() ? point.y() : point.x();
619 bool blocksAreFlipped = style()->isFlippedBlocksWritingMode();
621 InlineTextBox* lastBox = 0;
622 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
623 if (box->isLineBreak() && !box->prevLeafChild() && box->nextLeafChild() && !box->nextLeafChild()->isLineBreak())
624 box = box->nextTextBox();
626 RootInlineBox* rootBox = box->root();
627 LayoutUnit top = min(rootBox->selectionTop(), rootBox->lineTop());
628 if (pointBlockDirection > top || (!blocksAreFlipped && pointBlockDirection == top)) {
629 LayoutUnit bottom = rootBox->selectionBottom();
630 if (rootBox->nextRootBox())
631 bottom = min(bottom, rootBox->nextRootBox()->lineTop());
633 if (pointBlockDirection < bottom || (blocksAreFlipped && pointBlockDirection == bottom)) {
634 ShouldAffinityBeDownstream shouldAffinityBeDownstream;
635 if (lineDirectionPointFitsInBox(pointLineDirection, box, shouldAffinityBeDownstream))
636 return createVisiblePositionAfterAdjustingOffsetForBiDi(box, box->offsetForPosition(pointLineDirection), shouldAffinityBeDownstream);
643 ShouldAffinityBeDownstream shouldAffinityBeDownstream;
644 lineDirectionPointFitsInBox(pointLineDirection, lastBox, shouldAffinityBeDownstream);
645 return createVisiblePositionAfterAdjustingOffsetForBiDi(lastBox, lastBox->offsetForPosition(pointLineDirection) + lastBox->start(), shouldAffinityBeDownstream);
647 return createVisiblePosition(0, DOWNSTREAM);
650 LayoutRect RenderText::localCaretRect(InlineBox* inlineBox, int caretOffset, LayoutUnit* extraWidthToEndOfLine)
655 ASSERT(inlineBox->isInlineTextBox());
656 if (!inlineBox->isInlineTextBox())
659 InlineTextBox* box = toInlineTextBox(inlineBox);
661 int height = box->root()->selectionHeight();
662 int top = box->root()->selectionTop();
664 // Go ahead and round left to snap it to the nearest pixel.
665 float left = box->positionForOffset(caretOffset);
667 // Distribute the caret's width to either side of the offset.
668 int caretWidthLeftOfOffset = caretWidth / 2;
669 left -= caretWidthLeftOfOffset;
670 int caretWidthRightOfOffset = caretWidth - caretWidthLeftOfOffset;
674 float rootLeft = box->root()->logicalLeft();
675 float rootRight = box->root()->logicalRight();
677 // FIXME: should we use the width of the root inline box or the
678 // width of the containing block for this?
679 if (extraWidthToEndOfLine)
680 *extraWidthToEndOfLine = (box->root()->logicalWidth() + rootLeft) - (left + 1);
682 RenderBlock* cb = containingBlock();
683 RenderStyle* cbStyle = cb->style();
687 leftEdge = min<float>(0, rootLeft);
688 rightEdge = max<float>(cb->logicalWidth(), rootRight);
690 bool rightAligned = false;
691 switch (cbStyle->textAlign()) {
703 rightAligned = !cbStyle->isLeftToRightDirection();
706 rightAligned = cbStyle->isLeftToRightDirection();
711 left = max(left, leftEdge);
712 left = min(left, rootRight - caretWidth);
714 left = min(left, rightEdge - caretWidthRightOfOffset);
715 left = max(left, rootLeft);
718 return style()->isHorizontalWritingMode() ? IntRect(left, top, caretWidth, height) : IntRect(top, left, height, caretWidth);
721 ALWAYS_INLINE float RenderText::widthFromCache(const Font& f, int start, int len, float xPos, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
723 if (style()->hasTextCombine() && isCombineText()) {
724 const RenderCombineText* combineText = toRenderCombineText(this);
725 if (combineText->isCombined())
726 return combineText->combinedTextWidth(f);
729 if (f.isFixedPitch() && !f.isSmallCaps() && m_isAllASCII && (!glyphOverflow || !glyphOverflow->computeBounds)) {
730 float monospaceCharacterWidth = f.spaceWidth();
734 StringImpl& text = *m_text.impl();
735 for (int i = start; i < start + len; i++) {
738 if (c == ' ' || c == '\n') {
739 w += monospaceCharacterWidth;
741 } else if (c == '\t') {
742 if (style()->collapseWhiteSpace()) {
743 w += monospaceCharacterWidth;
746 w += f.tabWidth(style()->tabSize(), xPos + w);
752 w += monospaceCharacterWidth;
755 if (isSpace && i > start)
756 w += f.wordSpacing();
761 TextRun run = RenderBlock::constructTextRun(const_cast<RenderText*>(this), f, this, start, len, style());
762 run.setCharactersLength(textLength() - start);
763 ASSERT(run.charactersLength() >= run.length());
765 run.setCharacterScanForCodePath(!canUseSimpleFontCodePath());
766 run.setTabSize(!style()->collapseWhiteSpace(), style()->tabSize());
768 return f.width(run, fallbackFonts, glyphOverflow);
771 void RenderText::trimmedPrefWidths(float leadWidth,
772 float& beginMinW, bool& beginWS,
773 float& endMinW, bool& endWS,
774 bool& hasBreakableChar, bool& hasBreak,
775 float& beginMaxW, float& endMaxW,
776 float& minW, float& maxW, bool& stripFrontSpaces)
778 bool collapseWhiteSpace = style()->collapseWhiteSpace();
779 if (!collapseWhiteSpace)
780 stripFrontSpaces = false;
782 if (m_hasTab || preferredLogicalWidthsDirty())
783 computePreferredLogicalWidths(leadWidth);
785 beginWS = !stripFrontSpaces && m_hasBeginWS;
788 int len = textLength();
790 if (!len || (stripFrontSpaces && text()->containsOnlyWhitespace())) {
804 beginMinW = m_beginMinWidth;
805 endMinW = m_endMinWidth;
807 hasBreakableChar = m_hasBreakableChar;
808 hasBreak = m_hasBreak;
811 StringImpl& text = *m_text.impl();
812 if (text[0] == ' ' || (text[0] == '\n' && !style()->preserveNewline()) || text[0] == '\t') {
813 const Font& font = style()->font(); // FIXME: This ignores first-line.
814 if (stripFrontSpaces) {
815 const UChar space = ' ';
816 float spaceWidth = font.width(RenderBlock::constructTextRun(this, font, &space, 1, style()));
819 maxW += font.wordSpacing();
822 stripFrontSpaces = collapseWhiteSpace && m_hasEndWS;
824 if (!style()->autoWrap() || minW > maxW)
827 // Compute our max widths by scanning the string for newlines.
829 const Font& f = style()->font(); // FIXME: This ignores first-line.
830 bool firstLine = true;
833 for (int i = 0; i < len; i++) {
835 while (i + linelen < len && text[i + linelen] != '\n')
839 endMaxW = widthFromCache(f, i, linelen, leadWidth + endMaxW, 0, 0);
846 } else if (firstLine) {
853 // A <pre> run that ends with a newline, as in, e.g.,
854 // <pre>Some text\n\n<span>More text</pre>
860 static inline bool isSpaceAccordingToStyle(UChar c, RenderStyle* style)
862 return c == ' ' || (c == noBreakSpace && style->nbspMode() == SPACE);
865 float RenderText::minLogicalWidth() const
867 if (preferredLogicalWidthsDirty())
868 const_cast<RenderText*>(this)->computePreferredLogicalWidths(0);
873 float RenderText::maxLogicalWidth() const
875 if (preferredLogicalWidthsDirty())
876 const_cast<RenderText*>(this)->computePreferredLogicalWidths(0);
881 void RenderText::computePreferredLogicalWidths(float leadWidth)
883 HashSet<const SimpleFontData*> fallbackFonts;
884 GlyphOverflow glyphOverflow;
885 computePreferredLogicalWidths(leadWidth, fallbackFonts, glyphOverflow);
886 if (fallbackFonts.isEmpty() && !glyphOverflow.left && !glyphOverflow.right && !glyphOverflow.top && !glyphOverflow.bottom)
887 m_knownToHaveNoOverflowAndNoFallbackFonts = true;
890 static inline float hyphenWidth(RenderText* renderer, const Font& font)
892 RenderStyle* style = renderer->style();
893 return font.width(RenderBlock::constructTextRun(renderer, font, style->hyphenString().string(), style));
896 static float maxWordFragmentWidth(RenderText* renderer, RenderStyle* style, const Font& font, const UChar* word, int wordLength, int minimumPrefixLength, int minimumSuffixLength, int& suffixStart, HashSet<const SimpleFontData*>& fallbackFonts, GlyphOverflow& glyphOverflow)
899 if (wordLength <= minimumSuffixLength)
902 Vector<int, 8> hyphenLocations;
903 int hyphenLocation = wordLength - minimumSuffixLength;
904 while ((hyphenLocation = lastHyphenLocation(word, wordLength, hyphenLocation, style->locale())) >= minimumPrefixLength)
905 hyphenLocations.append(hyphenLocation);
907 if (hyphenLocations.isEmpty())
910 hyphenLocations.reverse();
912 float minimumFragmentWidthToConsider = font.pixelSize() * 5 / 4 + hyphenWidth(renderer, font);
913 float maxFragmentWidth = 0;
914 for (size_t k = 0; k < hyphenLocations.size(); ++k) {
915 int fragmentLength = hyphenLocations[k] - suffixStart;
916 StringBuilder fragmentWithHyphen;
917 fragmentWithHyphen.append(word + suffixStart, fragmentLength);
918 fragmentWithHyphen.append(style->hyphenString());
920 TextRun run = RenderBlock::constructTextRun(renderer, font, fragmentWithHyphen.characters(), fragmentWithHyphen.length(), style);
921 run.setCharactersLength(fragmentWithHyphen.length());
922 run.setCharacterScanForCodePath(!renderer->canUseSimpleFontCodePath());
923 float fragmentWidth = font.width(run, &fallbackFonts, &glyphOverflow);
925 // Narrow prefixes are ignored. See tryHyphenating in RenderBlockLineLayout.cpp.
926 if (fragmentWidth <= minimumFragmentWidthToConsider)
929 suffixStart += fragmentLength;
930 maxFragmentWidth = max(maxFragmentWidth, fragmentWidth);
933 return maxFragmentWidth;
936 void RenderText::computePreferredLogicalWidths(float leadWidth, HashSet<const SimpleFontData*>& fallbackFonts, GlyphOverflow& glyphOverflow)
938 ASSERT(m_hasTab || preferredLogicalWidthsDirty() || !m_knownToHaveNoOverflowAndNoFallbackFonts);
948 float currMinWidth = 0;
949 float currMaxWidth = 0;
950 m_hasBreakableChar = false;
953 m_hasBeginWS = false;
956 RenderStyle* styleToUse = style();
957 const Font& f = styleToUse->font(); // FIXME: This ignores first-line.
958 float wordSpacing = styleToUse->wordSpacing();
959 int len = textLength();
960 LazyLineBreakIterator breakIterator(m_text, styleToUse->locale());
961 bool needsWordSpacing = false;
962 bool ignoringSpaces = false;
963 bool isSpace = false;
964 bool firstWord = true;
965 bool firstLine = true;
966 int nextBreakable = -1;
967 int lastWordBoundary = 0;
969 // Non-zero only when kerning is enabled, in which case we measure words with their trailing
970 // space, then subtract its width.
971 float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(RenderBlock::constructTextRun(this, f, &space, 1, styleToUse), &fallbackFonts) + wordSpacing : 0;
973 // If automatic hyphenation is allowed, we keep track of the width of the widest word (or word
974 // fragment) encountered so far, and only try hyphenating words that are wider.
975 float maxWordWidth = numeric_limits<float>::max();
976 int minimumPrefixLength = 0;
977 int minimumSuffixLength = 0;
978 if (styleToUse->hyphens() == HyphensAuto && canHyphenate(styleToUse->locale())) {
981 // Map 'hyphenate-limit-{before,after}: auto;' to 2.
982 minimumPrefixLength = styleToUse->hyphenationLimitBefore();
983 if (minimumPrefixLength < 0)
984 minimumPrefixLength = 2;
986 minimumSuffixLength = styleToUse->hyphenationLimitAfter();
987 if (minimumSuffixLength < 0)
988 minimumSuffixLength = 2;
991 int firstGlyphLeftOverflow = -1;
993 bool breakNBSP = styleToUse->autoWrap() && styleToUse->nbspMode() == SPACE;
994 bool breakAll = (styleToUse->wordBreak() == BreakAllWordBreak || styleToUse->wordBreak() == BreakWordBreak) && styleToUse->autoWrap();
996 for (int i = 0; i < len; i++) {
997 UChar c = characterAt(i);
999 bool previousCharacterIsSpace = isSpace;
1001 bool isNewline = false;
1003 if (styleToUse->preserveNewline()) {
1009 } else if (c == '\t') {
1010 if (!styleToUse->collapseWhiteSpace()) {
1018 if ((isSpace || isNewline) && !i)
1019 m_hasBeginWS = true;
1020 if ((isSpace || isNewline) && i == len - 1)
1023 if (!ignoringSpaces && styleToUse->collapseWhiteSpace() && previousCharacterIsSpace && isSpace)
1024 ignoringSpaces = true;
1026 if (ignoringSpaces && !isSpace)
1027 ignoringSpaces = false;
1029 // Ignore spaces and soft hyphens
1030 if (ignoringSpaces) {
1031 ASSERT(lastWordBoundary == i);
1034 } else if (c == softHyphen && styleToUse->hyphens() != HyphensNone) {
1035 currMaxWidth += widthFromCache(f, lastWordBoundary, i - lastWordBoundary, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow);
1036 if (firstGlyphLeftOverflow < 0)
1037 firstGlyphLeftOverflow = glyphOverflow.left;
1038 lastWordBoundary = i + 1;
1042 bool hasBreak = breakAll || isBreakable(breakIterator, i, nextBreakable, breakNBSP);
1043 bool betweenWords = true;
1045 while (c != '\n' && !isSpaceAccordingToStyle(c, styleToUse) && c != '\t' && (c != softHyphen || styleToUse->hyphens() == HyphensNone)) {
1050 if (isBreakable(breakIterator, j, nextBreakable, breakNBSP) && characterAt(j - 1) != softHyphen)
1053 betweenWords = false;
1058 int wordLen = j - i;
1060 bool isSpace = (j < len) && isSpaceAccordingToStyle(c, styleToUse);
1062 if (wordTrailingSpaceWidth && isSpace)
1063 w = widthFromCache(f, i, wordLen + 1, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow) - wordTrailingSpaceWidth;
1065 w = widthFromCache(f, i, wordLen, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow);
1066 if (c == softHyphen && styleToUse->hyphens() != HyphensNone)
1067 currMinWidth += hyphenWidth(this, f);
1070 if (w > maxWordWidth) {
1072 float maxFragmentWidth = maxWordFragmentWidth(this, styleToUse, f, characters() + i, wordLen, minimumPrefixLength, minimumSuffixLength, suffixStart, fallbackFonts, glyphOverflow);
1076 if (wordTrailingSpaceWidth && isSpace)
1077 suffixWidth = widthFromCache(f, i + suffixStart, wordLen - suffixStart + 1, leadWidth + currMaxWidth, 0, 0) - wordTrailingSpaceWidth;
1079 suffixWidth = widthFromCache(f, i + suffixStart, wordLen - suffixStart, leadWidth + currMaxWidth, 0, 0);
1081 maxFragmentWidth = max(maxFragmentWidth, suffixWidth);
1083 currMinWidth += maxFragmentWidth - w;
1084 maxWordWidth = max(maxWordWidth, maxFragmentWidth);
1089 if (firstGlyphLeftOverflow < 0)
1090 firstGlyphLeftOverflow = glyphOverflow.left;
1093 if (lastWordBoundary == i)
1096 currMaxWidth += widthFromCache(f, lastWordBoundary, j - lastWordBoundary, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow);
1097 lastWordBoundary = j;
1100 bool isCollapsibleWhiteSpace = (j < len) && styleToUse->isCollapsibleWhiteSpace(c);
1101 if (j < len && styleToUse->autoWrap())
1102 m_hasBreakableChar = true;
1104 // Add in wordSpacing to our currMaxWidth, but not if this is the last word on a line or the
1105 // last word in the run.
1106 if (wordSpacing && (isSpace || isCollapsibleWhiteSpace) && !containsOnlyWhitespace(j, len-j))
1107 currMaxWidth += wordSpacing;
1111 // If the first character in the run is breakable, then we consider ourselves to have a beginning
1112 // minimum width of 0, since a break could occur right before our run starts, preventing us from ever
1113 // being appended to a previous text run when considering the total minimum width of the containing block.
1115 m_hasBreakableChar = true;
1116 m_beginMinWidth = hasBreak ? 0 : currMinWidth;
1118 m_endMinWidth = currMinWidth;
1120 if (currMinWidth > m_minWidth)
1121 m_minWidth = currMinWidth;
1126 // Nowrap can never be broken, so don't bother setting the
1127 // breakable character boolean. Pre can only be broken if we encounter a newline.
1128 if (style()->autoWrap() || isNewline)
1129 m_hasBreakableChar = true;
1131 if (currMinWidth > m_minWidth)
1132 m_minWidth = currMinWidth;
1135 if (isNewline) { // Only set if preserveNewline was true and we saw a newline.
1139 if (!styleToUse->autoWrap())
1140 m_beginMinWidth = currMaxWidth;
1143 if (currMaxWidth > m_maxWidth)
1144 m_maxWidth = currMaxWidth;
1147 TextRun run = RenderBlock::constructTextRun(this, f, this, i, 1, styleToUse);
1148 run.setCharactersLength(len - i);
1149 ASSERT(run.charactersLength() >= run.length());
1150 run.setTabSize(!style()->collapseWhiteSpace(), style()->tabSize());
1151 run.setXPos(leadWidth + currMaxWidth);
1153 currMaxWidth += f.width(run, &fallbackFonts);
1154 glyphOverflow.right = 0;
1155 needsWordSpacing = isSpace && !previousCharacterIsSpace && i == len - 1;
1157 ASSERT(lastWordBoundary == i);
1162 if (firstGlyphLeftOverflow > 0)
1163 glyphOverflow.left = firstGlyphLeftOverflow;
1165 if ((needsWordSpacing && len > 1) || (ignoringSpaces && !firstWord))
1166 currMaxWidth += wordSpacing;
1168 m_minWidth = max(currMinWidth, m_minWidth);
1169 m_maxWidth = max(currMaxWidth, m_maxWidth);
1171 if (!styleToUse->autoWrap())
1172 m_minWidth = m_maxWidth;
1174 if (styleToUse->whiteSpace() == PRE) {
1176 m_beginMinWidth = m_maxWidth;
1177 m_endMinWidth = currMaxWidth;
1180 setPreferredLogicalWidthsDirty(false);
1183 bool RenderText::isAllCollapsibleWhitespace() const
1185 unsigned length = textLength();
1187 for (unsigned i = 0; i < length; ++i) {
1188 if (!style()->isCollapsibleWhiteSpace(characters8()[i]))
1193 for (unsigned i = 0; i < length; ++i) {
1194 if (!style()->isCollapsibleWhiteSpace(characters16()[i]))
1200 bool RenderText::containsOnlyWhitespace(unsigned from, unsigned len) const
1203 StringImpl& text = *m_text.impl();
1205 for (currPos = from;
1206 currPos < from + len && (text[currPos] == '\n' || text[currPos] == ' ' || text[currPos] == '\t');
1208 return currPos >= (from + len);
1211 FloatPoint RenderText::firstRunOrigin() const
1213 return IntPoint(firstRunX(), firstRunY());
1216 float RenderText::firstRunX() const
1218 return m_firstTextBox ? m_firstTextBox->x() : 0;
1221 float RenderText::firstRunY() const
1223 return m_firstTextBox ? m_firstTextBox->y() : 0;
1226 void RenderText::setSelectionState(SelectionState state)
1228 RenderObject::setSelectionState(state);
1230 if (canUpdateSelectionOnRootLineBoxes()) {
1231 if (state == SelectionStart || state == SelectionEnd || state == SelectionBoth) {
1232 int startPos, endPos;
1233 selectionStartEnd(startPos, endPos);
1234 if (selectionState() == SelectionStart) {
1235 endPos = textLength();
1237 // to handle selection from end of text to end of line
1238 if (startPos && startPos == endPos)
1239 startPos = endPos - 1;
1240 } else if (selectionState() == SelectionEnd)
1243 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
1244 if (box->isSelected(startPos, endPos)) {
1245 RootInlineBox* root = box->root();
1247 root->setHasSelectedChildren(true);
1251 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
1252 RootInlineBox* root = box->root();
1254 root->setHasSelectedChildren(state == SelectionInside);
1259 // The containing block can be null in case of an orphaned tree.
1260 RenderBlock* containingBlock = this->containingBlock();
1261 if (containingBlock && !containingBlock->isRenderView())
1262 containingBlock->setSelectionState(state);
1265 void RenderText::setTextWithOffset(PassRefPtr<StringImpl> text, unsigned offset, unsigned len, bool force)
1267 if (!force && equal(m_text.impl(), text.get()))
1270 unsigned oldLen = textLength();
1271 unsigned newLen = text->length();
1272 int delta = newLen - oldLen;
1273 unsigned end = len ? offset + len - 1 : offset;
1275 RootInlineBox* firstRootBox = 0;
1276 RootInlineBox* lastRootBox = 0;
1278 bool dirtiedLines = false;
1280 // Dirty all text boxes that include characters in between offset and offset+len.
1281 for (InlineTextBox* curr = firstTextBox(); curr; curr = curr->nextTextBox()) {
1282 // FIXME: This shouldn't rely on the end of a dirty line box. See https://bugs.webkit.org/show_bug.cgi?id=97264
1283 // Text run is entirely before the affected range.
1284 if (curr->end() < offset)
1287 // Text run is entirely after the affected range.
1288 if (curr->start() > end) {
1289 curr->offsetRun(delta);
1290 RootInlineBox* root = curr->root();
1291 if (!firstRootBox) {
1292 firstRootBox = root;
1293 if (!dirtiedLines) {
1294 // The affected area was in between two runs. Go ahead and mark the root box of
1295 // the run after the affected area as dirty.
1296 firstRootBox->markDirty();
1297 dirtiedLines = true;
1301 } else if (curr->end() >= offset && curr->end() <= end) {
1302 // Text run overlaps with the left end of the affected range.
1303 curr->dirtyLineBoxes();
1304 dirtiedLines = true;
1305 } else if (curr->start() <= offset && curr->end() >= end) {
1306 // Text run subsumes the affected range.
1307 curr->dirtyLineBoxes();
1308 dirtiedLines = true;
1309 } else if (curr->start() <= end && curr->end() >= end) {
1310 // Text run overlaps with right end of the affected range.
1311 curr->dirtyLineBoxes();
1312 dirtiedLines = true;
1316 // Now we have to walk all of the clean lines and adjust their cached line break information
1317 // to reflect our updated offsets.
1319 lastRootBox = lastRootBox->nextRootBox();
1321 RootInlineBox* prev = firstRootBox->prevRootBox();
1323 firstRootBox = prev;
1324 } else if (lastTextBox()) {
1325 ASSERT(!lastRootBox);
1326 firstRootBox = lastTextBox()->root();
1327 firstRootBox->markDirty();
1328 dirtiedLines = true;
1330 for (RootInlineBox* curr = firstRootBox; curr && curr != lastRootBox; curr = curr->nextRootBox()) {
1331 if (curr->lineBreakObj() == this && curr->lineBreakPos() > end)
1332 curr->setLineBreakPos(curr->lineBreakPos() + delta);
1335 // If the text node is empty, dirty the line where new text will be inserted.
1336 if (!firstTextBox() && parent()) {
1337 parent()->dirtyLinesFromChangedChild(this);
1338 dirtiedLines = true;
1341 m_linesDirty = dirtiedLines;
1342 setText(text, force || dirtiedLines);
1345 void RenderText::transformText()
1347 if (RefPtr<StringImpl> textToTransform = originalText())
1348 setText(textToTransform.release(), true);
1351 static inline bool isInlineFlowOrEmptyText(const RenderObject* o)
1353 if (o->isRenderInline())
1357 StringImpl* text = toRenderText(o)->text();
1360 return !text->length();
1363 UChar RenderText::previousCharacter() const
1365 // find previous text renderer if one exists
1366 const RenderObject* previousText = this;
1367 while ((previousText = previousText->previousInPreOrder()))
1368 if (!isInlineFlowOrEmptyText(previousText))
1371 if (previousText && previousText->isText())
1372 if (StringImpl* previousString = toRenderText(previousText)->text())
1373 prev = (*previousString)[previousString->length() - 1];
1377 void applyTextTransform(const RenderStyle* style, String& text, UChar previousCharacter)
1382 switch (style->textTransform()) {
1386 makeCapitalized(&text, previousCharacter);
1397 void RenderText::setTextInternal(PassRefPtr<StringImpl> text)
1401 if (m_needsTranscoding) {
1402 const TextEncoding* encoding = document()->decoder() ? &document()->decoder()->encoding() : 0;
1403 fontTranscoder().convert(m_text, style()->font().fontDescription(), encoding);
1408 applyTextTransform(style(), m_text, previousCharacter());
1410 // We use the same characters here as for list markers.
1411 // See the listMarkerText function in RenderListMarker.cpp.
1412 switch (style()->textSecurity()) {
1416 secureText(whiteBullet);
1422 secureText(blackSquare);
1427 ASSERT(!isBR() || (textLength() == 1 && m_text[0] == '\n'));
1429 m_isAllASCII = m_text.containsOnlyASCII();
1430 m_canUseSimpleFontCodePath = computeCanUseSimpleFontCodePath();
1433 void RenderText::secureText(UChar mask)
1435 if (!m_text.length())
1438 int lastTypedCharacterOffsetToReveal = -1;
1439 String revealedText;
1440 SecureTextTimer* secureTextTimer = gSecureTextTimers ? gSecureTextTimers->get(this) : 0;
1441 if (secureTextTimer && secureTextTimer->isActive()) {
1442 lastTypedCharacterOffsetToReveal = secureTextTimer->lastTypedCharacterOffset();
1443 if (lastTypedCharacterOffsetToReveal >= 0)
1444 revealedText.append(m_text[lastTypedCharacterOffsetToReveal]);
1448 if (lastTypedCharacterOffsetToReveal >= 0) {
1449 m_text.replace(lastTypedCharacterOffsetToReveal, 1, revealedText);
1450 // m_text may be updated later before timer fires. We invalidate the lastTypedCharacterOffset to avoid inconsistency.
1451 secureTextTimer->invalidate();
1455 void RenderText::setText(PassRefPtr<StringImpl> text, bool force)
1459 if (!force && equal(m_text.impl(), text.get()))
1462 setTextInternal(text);
1463 setNeedsLayoutAndPrefWidthsRecalc();
1464 m_knownToHaveNoOverflowAndNoFallbackFonts = false;
1466 if (AXObjectCache* cache = document()->existingAXObjectCache())
1467 cache->textChanged(this);
1470 String RenderText::textWithoutTranscoding() const
1472 // If m_text isn't transcoded or is secure, we can just return the modified text.
1473 if (!m_needsTranscoding || style()->textSecurity() != TSNONE)
1476 // Otherwise, we should use original text. If text-transform is
1477 // specified, we should transform the text on the fly.
1478 String text = originalText();
1479 applyTextTransform(style(), text, previousCharacter());
1483 void RenderText::dirtyLineBoxes(bool fullLayout)
1487 else if (!m_linesDirty) {
1488 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
1489 box->dirtyLineBoxes();
1491 m_linesDirty = false;
1494 InlineTextBox* RenderText::createTextBox()
1496 return new (renderArena()) InlineTextBox(this);
1499 InlineTextBox* RenderText::createInlineTextBox()
1501 InlineTextBox* textBox = createTextBox();
1502 if (!m_firstTextBox)
1503 m_firstTextBox = m_lastTextBox = textBox;
1505 m_lastTextBox->setNextTextBox(textBox);
1506 textBox->setPreviousTextBox(m_lastTextBox);
1507 m_lastTextBox = textBox;
1509 textBox->setIsText(true);
1513 void RenderText::positionLineBox(InlineBox* box)
1515 InlineTextBox* s = toInlineTextBox(box);
1517 // FIXME: should not be needed!!!
1519 // We want the box to be destroyed.
1521 if (m_firstTextBox == s)
1522 m_firstTextBox = s->nextTextBox();
1524 s->prevTextBox()->setNextTextBox(s->nextTextBox());
1525 if (m_lastTextBox == s)
1526 m_lastTextBox = s->prevTextBox();
1528 s->nextTextBox()->setPreviousTextBox(s->prevTextBox());
1529 s->destroy(renderArena());
1533 m_containsReversedText |= !s->isLeftToRightDirection();
1536 float RenderText::width(unsigned from, unsigned len, float xPos, bool firstLine, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
1538 if (from >= textLength())
1541 if (from + len > textLength())
1542 len = textLength() - from;
1544 return width(from, len, style(firstLine)->font(), xPos, fallbackFonts, glyphOverflow);
1547 float RenderText::width(unsigned from, unsigned len, const Font& f, float xPos, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
1549 ASSERT(from + len <= textLength());
1554 if (&f == &style()->font()) {
1555 if (!style()->preserveNewline() && !from && len == textLength() && (!glyphOverflow || !glyphOverflow->computeBounds)) {
1556 if (fallbackFonts) {
1557 ASSERT(glyphOverflow);
1558 if (preferredLogicalWidthsDirty() || !m_knownToHaveNoOverflowAndNoFallbackFonts) {
1559 const_cast<RenderText*>(this)->computePreferredLogicalWidths(0, *fallbackFonts, *glyphOverflow);
1560 if (fallbackFonts->isEmpty() && !glyphOverflow->left && !glyphOverflow->right && !glyphOverflow->top && !glyphOverflow->bottom)
1561 m_knownToHaveNoOverflowAndNoFallbackFonts = true;
1565 w = maxLogicalWidth();
1567 w = widthFromCache(f, from, len, xPos, fallbackFonts, glyphOverflow);
1569 TextRun run = RenderBlock::constructTextRun(const_cast<RenderText*>(this), f, this, from, len, style());
1570 run.setCharactersLength(textLength() - from);
1571 ASSERT(run.charactersLength() >= run.length());
1573 run.setCharacterScanForCodePath(!canUseSimpleFontCodePath());
1574 run.setTabSize(!style()->collapseWhiteSpace(), style()->tabSize());
1576 w = f.width(run, fallbackFonts, glyphOverflow);
1582 IntRect RenderText::linesBoundingBox() const
1586 ASSERT(!firstTextBox() == !lastTextBox()); // Either both are null or both exist.
1587 if (firstTextBox() && lastTextBox()) {
1588 // Return the width of the minimal left side and the maximal right side.
1589 float logicalLeftSide = 0;
1590 float logicalRightSide = 0;
1591 for (InlineTextBox* curr = firstTextBox(); curr; curr = curr->nextTextBox()) {
1592 if (curr == firstTextBox() || curr->logicalLeft() < logicalLeftSide)
1593 logicalLeftSide = curr->logicalLeft();
1594 if (curr == firstTextBox() || curr->logicalRight() > logicalRightSide)
1595 logicalRightSide = curr->logicalRight();
1598 bool isHorizontal = style()->isHorizontalWritingMode();
1600 float x = isHorizontal ? logicalLeftSide : firstTextBox()->x();
1601 float y = isHorizontal ? firstTextBox()->y() : logicalLeftSide;
1602 float width = isHorizontal ? logicalRightSide - logicalLeftSide : lastTextBox()->logicalBottom() - x;
1603 float height = isHorizontal ? lastTextBox()->logicalBottom() - y : logicalRightSide - logicalLeftSide;
1604 result = enclosingIntRect(FloatRect(x, y, width, height));
1610 LayoutRect RenderText::linesVisualOverflowBoundingBox() const
1612 if (!firstTextBox())
1613 return LayoutRect();
1615 // Return the width of the minimal left side and the maximal right side.
1616 LayoutUnit logicalLeftSide = LayoutUnit::max();
1617 LayoutUnit logicalRightSide = LayoutUnit::min();
1618 for (InlineTextBox* curr = firstTextBox(); curr; curr = curr->nextTextBox()) {
1619 logicalLeftSide = min(logicalLeftSide, curr->logicalLeftVisualOverflow());
1620 logicalRightSide = max(logicalRightSide, curr->logicalRightVisualOverflow());
1623 LayoutUnit logicalTop = firstTextBox()->logicalTopVisualOverflow();
1624 LayoutUnit logicalWidth = logicalRightSide - logicalLeftSide;
1625 LayoutUnit logicalHeight = lastTextBox()->logicalBottomVisualOverflow() - logicalTop;
1627 LayoutRect rect(logicalLeftSide, logicalTop, logicalWidth, logicalHeight);
1628 if (!style()->isHorizontalWritingMode())
1629 rect = rect.transposedRect();
1633 LayoutRect RenderText::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
1635 RenderObject* rendererToRepaint = containingBlock();
1637 // Do not cross self-painting layer boundaries.
1638 RenderObject* enclosingLayerRenderer = enclosingLayer()->renderer();
1639 if (enclosingLayerRenderer != rendererToRepaint && !rendererToRepaint->isDescendantOf(enclosingLayerRenderer))
1640 rendererToRepaint = enclosingLayerRenderer;
1642 // The renderer we chose to repaint may be an ancestor of repaintContainer, but we need to do a repaintContainer-relative repaint.
1643 if (repaintContainer && repaintContainer != rendererToRepaint && !rendererToRepaint->isDescendantOf(repaintContainer))
1644 return repaintContainer->clippedOverflowRectForRepaint(repaintContainer);
1646 return rendererToRepaint->clippedOverflowRectForRepaint(repaintContainer);
1649 LayoutRect RenderText::selectionRectForRepaint(const RenderLayerModelObject* repaintContainer, bool clipToVisibleContent)
1651 ASSERT(!needsLayout());
1653 if (selectionState() == SelectionNone)
1654 return LayoutRect();
1655 RenderBlock* cb = containingBlock();
1657 return LayoutRect();
1659 // Now calculate startPos and endPos for painting selection.
1660 // We include a selection while endPos > 0
1661 int startPos, endPos;
1662 if (selectionState() == SelectionInside) {
1663 // We are fully selected.
1665 endPos = textLength();
1667 selectionStartEnd(startPos, endPos);
1668 if (selectionState() == SelectionStart)
1669 endPos = textLength();
1670 else if (selectionState() == SelectionEnd)
1674 if (startPos == endPos)
1678 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
1679 rect.unite(box->localSelectionRect(startPos, endPos));
1680 rect.unite(ellipsisRectForBox(box, startPos, endPos));
1683 if (clipToVisibleContent)
1684 computeRectForRepaint(repaintContainer, rect);
1686 if (cb->hasColumns())
1687 cb->adjustRectForColumns(rect);
1689 rect = localToContainerQuad(FloatRect(rect), repaintContainer).enclosingBoundingBox();
1695 int RenderText::caretMinOffset() const
1697 InlineTextBox* box = firstTextBox();
1700 int minOffset = box->start();
1701 for (box = box->nextTextBox(); box; box = box->nextTextBox())
1702 minOffset = min<int>(minOffset, box->start());
1706 int RenderText::caretMaxOffset() const
1708 InlineTextBox* box = lastTextBox();
1710 return textLength();
1712 int maxOffset = box->start() + box->len();
1713 for (box = box->prevTextBox(); box; box = box->prevTextBox())
1714 maxOffset = max<int>(maxOffset, box->start() + box->len());
1718 unsigned RenderText::renderedTextLength() const
1721 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
1726 int RenderText::previousOffset(int current) const
1728 if (isAllASCII() || m_text.is8Bit())
1731 StringImpl* textImpl = m_text.impl();
1732 TextBreakIterator* iterator = cursorMovementIterator(textImpl->characters16(), textImpl->length());
1736 long result = textBreakPreceding(iterator, current);
1737 if (result == TextBreakDone)
1738 result = current - 1;
1746 #define HANGUL_CHOSEONG_START (0x1100)
1747 #define HANGUL_CHOSEONG_END (0x115F)
1748 #define HANGUL_JUNGSEONG_START (0x1160)
1749 #define HANGUL_JUNGSEONG_END (0x11A2)
1750 #define HANGUL_JONGSEONG_START (0x11A8)
1751 #define HANGUL_JONGSEONG_END (0x11F9)
1752 #define HANGUL_SYLLABLE_START (0xAC00)
1753 #define HANGUL_SYLLABLE_END (0xD7AF)
1754 #define HANGUL_JONGSEONG_COUNT (28)
1765 inline bool isHangulLVT(UChar32 character)
1767 return (character - HANGUL_SYLLABLE_START) % HANGUL_JONGSEONG_COUNT;
1770 inline bool isMark(UChar32 c)
1772 int8_t charType = u_charType(c);
1773 return charType == U_NON_SPACING_MARK || charType == U_ENCLOSING_MARK || charType == U_COMBINING_SPACING_MARK;
1776 inline bool isRegionalIndicator(UChar32 c)
1778 // National flag emoji each consists of a pair of regional indicator symbols.
1779 return 0x1F1E6 <= c && c <= 0x1F1FF;
1784 int RenderText::previousOffsetForBackwardDeletion(int current) const
1788 StringImpl& text = *m_text.impl();
1790 bool sawRegionalIndicator = false;
1791 while (current > 0) {
1792 if (U16_IS_TRAIL(text[--current]))
1797 UChar32 character = text.characterStartingAt(current);
1799 if (sawRegionalIndicator) {
1800 // We don't check if the pair of regional indicator symbols before current position can actually be combined
1801 // into a flag, and just delete it. This may not agree with how the pair is rendered in edge cases,
1802 // but is good enough in practice.
1803 if (isRegionalIndicator(character))
1805 // Don't delete a preceding character that isn't a regional indicator symbol.
1806 U16_FWD_1_UNSAFE(text, current);
1809 // We don't combine characters in Armenian ... Limbu range for backward deletion.
1810 if ((character >= 0x0530) && (character < 0x1950))
1813 if (isRegionalIndicator(character)) {
1814 sawRegionalIndicator = true;
1818 if (!isMark(character) && (character != 0xFF9E) && (character != 0xFF9F))
1826 character = text.characterStartingAt(current);
1827 if (((character >= HANGUL_CHOSEONG_START) && (character <= HANGUL_JONGSEONG_END)) || ((character >= HANGUL_SYLLABLE_START) && (character <= HANGUL_SYLLABLE_END))) {
1829 HangulState initialState;
1831 if (character < HANGUL_JUNGSEONG_START)
1832 state = HangulStateL;
1833 else if (character < HANGUL_JONGSEONG_START)
1834 state = HangulStateV;
1835 else if (character < HANGUL_SYLLABLE_START)
1836 state = HangulStateT;
1838 state = isHangulLVT(character) ? HangulStateLVT : HangulStateLV;
1840 initialState = state;
1842 while (current > 0 && ((character = text.characterStartingAt(current - 1)) >= HANGUL_CHOSEONG_START) && (character <= HANGUL_SYLLABLE_END) && ((character <= HANGUL_JONGSEONG_END) || (character >= HANGUL_SYLLABLE_START))) {
1845 if (character <= HANGUL_CHOSEONG_END)
1846 state = HangulStateL;
1847 else if ((character >= HANGUL_SYLLABLE_START) && (character <= HANGUL_SYLLABLE_END) && !isHangulLVT(character))
1848 state = HangulStateLV;
1849 else if (character > HANGUL_JUNGSEONG_END)
1850 state = HangulStateBreak;
1853 if ((character >= HANGUL_JUNGSEONG_START) && (character <= HANGUL_JUNGSEONG_END))
1854 state = HangulStateV;
1855 else if ((character >= HANGUL_SYLLABLE_START) && (character <= HANGUL_SYLLABLE_END))
1856 state = (isHangulLVT(character) ? HangulStateLVT : HangulStateLV);
1857 else if (character < HANGUL_JUNGSEONG_START)
1858 state = HangulStateBreak;
1861 state = (character < HANGUL_JUNGSEONG_START) ? HangulStateL : HangulStateBreak;
1864 if (state == HangulStateBreak)
1873 // Platforms other than Mac delete by one code point.
1874 if (U16_IS_TRAIL(m_text[--current]))
1882 int RenderText::nextOffset(int current) const
1884 if (isAllASCII() || m_text.is8Bit())
1887 StringImpl* textImpl = m_text.impl();
1888 TextBreakIterator* iterator = cursorMovementIterator(textImpl->characters16(), textImpl->length());
1892 long result = textBreakFollowing(iterator, current);
1893 if (result == TextBreakDone)
1894 result = current + 1;
1899 bool RenderText::computeCanUseSimpleFontCodePath() const
1901 if (isAllASCII() || m_text.is8Bit())
1903 return Font::characterRangeCodePath(characters(), length()) == Font::Simple;
1908 void RenderText::checkConsistency() const
1910 #ifdef CHECK_CONSISTENCY
1911 const InlineTextBox* prev = 0;
1912 for (const InlineTextBox* child = m_firstTextBox; child != 0; child = child->nextTextBox()) {
1913 ASSERT(child->renderer() == this);
1914 ASSERT(child->prevTextBox() == prev);
1917 ASSERT(prev == m_lastTextBox);
1923 void RenderText::momentarilyRevealLastTypedCharacter(unsigned lastTypedCharacterOffset)
1925 if (!gSecureTextTimers)
1926 gSecureTextTimers = new SecureTextTimerMap;
1928 SecureTextTimer* secureTextTimer = gSecureTextTimers->get(this);
1929 if (!secureTextTimer) {
1930 secureTextTimer = new SecureTextTimer(this);
1931 gSecureTextTimers->add(this, secureTextTimer);
1933 secureTextTimer->restartWithNewText(lastTypedCharacterOffset);
1936 } // namespace WebCore