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 "InlineTextBox.h"
35 #include "RenderArena.h"
36 #include "RenderBlock.h"
37 #include "RenderCombineText.h"
38 #include "RenderLayer.h"
39 #include "RenderView.h"
42 #include "TextBreakIterator.h"
43 #include "TextResourceDecoder.h"
44 #include "VisiblePosition.h"
45 #include "break_lines.h"
46 #include <wtf/AlwaysInline.h>
47 #include <wtf/text/StringBuffer.h>
48 #include <wtf/unicode/CharacterNames.h>
52 using namespace Unicode;
56 class SecureTextTimer;
57 typedef HashMap<RenderText*, SecureTextTimer*> SecureTextTimerMap;
58 static SecureTextTimerMap* gSecureTextTimers = 0;
60 class SecureTextTimer : public TimerBase {
62 SecureTextTimer(RenderText* renderText)
63 : m_renderText(renderText)
64 , m_lastTypedCharacterOffset(-1)
68 void restartWithNewText(unsigned lastTypedCharacterOffset)
70 m_lastTypedCharacterOffset = lastTypedCharacterOffset;
71 startOneShot(m_renderText->document()->settings()->passwordEchoDurationInSeconds());
73 void invalidate() { m_lastTypedCharacterOffset = -1; }
74 unsigned lastTypedCharacterOffset() { return m_lastTypedCharacterOffset; }
79 ASSERT(gSecureTextTimers->contains(m_renderText));
80 m_renderText->setText(m_renderText->text(), true /* forcing setting text as it may be masked later */);
83 RenderText* m_renderText;
84 int m_lastTypedCharacterOffset;
87 static void makeCapitalized(String* string, UChar previous)
92 unsigned length = string->length();
93 const UChar* characters = string->characters();
95 if (length >= numeric_limits<unsigned>::max())
98 StringBuffer stringWithPrevious(length + 1);
99 stringWithPrevious[0] = previous == noBreakSpace ? ' ' : previous;
100 for (unsigned i = 1; i < length + 1; i++) {
101 // Replace   with a real space since ICU no longer treats   as a word separator.
102 if (characters[i - 1] == noBreakSpace)
103 stringWithPrevious[i] = ' ';
105 stringWithPrevious[i] = characters[i - 1];
108 TextBreakIterator* boundary = wordBreakIterator(stringWithPrevious.characters(), length + 1);
112 StringBuffer data(length);
115 int32_t startOfWord = textBreakFirst(boundary);
116 for (endOfWord = textBreakNext(boundary); endOfWord != TextBreakDone; startOfWord = endOfWord, endOfWord = textBreakNext(boundary)) {
117 if (startOfWord != 0) // Ignore first char of previous string
118 data[startOfWord - 1] = characters[startOfWord - 1] == noBreakSpace ? noBreakSpace : toTitleCase(stringWithPrevious[startOfWord]);
119 for (int i = startOfWord + 1; i < endOfWord; i++)
120 data[i - 1] = characters[i - 1];
123 *string = String::adopt(data);
126 RenderText::RenderText(Node* node, PassRefPtr<StringImpl> str)
136 , m_linesDirty(false)
137 , m_containsReversedText(false)
138 , m_isAllASCII(m_text.containsOnlyASCII())
139 , m_knownToHaveNoOverflowAndNoFallbackFonts(false)
140 , m_needsTranscoding(false)
146 view()->frameView()->incrementVisuallyNonEmptyCharacterCount(m_text.length());
151 RenderText::~RenderText()
153 ASSERT(!m_firstTextBox);
154 ASSERT(!m_lastTextBox);
159 const char* RenderText::renderName() const
164 bool RenderText::isTextFragment() const
169 bool RenderText::isWordBreak() const
174 void RenderText::updateNeedsTranscoding()
176 const TextEncoding* encoding = document()->decoder() ? &document()->decoder()->encoding() : 0;
177 m_needsTranscoding = fontTranscoder().needsTranscoding(style()->font().fontDescription(), encoding);
180 void RenderText::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
182 // There is no need to ever schedule repaints from a style change of a text run, since
183 // we already did this for the parent of the text run.
184 // We do have to schedule layouts, though, since a style change can force us to
186 if (diff == StyleDifferenceLayout) {
187 setNeedsLayoutAndPrefWidthsRecalc();
188 m_knownToHaveNoOverflowAndNoFallbackFonts = false;
191 bool needsResetText = false;
193 updateNeedsTranscoding();
194 needsResetText = m_needsTranscoding;
195 } else if (oldStyle->font().needsTranscoding() != style()->font().needsTranscoding() || (style()->font().needsTranscoding() && oldStyle->font().family().family() != style()->font().family().family())) {
196 updateNeedsTranscoding();
197 needsResetText = true;
200 ETextTransform oldTransform = oldStyle ? oldStyle->textTransform() : TTNONE;
201 ETextSecurity oldSecurity = oldStyle ? oldStyle->textSecurity() : TSNONE;
202 if (needsResetText || oldTransform != style()->textTransform() || oldSecurity != style()->textSecurity()) {
203 if (RefPtr<StringImpl> textToTransform = originalText())
204 setText(textToTransform.release(), true);
208 void RenderText::removeAndDestroyTextBoxes()
210 if (!documentBeingDestroyed()) {
211 if (firstTextBox()) {
213 RootInlineBox* next = firstTextBox()->root()->nextRootBox();
217 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
220 parent()->dirtyLinesFromChangedChild(this);
225 void RenderText::willBeDestroyed()
227 if (SecureTextTimer* secureTextTimer = gSecureTextTimers ? gSecureTextTimers->take(this) : 0)
228 delete secureTextTimer;
230 removeAndDestroyTextBoxes();
231 RenderObject::willBeDestroyed();
234 void RenderText::extractTextBox(InlineTextBox* box)
238 m_lastTextBox = box->prevTextBox();
239 if (box == m_firstTextBox)
241 if (box->prevTextBox())
242 box->prevTextBox()->setNextTextBox(0);
243 box->setPreviousTextBox(0);
244 for (InlineTextBox* curr = box; curr; curr = curr->nextTextBox())
245 curr->setExtracted();
250 void RenderText::attachTextBox(InlineTextBox* box)
255 m_lastTextBox->setNextTextBox(box);
256 box->setPreviousTextBox(m_lastTextBox);
258 m_firstTextBox = box;
259 InlineTextBox* last = box;
260 for (InlineTextBox* curr = box; curr; curr = curr->nextTextBox()) {
261 curr->setExtracted(false);
264 m_lastTextBox = last;
269 void RenderText::removeTextBox(InlineTextBox* box)
273 if (box == m_firstTextBox)
274 m_firstTextBox = box->nextTextBox();
275 if (box == m_lastTextBox)
276 m_lastTextBox = box->prevTextBox();
277 if (box->nextTextBox())
278 box->nextTextBox()->setPreviousTextBox(box->prevTextBox());
279 if (box->prevTextBox())
280 box->prevTextBox()->setNextTextBox(box->nextTextBox());
285 void RenderText::deleteTextBoxes()
287 if (firstTextBox()) {
288 RenderArena* arena = renderArena();
290 for (InlineTextBox* curr = firstTextBox(); curr; curr = next) {
291 next = curr->nextTextBox();
292 curr->destroy(arena);
294 m_firstTextBox = m_lastTextBox = 0;
298 PassRefPtr<StringImpl> RenderText::originalText() const
301 return (e && e->isTextNode()) ? static_cast<Text*>(e)->dataImpl() : 0;
304 void RenderText::absoluteRects(Vector<LayoutRect>& rects, const LayoutPoint& accumulatedOffset)
306 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
307 rects.append(enclosingLayoutRect(FloatRect(accumulatedOffset + box->topLeft(), box->size())));
310 static FloatRect localQuadForTextBox(InlineTextBox* box, unsigned start, unsigned end, bool useSelectionHeight)
312 unsigned realEnd = min(box->end() + 1, end);
313 IntRect r = box->localSelectionRect(start, realEnd);
315 if (!useSelectionHeight) {
316 // Change the height and y position (or width and x for vertical text)
317 // because selectionRect uses selection-specific values.
318 if (box->isHorizontal()) {
319 r.setHeight(box->logicalHeight());
322 r.setWidth(box->logicalWidth());
331 void RenderText::absoluteRectsForRange(Vector<IntRect>& rects, unsigned start, unsigned end, bool useSelectionHeight, bool* wasFixed)
333 // Work around signed/unsigned issues. This function takes unsigneds, and is often passed UINT_MAX
334 // to mean "all the way to the end". InlineTextBox coordinates are unsigneds, so changing this
335 // function to take ints causes various internal mismatches. But selectionRect takes ints, and
336 // passing UINT_MAX to it causes trouble. Ideally we'd change selectionRect to take unsigneds, but
337 // that would cause many ripple effects, so for now we'll just clamp our unsigned parameters to INT_MAX.
338 ASSERT(end == UINT_MAX || end <= INT_MAX);
339 ASSERT(start <= INT_MAX);
340 start = min(start, static_cast<unsigned>(INT_MAX));
341 end = min(end, static_cast<unsigned>(INT_MAX));
343 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
344 // Note: box->end() returns the index of the last character, not the index past it
345 if (start <= box->start() && box->end() < end) {
346 IntRect r = box->calculateBoundaries();
347 if (useSelectionHeight) {
348 IntRect selectionRect = box->localSelectionRect(start, end);
349 if (box->isHorizontal()) {
350 r.setHeight(selectionRect.height());
351 r.setY(selectionRect.y());
353 r.setWidth(selectionRect.width());
354 r.setX(selectionRect.x());
357 rects.append(localToAbsoluteQuad(FloatQuad(r), false, wasFixed).enclosingBoundingBox());
359 // FIXME: This code is wrong. It's converting local to absolute twice. http://webkit.org/b/65722
360 FloatRect rect = localQuadForTextBox(box, start, end, useSelectionHeight);
362 rects.append(localToAbsoluteQuad(rect, false, wasFixed).enclosingBoundingBox());
367 static IntRect ellipsisRectForBox(InlineTextBox* box, unsigned startPos, unsigned endPos)
372 unsigned short truncation = box->truncation();
373 if (truncation == cNoTruncation)
377 if (EllipsisBox* ellipsis = box->root()->ellipsisBox()) {
378 int ellipsisStartPosition = max<int>(startPos - box->start(), 0);
379 int ellipsisEndPosition = min<int>(endPos - box->start(), box->len());
381 // The ellipsis should be considered to be selected if the end of
382 // the selection is past the beginning of the truncation and the
383 // beginning of the selection is before or at the beginning of the truncation.
384 if (ellipsisEndPosition >= truncation && ellipsisStartPosition <= truncation)
385 return ellipsis->selectionRect();
391 void RenderText::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed, ClippingOption option)
393 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
394 IntRect boundaries = box->calculateBoundaries();
396 // Shorten the width of this text box if it ends in an ellipsis.
397 IntRect ellipsisRect = (option == ClipToEllipsis) ? ellipsisRectForBox(box, 0, textLength()) : IntRect();
398 if (!ellipsisRect.isEmpty()) {
399 if (style()->isHorizontalWritingMode())
400 boundaries.setWidth(ellipsisRect.maxX() - boundaries.x());
402 boundaries.setHeight(ellipsisRect.maxY() - boundaries.y());
404 quads.append(localToAbsoluteQuad(FloatRect(boundaries), false, wasFixed));
408 void RenderText::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed)
410 absoluteQuads(quads, wasFixed, NoClipping);
413 void RenderText::absoluteQuadsForRange(Vector<FloatQuad>& quads, unsigned start, unsigned end, bool useSelectionHeight, bool* wasFixed)
415 // Work around signed/unsigned issues. This function takes unsigneds, and is often passed UINT_MAX
416 // to mean "all the way to the end". InlineTextBox coordinates are unsigneds, so changing this
417 // function to take ints causes various internal mismatches. But selectionRect takes ints, and
418 // passing UINT_MAX to it causes trouble. Ideally we'd change selectionRect to take unsigneds, but
419 // that would cause many ripple effects, so for now we'll just clamp our unsigned parameters to INT_MAX.
420 ASSERT(end == UINT_MAX || end <= INT_MAX);
421 ASSERT(start <= INT_MAX);
422 start = min(start, static_cast<unsigned>(INT_MAX));
423 end = min(end, static_cast<unsigned>(INT_MAX));
425 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
426 // Note: box->end() returns the index of the last character, not the index past it
427 if (start <= box->start() && box->end() < end) {
428 IntRect r(box->calculateBoundaries());
429 if (useSelectionHeight) {
430 IntRect selectionRect = box->localSelectionRect(start, end);
431 if (box->isHorizontal()) {
432 r.setHeight(selectionRect.height());
433 r.setY(selectionRect.y());
435 r.setWidth(selectionRect.width());
436 r.setX(selectionRect.x());
439 quads.append(localToAbsoluteQuad(FloatRect(r), false, wasFixed));
441 FloatRect rect = localQuadForTextBox(box, start, end, useSelectionHeight);
443 quads.append(localToAbsoluteQuad(rect, false, wasFixed));
448 InlineTextBox* RenderText::findNextInlineTextBox(int offset, int& pos) const
450 // The text runs point to parts of the RenderText's m_text
451 // (they don't include '\n')
452 // Find the text run that includes the character at offset
453 // and return pos, which is the position of the char in the run.
458 InlineTextBox* s = m_firstTextBox;
460 while (offset > off && s->nextTextBox()) {
461 s = s->nextTextBox();
462 off = s->start() + s->len();
464 // we are now in the correct text run
465 pos = (offset > off ? s->len() : s->len() - (off - offset) );
469 enum ShouldAffinityBeDownstream { AlwaysDownstream, AlwaysUpstream, UpstreamIfPositionIsNotAtStart };
471 static bool lineDirectionPointFitsInBox(int pointLineDirection, InlineTextBox* box, ShouldAffinityBeDownstream& shouldAffinityBeDownstream)
473 shouldAffinityBeDownstream = AlwaysDownstream;
475 // the x coordinate is equal to the left edge of this box
476 // the affinity must be downstream so the position doesn't jump back to the previous line
477 if (pointLineDirection == box->logicalLeft())
480 // and the x coordinate is to the left of the right edge of this box
481 // check to see if position goes in this box
482 if (pointLineDirection < box->logicalRight()) {
483 shouldAffinityBeDownstream = UpstreamIfPositionIsNotAtStart;
487 // box is first on line
488 // and the x coordinate is to the left of the first text box left edge
489 if (!box->prevOnLine() && pointLineDirection < box->logicalLeft())
492 if (!box->nextOnLine()) {
493 // box is last on line
494 // and the x coordinate is to the right of the last text box right edge
495 // generate VisiblePosition, use UPSTREAM affinity if possible
496 shouldAffinityBeDownstream = UpstreamIfPositionIsNotAtStart;
503 static VisiblePosition createVisiblePositionForBox(const InlineBox* box, int offset, ShouldAffinityBeDownstream shouldAffinityBeDownstream)
505 EAffinity affinity = VP_DEFAULT_AFFINITY;
506 switch (shouldAffinityBeDownstream) {
507 case AlwaysDownstream:
508 affinity = DOWNSTREAM;
511 affinity = VP_UPSTREAM_IF_POSSIBLE;
513 case UpstreamIfPositionIsNotAtStart:
514 affinity = offset > box->caretMinOffset() ? VP_UPSTREAM_IF_POSSIBLE : DOWNSTREAM;
517 return box->renderer()->createVisiblePosition(offset, affinity);
520 static VisiblePosition createVisiblePositionAfterAdjustingOffsetForBiDi(const InlineTextBox* box, int offset, ShouldAffinityBeDownstream shouldAffinityBeDownstream)
523 ASSERT(box->renderer());
526 if (offset && static_cast<unsigned>(offset) < box->len())
527 return createVisiblePositionForBox(box, box->start() + offset, shouldAffinityBeDownstream);
529 bool positionIsAtStartOfBox = !offset;
530 if (positionIsAtStartOfBox == box->isLeftToRightDirection()) {
531 // offset is on the left edge
533 const InlineBox* prevBox = box->prevLeafChild();
534 if ((prevBox && prevBox->bidiLevel() == box->bidiLevel())
535 || box->renderer()->containingBlock()->style()->direction() == box->direction()) // FIXME: left on 12CBA
536 return createVisiblePositionForBox(box, box->caretLeftmostOffset(), shouldAffinityBeDownstream);
538 if (prevBox && prevBox->bidiLevel() > box->bidiLevel()) {
539 // e.g. left of B in aDC12BAb
540 const InlineBox* leftmostBox;
542 leftmostBox = prevBox;
543 prevBox = leftmostBox->prevLeafChild();
544 } while (prevBox && prevBox->bidiLevel() > box->bidiLevel());
545 return createVisiblePositionForBox(leftmostBox, leftmostBox->caretRightmostOffset(), shouldAffinityBeDownstream);
548 if (!prevBox || prevBox->bidiLevel() < box->bidiLevel()) {
549 // e.g. left of D in aDC12BAb
550 const InlineBox* rightmostBox;
551 const InlineBox* nextBox = box;
553 rightmostBox = nextBox;
554 nextBox = rightmostBox->nextLeafChild();
555 } while (nextBox && nextBox->bidiLevel() >= box->bidiLevel());
556 return createVisiblePositionForBox(rightmostBox,
557 box->isLeftToRightDirection() ? rightmostBox->caretMaxOffset() : rightmostBox->caretMinOffset(), shouldAffinityBeDownstream);
560 return createVisiblePositionForBox(box, box->caretRightmostOffset(), shouldAffinityBeDownstream);
563 const InlineBox* nextBox = box->nextLeafChild();
564 if ((nextBox && nextBox->bidiLevel() == box->bidiLevel())
565 || box->renderer()->containingBlock()->style()->direction() == box->direction())
566 return createVisiblePositionForBox(box, box->caretRightmostOffset(), shouldAffinityBeDownstream);
568 // offset is on the right edge
569 if (nextBox && nextBox->bidiLevel() > box->bidiLevel()) {
570 // e.g. right of C in aDC12BAb
571 const InlineBox* rightmostBox;
573 rightmostBox = nextBox;
574 nextBox = rightmostBox->nextLeafChild();
575 } while (nextBox && nextBox->bidiLevel() > box->bidiLevel());
576 return createVisiblePositionForBox(rightmostBox, rightmostBox->caretLeftmostOffset(), shouldAffinityBeDownstream);
579 if (!nextBox || nextBox->bidiLevel() < box->bidiLevel()) {
580 // e.g. right of A in aDC12BAb
581 const InlineBox* leftmostBox;
582 const InlineBox* prevBox = box;
584 leftmostBox = prevBox;
585 prevBox = leftmostBox->prevLeafChild();
586 } while (prevBox && prevBox->bidiLevel() >= box->bidiLevel());
587 return createVisiblePositionForBox(leftmostBox,
588 box->isLeftToRightDirection() ? leftmostBox->caretMinOffset() : leftmostBox->caretMaxOffset(), shouldAffinityBeDownstream);
591 return createVisiblePositionForBox(box, box->caretLeftmostOffset(), shouldAffinityBeDownstream);
594 VisiblePosition RenderText::positionForPoint(const LayoutPoint& point)
596 if (!firstTextBox() || textLength() == 0)
597 return createVisiblePosition(0, DOWNSTREAM);
599 // Get the offset for the position, since this will take rtl text into account.
602 LayoutUnit pointLineDirection = firstTextBox()->isHorizontal() ? point.x() : point.y();
603 LayoutUnit pointBlockDirection = firstTextBox()->isHorizontal() ? point.y() : point.x();
605 // FIXME: We should be able to roll these special cases into the general cases in the loop below.
606 if (firstTextBox() && pointBlockDirection < firstTextBox()->root()->selectionBottom() && pointLineDirection < firstTextBox()->logicalLeft()) {
607 // at the y coordinate of the first line or above
608 // and the x coordinate is to the left of the first text box left edge
609 offset = firstTextBox()->offsetForPosition(pointLineDirection);
610 return createVisiblePositionAfterAdjustingOffsetForBiDi(firstTextBox(), offset, UpstreamIfPositionIsNotAtStart);
612 if (lastTextBox() && pointBlockDirection >= lastTextBox()->root()->selectionTop() && pointLineDirection >= lastTextBox()->logicalRight()) {
613 // at the y coordinate of the last line or below
614 // and the x coordinate is to the right of the last text box right edge
615 offset = lastTextBox()->offsetForPosition(pointLineDirection);
616 return createVisiblePositionAfterAdjustingOffsetForBiDi(lastTextBox(), offset, AlwaysUpstream);
619 InlineTextBox* lastBoxAbove = 0;
620 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
621 RootInlineBox* rootBox = box->root();
622 if (pointBlockDirection >= rootBox->selectionTop() || pointBlockDirection >= rootBox->lineTop()) {
623 LayoutUnit bottom = rootBox->selectionBottom();
624 if (rootBox->nextRootBox())
625 bottom = min(bottom, rootBox->nextRootBox()->lineTop());
627 if (pointBlockDirection < bottom) {
628 ShouldAffinityBeDownstream shouldAffinityBeDownstream;
629 offset = box->offsetForPosition(pointLineDirection);
630 if (lineDirectionPointFitsInBox(pointLineDirection, box, shouldAffinityBeDownstream))
631 return createVisiblePositionAfterAdjustingOffsetForBiDi(box, offset, shouldAffinityBeDownstream);
637 return createVisiblePosition(lastBoxAbove ? lastBoxAbove->start() + lastBoxAbove->len() : 0, DOWNSTREAM);
640 IntRect RenderText::localCaretRect(InlineBox* inlineBox, int caretOffset, int* extraWidthToEndOfLine)
645 ASSERT(inlineBox->isInlineTextBox());
646 if (!inlineBox->isInlineTextBox())
649 InlineTextBox* box = toInlineTextBox(inlineBox);
651 int height = box->root()->selectionHeight();
652 int top = box->root()->selectionTop();
654 // Go ahead and round left to snap it to the nearest pixel.
655 float left = box->positionForOffset(caretOffset);
657 // Distribute the caret's width to either side of the offset.
658 int caretWidthLeftOfOffset = caretWidth / 2;
659 left -= caretWidthLeftOfOffset;
660 int caretWidthRightOfOffset = caretWidth - caretWidthLeftOfOffset;
664 float rootLeft = box->root()->logicalLeft();
665 float rootRight = box->root()->logicalRight();
667 // FIXME: should we use the width of the root inline box or the
668 // width of the containing block for this?
669 if (extraWidthToEndOfLine)
670 *extraWidthToEndOfLine = (box->root()->logicalWidth() + rootLeft) - (left + 1);
672 RenderBlock* cb = containingBlock();
673 RenderStyle* cbStyle = cb->style();
676 if (style()->autoWrap()) {
678 rightEdge = cb->logicalWidth();
680 leftEdge = min(static_cast<float>(0), rootLeft);
681 rightEdge = max(static_cast<float>(cb->logicalWidth()), rootRight);
684 bool rightAligned = false;
685 switch (cbStyle->textAlign()) {
688 rightAligned = !cbStyle->isLeftToRightDirection();
700 rightAligned = !cbStyle->isLeftToRightDirection();
703 rightAligned = cbStyle->isLeftToRightDirection();
708 left = max(left, leftEdge);
709 left = min(left, rootRight - caretWidth);
711 left = min(left, rightEdge - caretWidthRightOfOffset);
712 left = max(left, rootLeft);
715 return style()->isHorizontalWritingMode() ? IntRect(left, top, caretWidth, height) : IntRect(top, left, height, caretWidth);
718 ALWAYS_INLINE float RenderText::widthFromCache(const Font& f, int start, int len, float xPos, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
720 if (style()->hasTextCombine() && isCombineText()) {
721 const RenderCombineText* combineText = toRenderCombineText(this);
722 if (combineText->isCombined())
723 return combineText->combinedTextWidth(f);
726 if (f.isFixedPitch() && !f.isSmallCaps() && m_isAllASCII && (!glyphOverflow || !glyphOverflow->computeBounds)) {
727 float monospaceCharacterWidth = f.spaceWidth();
728 float tabWidth = allowTabs() ? monospaceCharacterWidth * 8 : 0;
731 bool previousCharWasSpace = true; // FIXME: Preserves historical behavior, but seems wrong for start > 0.
733 StringImpl& text = *m_text.impl();
734 for (int i = start; i < start + len; i++) {
737 if (c == ' ' || c == '\n') {
738 w += monospaceCharacterWidth;
740 } else if (c == '\t') {
741 w += tabWidth ? tabWidth - fmodf(xPos + w, tabWidth) : monospaceCharacterWidth;
746 w += monospaceCharacterWidth;
749 if (isSpace && !previousCharWasSpace)
750 w += f.wordSpacing();
751 previousCharWasSpace = isSpace;
756 TextRun run = RenderBlock::constructTextRun(const_cast<RenderText*>(this), f, text()->characters() + start, len, style());
757 run.setCharactersLength(textLength() - start);
758 ASSERT(run.charactersLength() >= run.length());
760 run.setAllowTabs(allowTabs());
762 return f.width(run, fallbackFonts, glyphOverflow);
765 void RenderText::trimmedPrefWidths(float leadWidth,
766 float& beginMinW, bool& beginWS,
767 float& endMinW, bool& endWS,
768 bool& hasBreakableChar, bool& hasBreak,
769 float& beginMaxW, float& endMaxW,
770 float& minW, float& maxW, bool& stripFrontSpaces)
772 bool collapseWhiteSpace = style()->collapseWhiteSpace();
773 if (!collapseWhiteSpace)
774 stripFrontSpaces = false;
776 if (m_hasTab || preferredLogicalWidthsDirty())
777 computePreferredLogicalWidths(leadWidth);
779 beginWS = !stripFrontSpaces && m_hasBeginWS;
782 int len = textLength();
784 if (!len || (stripFrontSpaces && text()->containsOnlyWhitespace())) {
798 beginMinW = m_beginMinWidth;
799 endMinW = m_endMinWidth;
801 hasBreakableChar = m_hasBreakableChar;
802 hasBreak = m_hasBreak;
805 StringImpl& text = *m_text.impl();
806 if (text[0] == ' ' || (text[0] == '\n' && !style()->preserveNewline()) || text[0] == '\t') {
807 const Font& font = style()->font(); // FIXME: This ignores first-line.
808 if (stripFrontSpaces) {
809 const UChar space = ' ';
810 float spaceWidth = font.width(RenderBlock::constructTextRun(this, font, &space, 1, style()));
813 maxW += font.wordSpacing();
816 stripFrontSpaces = collapseWhiteSpace && m_hasEndWS;
818 if (!style()->autoWrap() || minW > maxW)
821 // Compute our max widths by scanning the string for newlines.
823 const Font& f = style()->font(); // FIXME: This ignores first-line.
824 bool firstLine = true;
827 for (int i = 0; i < len; i++) {
829 while (i + linelen < len && text[i + linelen] != '\n')
833 endMaxW = widthFromCache(f, i, linelen, leadWidth + endMaxW, 0, 0);
840 } else if (firstLine) {
847 // A <pre> run that ends with a newline, as in, e.g.,
848 // <pre>Some text\n\n<span>More text</pre>
854 static inline bool isSpaceAccordingToStyle(UChar c, RenderStyle* style)
856 return c == ' ' || (c == noBreakSpace && style->nbspMode() == SPACE);
859 float RenderText::minLogicalWidth() const
861 if (preferredLogicalWidthsDirty())
862 const_cast<RenderText*>(this)->computePreferredLogicalWidths(0);
867 float RenderText::maxLogicalWidth() const
869 if (preferredLogicalWidthsDirty())
870 const_cast<RenderText*>(this)->computePreferredLogicalWidths(0);
875 void RenderText::computePreferredLogicalWidths(float leadWidth)
877 HashSet<const SimpleFontData*> fallbackFonts;
878 GlyphOverflow glyphOverflow;
879 computePreferredLogicalWidths(leadWidth, fallbackFonts, glyphOverflow);
880 if (fallbackFonts.isEmpty() && !glyphOverflow.left && !glyphOverflow.right && !glyphOverflow.top && !glyphOverflow.bottom)
881 m_knownToHaveNoOverflowAndNoFallbackFonts = true;
884 void RenderText::computePreferredLogicalWidths(float leadWidth, HashSet<const SimpleFontData*>& fallbackFonts, GlyphOverflow& glyphOverflow)
886 ASSERT(m_hasTab || preferredLogicalWidthsDirty() || !m_knownToHaveNoOverflowAndNoFallbackFonts);
896 float currMinWidth = 0;
897 float currMaxWidth = 0;
898 m_hasBreakableChar = false;
901 m_hasBeginWS = false;
904 const Font& f = style()->font(); // FIXME: This ignores first-line.
905 float wordSpacing = style()->wordSpacing();
906 int len = textLength();
907 const UChar* txt = characters();
908 LazyLineBreakIterator breakIterator(txt, len, style()->locale());
909 bool needsWordSpacing = false;
910 bool ignoringSpaces = false;
911 bool isSpace = false;
912 bool firstWord = true;
913 bool firstLine = true;
914 int nextBreakable = -1;
915 int lastWordBoundary = 0;
917 // Non-zero only when kerning is enabled, in which case we measure words with their trailing
918 // space, then subtract its width.
919 float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(RenderBlock::constructTextRun(this, f, &space, 1, style())) : 0;
921 int firstGlyphLeftOverflow = -1;
923 bool breakNBSP = style()->autoWrap() && style()->nbspMode() == SPACE;
924 bool breakAll = (style()->wordBreak() == BreakAllWordBreak || style()->wordBreak() == BreakWordBreak) && style()->autoWrap();
926 for (int i = 0; i < len; i++) {
929 bool previousCharacterIsSpace = isSpace;
931 bool isNewline = false;
933 if (style()->preserveNewline()) {
939 } else if (c == '\t') {
940 if (!style()->collapseWhiteSpace()) {
948 if ((isSpace || isNewline) && !i)
950 if ((isSpace || isNewline) && i == len - 1)
953 if (!ignoringSpaces && style()->collapseWhiteSpace() && previousCharacterIsSpace && isSpace)
954 ignoringSpaces = true;
956 if (ignoringSpaces && !isSpace)
957 ignoringSpaces = false;
959 // Ignore spaces and soft hyphens
960 if (ignoringSpaces) {
961 ASSERT(lastWordBoundary == i);
964 } else if (c == softHyphen) {
965 currMaxWidth += widthFromCache(f, lastWordBoundary, i - lastWordBoundary, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow);
966 if (firstGlyphLeftOverflow < 0)
967 firstGlyphLeftOverflow = glyphOverflow.left;
968 lastWordBoundary = i + 1;
972 bool hasBreak = breakAll || isBreakable(breakIterator, i, nextBreakable, breakNBSP);
973 bool betweenWords = true;
975 while (c != '\n' && !isSpaceAccordingToStyle(c, style()) && c != '\t' && c != softHyphen) {
980 if (isBreakable(breakIterator, j, nextBreakable, breakNBSP))
983 betweenWords = false;
990 bool isSpace = (j < len) && isSpaceAccordingToStyle(c, style());
992 if (wordTrailingSpaceWidth && isSpace)
993 w = widthFromCache(f, i, wordLen + 1, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow) - wordTrailingSpaceWidth;
995 w = widthFromCache(f, i, wordLen, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow);
997 if (firstGlyphLeftOverflow < 0)
998 firstGlyphLeftOverflow = glyphOverflow.left;
1001 if (lastWordBoundary == i)
1004 currMaxWidth += widthFromCache(f, lastWordBoundary, j - lastWordBoundary, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow);
1005 lastWordBoundary = j;
1008 bool isCollapsibleWhiteSpace = (j < len) && style()->isCollapsibleWhiteSpace(c);
1009 if (j < len && style()->autoWrap())
1010 m_hasBreakableChar = true;
1012 // Add in wordSpacing to our currMaxWidth, but not if this is the last word on a line or the
1013 // last word in the run.
1014 if (wordSpacing && (isSpace || isCollapsibleWhiteSpace) && !containsOnlyWhitespace(j, len-j))
1015 currMaxWidth += wordSpacing;
1019 // If the first character in the run is breakable, then we consider ourselves to have a beginning
1020 // minimum width of 0, since a break could occur right before our run starts, preventing us from ever
1021 // being appended to a previous text run when considering the total minimum width of the containing block.
1023 m_hasBreakableChar = true;
1024 m_beginMinWidth = hasBreak ? 0 : w;
1028 if (currMinWidth > m_minWidth)
1029 m_minWidth = currMinWidth;
1034 // Nowrap can never be broken, so don't bother setting the
1035 // breakable character boolean. Pre can only be broken if we encounter a newline.
1036 if (style()->autoWrap() || isNewline)
1037 m_hasBreakableChar = true;
1039 if (currMinWidth > m_minWidth)
1040 m_minWidth = currMinWidth;
1043 if (isNewline) { // Only set if preserveNewline was true and we saw a newline.
1047 if (!style()->autoWrap())
1048 m_beginMinWidth = currMaxWidth;
1051 if (currMaxWidth > m_maxWidth)
1052 m_maxWidth = currMaxWidth;
1055 TextRun run = RenderBlock::constructTextRun(this, f, txt + i, 1, style());
1056 run.setCharactersLength(len - i);
1057 ASSERT(run.charactersLength() >= run.length());
1059 run.setAllowTabs(allowTabs());
1060 run.setXPos(leadWidth + currMaxWidth);
1062 currMaxWidth += f.width(run);
1063 glyphOverflow.right = 0;
1064 needsWordSpacing = isSpace && !previousCharacterIsSpace && i == len - 1;
1066 ASSERT(lastWordBoundary == i);
1071 if (firstGlyphLeftOverflow > 0)
1072 glyphOverflow.left = firstGlyphLeftOverflow;
1074 if ((needsWordSpacing && len > 1) || (ignoringSpaces && !firstWord))
1075 currMaxWidth += wordSpacing;
1077 m_minWidth = max(currMinWidth, m_minWidth);
1078 m_maxWidth = max(currMaxWidth, m_maxWidth);
1080 if (!style()->autoWrap())
1081 m_minWidth = m_maxWidth;
1083 if (style()->whiteSpace() == PRE) {
1085 m_beginMinWidth = m_maxWidth;
1086 m_endMinWidth = currMaxWidth;
1089 setPreferredLogicalWidthsDirty(false);
1092 bool RenderText::isAllCollapsibleWhitespace()
1094 int length = textLength();
1095 const UChar* text = characters();
1096 for (int i = 0; i < length; i++) {
1097 if (!style()->isCollapsibleWhiteSpace(text[i]))
1103 bool RenderText::containsOnlyWhitespace(unsigned from, unsigned len) const
1106 StringImpl& text = *m_text.impl();
1108 for (currPos = from;
1109 currPos < from + len && (text[currPos] == '\n' || text[currPos] == ' ' || text[currPos] == '\t');
1111 return currPos >= (from + len);
1114 FloatPoint RenderText::firstRunOrigin() const
1116 return IntPoint(firstRunX(), firstRunY());
1119 float RenderText::firstRunX() const
1121 return m_firstTextBox ? m_firstTextBox->x() : 0;
1124 float RenderText::firstRunY() const
1126 return m_firstTextBox ? m_firstTextBox->y() : 0;
1129 void RenderText::setSelectionState(SelectionState state)
1133 RenderObject::setSelectionState(state);
1134 if (state == SelectionStart || state == SelectionEnd || state == SelectionBoth) {
1135 int startPos, endPos;
1136 selectionStartEnd(startPos, endPos);
1137 if (selectionState() == SelectionStart) {
1138 endPos = textLength();
1140 // to handle selection from end of text to end of line
1141 if (startPos != 0 && startPos == endPos)
1142 startPos = endPos - 1;
1143 } else if (selectionState() == SelectionEnd)
1146 for (box = firstTextBox(); box; box = box->nextTextBox()) {
1147 if (box->isSelected(startPos, endPos)) {
1148 RootInlineBox* line = box->root();
1150 line->setHasSelectedChildren(true);
1154 for (box = firstTextBox(); box; box = box->nextTextBox()) {
1155 RootInlineBox* line = box->root();
1157 line->setHasSelectedChildren(state == SelectionInside);
1161 // The returned value can be null in case of an orphaned tree.
1162 if (RenderBlock* cb = containingBlock())
1163 cb->setSelectionState(state);
1166 void RenderText::setTextWithOffset(PassRefPtr<StringImpl> text, unsigned offset, unsigned len, bool force)
1168 unsigned oldLen = textLength();
1169 unsigned newLen = text->length();
1170 int delta = newLen - oldLen;
1171 unsigned end = len ? offset + len - 1 : offset;
1173 RootInlineBox* firstRootBox = 0;
1174 RootInlineBox* lastRootBox = 0;
1176 bool dirtiedLines = false;
1178 // Dirty all text boxes that include characters in between offset and offset+len.
1179 for (InlineTextBox* curr = firstTextBox(); curr; curr = curr->nextTextBox()) {
1180 // Text run is entirely before the affected range.
1181 if (curr->end() < offset)
1184 // Text run is entirely after the affected range.
1185 if (curr->start() > end) {
1186 curr->offsetRun(delta);
1187 RootInlineBox* root = curr->root();
1188 if (!firstRootBox) {
1189 firstRootBox = root;
1190 if (!dirtiedLines) {
1191 // The affected area was in between two runs. Go ahead and mark the root box of
1192 // the run after the affected area as dirty.
1193 firstRootBox->markDirty();
1194 dirtiedLines = true;
1198 } else if (curr->end() >= offset && curr->end() <= end) {
1199 // Text run overlaps with the left end of the affected range.
1200 curr->dirtyLineBoxes();
1201 dirtiedLines = true;
1202 } else if (curr->start() <= offset && curr->end() >= end) {
1203 // Text run subsumes the affected range.
1204 curr->dirtyLineBoxes();
1205 dirtiedLines = true;
1206 } else if (curr->start() <= end && curr->end() >= end) {
1207 // Text run overlaps with right end of the affected range.
1208 curr->dirtyLineBoxes();
1209 dirtiedLines = true;
1213 // Now we have to walk all of the clean lines and adjust their cached line break information
1214 // to reflect our updated offsets.
1216 lastRootBox = lastRootBox->nextRootBox();
1218 RootInlineBox* prev = firstRootBox->prevRootBox();
1220 firstRootBox = prev;
1221 } else if (lastTextBox()) {
1222 ASSERT(!lastRootBox);
1223 firstRootBox = lastTextBox()->root();
1224 firstRootBox->markDirty();
1225 dirtiedLines = true;
1227 for (RootInlineBox* curr = firstRootBox; curr && curr != lastRootBox; curr = curr->nextRootBox()) {
1228 if (curr->lineBreakObj() == this && curr->lineBreakPos() > end)
1229 curr->setLineBreakPos(curr->lineBreakPos() + delta);
1232 // If the text node is empty, dirty the line where new text will be inserted.
1233 if (!firstTextBox() && parent()) {
1234 parent()->dirtyLinesFromChangedChild(this);
1235 dirtiedLines = true;
1238 m_linesDirty = dirtiedLines;
1239 setText(text, force);
1242 static inline bool isInlineFlowOrEmptyText(const RenderObject* o)
1244 if (o->isRenderInline())
1248 StringImpl* text = toRenderText(o)->text();
1251 return !text->length();
1254 UChar RenderText::previousCharacter() const
1256 // find previous text renderer if one exists
1257 const RenderObject* previousText = this;
1258 while ((previousText = previousText->previousInPreOrder()))
1259 if (!isInlineFlowOrEmptyText(previousText))
1262 if (previousText && previousText->isText())
1263 if (StringImpl* previousString = toRenderText(previousText)->text())
1264 prev = (*previousString)[previousString->length() - 1];
1268 void RenderText::transformText(String& text) const
1271 switch (style()->textTransform()) {
1275 makeCapitalized(&text, previousCharacter());
1286 void RenderText::setTextInternal(PassRefPtr<StringImpl> text)
1290 if (m_needsTranscoding) {
1291 const TextEncoding* encoding = document()->decoder() ? &document()->decoder()->encoding() : 0;
1292 fontTranscoder().convert(m_text, style()->font().fontDescription(), encoding);
1297 transformText(m_text);
1299 // We use the same characters here as for list markers.
1300 // See the listMarkerText function in RenderListMarker.cpp.
1301 switch (style()->textSecurity()) {
1305 secureText(whiteBullet);
1311 secureText(blackSquare);
1316 ASSERT(!isBR() || (textLength() == 1 && m_text[0] == '\n'));
1318 m_isAllASCII = m_text.containsOnlyASCII();
1321 void RenderText::secureText(UChar mask)
1323 if (!m_text.length())
1326 int lastTypedCharacterOffsetToReveal = -1;
1327 String revealedText;
1328 SecureTextTimer* secureTextTimer = gSecureTextTimers ? gSecureTextTimers->get(this) : 0;
1329 if (secureTextTimer && secureTextTimer->isActive()) {
1330 lastTypedCharacterOffsetToReveal = secureTextTimer->lastTypedCharacterOffset();
1331 if (lastTypedCharacterOffsetToReveal >= 0)
1332 revealedText.append(m_text[lastTypedCharacterOffsetToReveal]);
1336 if (lastTypedCharacterOffsetToReveal >= 0) {
1337 m_text.replace(lastTypedCharacterOffsetToReveal, 1, revealedText);
1338 // m_text may be updated later before timer fires. We invalidate the lastTypedCharacterOffset to avoid inconsistency.
1339 secureTextTimer->invalidate();
1343 void RenderText::setText(PassRefPtr<StringImpl> text, bool force)
1347 if (!force && equal(m_text.impl(), text.get()))
1350 setTextInternal(text);
1351 setNeedsLayoutAndPrefWidthsRecalc();
1352 m_knownToHaveNoOverflowAndNoFallbackFonts = false;
1354 AXObjectCache* axObjectCache = document()->axObjectCache();
1355 if (axObjectCache->accessibilityEnabled())
1356 axObjectCache->contentChanged(this);
1359 String RenderText::textWithoutTranscoding() const
1361 // If m_text isn't transcoded or is secure, we can just return the modified text.
1362 if (!m_needsTranscoding || style()->textSecurity() != TSNONE)
1365 // Otherwise, we should use original text. If text-transform is
1366 // specified, we should transform the text on the fly.
1367 String text = originalText();
1369 transformText(text);
1373 void RenderText::dirtyLineBoxes(bool fullLayout)
1377 else if (!m_linesDirty) {
1378 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
1379 box->dirtyLineBoxes();
1381 m_linesDirty = false;
1384 InlineTextBox* RenderText::createTextBox()
1386 return new (renderArena()) InlineTextBox(this);
1389 InlineTextBox* RenderText::createInlineTextBox()
1391 InlineTextBox* textBox = createTextBox();
1392 if (!m_firstTextBox)
1393 m_firstTextBox = m_lastTextBox = textBox;
1395 m_lastTextBox->setNextTextBox(textBox);
1396 textBox->setPreviousTextBox(m_lastTextBox);
1397 m_lastTextBox = textBox;
1399 textBox->setIsText(true);
1403 void RenderText::positionLineBox(InlineBox* box)
1405 InlineTextBox* s = toInlineTextBox(box);
1407 // FIXME: should not be needed!!!
1409 // We want the box to be destroyed.
1411 if (m_firstTextBox == s)
1412 m_firstTextBox = s->nextTextBox();
1414 s->prevTextBox()->setNextTextBox(s->nextTextBox());
1415 if (m_lastTextBox == s)
1416 m_lastTextBox = s->prevTextBox();
1418 s->nextTextBox()->setPreviousTextBox(s->prevTextBox());
1419 s->destroy(renderArena());
1423 m_containsReversedText |= !s->isLeftToRightDirection();
1426 float RenderText::width(unsigned from, unsigned len, float xPos, bool firstLine, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
1428 if (from >= textLength())
1431 if (from + len > textLength())
1432 len = textLength() - from;
1434 return width(from, len, style(firstLine)->font(), xPos, fallbackFonts, glyphOverflow);
1437 float RenderText::width(unsigned from, unsigned len, const Font& f, float xPos, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
1439 ASSERT(from + len <= textLength());
1444 if (&f == &style()->font()) {
1445 if (!style()->preserveNewline() && !from && len == textLength() && (!glyphOverflow || !glyphOverflow->computeBounds)) {
1446 if (fallbackFonts) {
1447 ASSERT(glyphOverflow);
1448 if (preferredLogicalWidthsDirty() || !m_knownToHaveNoOverflowAndNoFallbackFonts) {
1449 const_cast<RenderText*>(this)->computePreferredLogicalWidths(0, *fallbackFonts, *glyphOverflow);
1450 if (fallbackFonts->isEmpty() && !glyphOverflow->left && !glyphOverflow->right && !glyphOverflow->top && !glyphOverflow->bottom)
1451 m_knownToHaveNoOverflowAndNoFallbackFonts = true;
1455 w = maxLogicalWidth();
1457 w = widthFromCache(f, from, len, xPos, fallbackFonts, glyphOverflow);
1459 TextRun run = RenderBlock::constructTextRun(const_cast<RenderText*>(this), f, text()->characters() + from, len, style());
1460 run.setCharactersLength(textLength() - from);
1461 ASSERT(run.charactersLength() >= run.length());
1463 run.setAllowTabs(allowTabs());
1465 w = f.width(run, fallbackFonts, glyphOverflow);
1471 IntRect RenderText::linesBoundingBox() const
1475 ASSERT(!firstTextBox() == !lastTextBox()); // Either both are null or both exist.
1476 if (firstTextBox() && lastTextBox()) {
1477 // Return the width of the minimal left side and the maximal right side.
1478 float logicalLeftSide = 0;
1479 float logicalRightSide = 0;
1480 for (InlineTextBox* curr = firstTextBox(); curr; curr = curr->nextTextBox()) {
1481 if (curr == firstTextBox() || curr->logicalLeft() < logicalLeftSide)
1482 logicalLeftSide = curr->logicalLeft();
1483 if (curr == firstTextBox() || curr->logicalRight() > logicalRightSide)
1484 logicalRightSide = curr->logicalRight();
1487 bool isHorizontal = style()->isHorizontalWritingMode();
1489 float x = isHorizontal ? logicalLeftSide : firstTextBox()->x();
1490 float y = isHorizontal ? firstTextBox()->y() : logicalLeftSide;
1491 float width = isHorizontal ? logicalRightSide - logicalLeftSide : lastTextBox()->logicalBottom() - x;
1492 float height = isHorizontal ? lastTextBox()->logicalBottom() - y : logicalRightSide - logicalLeftSide;
1493 result = enclosingIntRect(FloatRect(x, y, width, height));
1499 IntRect RenderText::linesVisualOverflowBoundingBox() const
1501 if (!firstTextBox())
1504 // Return the width of the minimal left side and the maximal right side.
1505 int logicalLeftSide = numeric_limits<int>::max();
1506 int logicalRightSide = numeric_limits<int>::min();
1507 for (InlineTextBox* curr = firstTextBox(); curr; curr = curr->nextTextBox()) {
1508 logicalLeftSide = min(logicalLeftSide, curr->logicalLeftVisualOverflow());
1509 logicalRightSide = max(logicalRightSide, curr->logicalRightVisualOverflow());
1512 int logicalTop = firstTextBox()->logicalTopVisualOverflow();
1513 int logicalWidth = logicalRightSide - logicalLeftSide;
1514 int logicalHeight = lastTextBox()->logicalBottomVisualOverflow() - logicalTop;
1516 IntRect rect(logicalLeftSide, logicalTop, logicalWidth, logicalHeight);
1517 if (!style()->isHorizontalWritingMode())
1518 rect = rect.transposedRect();
1522 IntRect RenderText::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
1524 RenderObject* rendererToRepaint = containingBlock();
1526 // Do not cross self-painting layer boundaries.
1527 RenderObject* enclosingLayerRenderer = enclosingLayer()->renderer();
1528 if (enclosingLayerRenderer != rendererToRepaint && !rendererToRepaint->isDescendantOf(enclosingLayerRenderer))
1529 rendererToRepaint = enclosingLayerRenderer;
1531 // The renderer we chose to repaint may be an ancestor of repaintContainer, but we need to do a repaintContainer-relative repaint.
1532 if (repaintContainer && repaintContainer != rendererToRepaint && !rendererToRepaint->isDescendantOf(repaintContainer))
1533 return repaintContainer->clippedOverflowRectForRepaint(repaintContainer);
1535 return rendererToRepaint->clippedOverflowRectForRepaint(repaintContainer);
1538 LayoutRect RenderText::selectionRectForRepaint(RenderBoxModelObject* repaintContainer, bool clipToVisibleContent)
1540 ASSERT(!needsLayout());
1542 if (selectionState() == SelectionNone)
1543 return LayoutRect();
1544 RenderBlock* cb = containingBlock();
1546 return LayoutRect();
1548 // Now calculate startPos and endPos for painting selection.
1549 // We include a selection while endPos > 0
1550 LayoutUnit startPos, endPos;
1551 if (selectionState() == SelectionInside) {
1552 // We are fully selected.
1554 endPos = textLength();
1556 selectionStartEnd(startPos, endPos);
1557 if (selectionState() == SelectionStart)
1558 endPos = textLength();
1559 else if (selectionState() == SelectionEnd)
1563 if (startPos == endPos)
1567 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
1568 rect.unite(box->localSelectionRect(startPos, endPos));
1569 rect.unite(ellipsisRectForBox(box, startPos, endPos));
1572 if (clipToVisibleContent)
1573 computeRectForRepaint(repaintContainer, rect);
1575 if (cb->hasColumns())
1576 cb->adjustRectForColumns(rect);
1578 rect = localToContainerQuad(FloatRect(rect), repaintContainer).enclosingBoundingBox();
1584 int RenderText::caretMinOffset() const
1586 InlineTextBox* box = firstTextBox();
1589 int minOffset = box->start();
1590 for (box = box->nextTextBox(); box; box = box->nextTextBox())
1591 minOffset = min<int>(minOffset, box->start());
1595 int RenderText::caretMaxOffset() const
1597 InlineTextBox* box = lastTextBox();
1599 return textLength();
1600 int maxOffset = box->start() + box->len();
1601 for (box = box->prevTextBox(); box; box = box->prevTextBox())
1602 maxOffset = max<int>(maxOffset, box->start() + box->len());
1606 unsigned RenderText::caretMaxRenderedOffset() const
1609 for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
1614 int RenderText::previousOffset(int current) const
1616 StringImpl* si = m_text.impl();
1617 TextBreakIterator* iterator = cursorMovementIterator(si->characters(), si->length());
1621 long result = textBreakPreceding(iterator, current);
1622 if (result == TextBreakDone)
1623 result = current - 1;
1629 #if PLATFORM(MAC) || PLATFORM(CHROMIUM) && OS(MAC_OS_X)
1631 #define HANGUL_CHOSEONG_START (0x1100)
1632 #define HANGUL_CHOSEONG_END (0x115F)
1633 #define HANGUL_JUNGSEONG_START (0x1160)
1634 #define HANGUL_JUNGSEONG_END (0x11A2)
1635 #define HANGUL_JONGSEONG_START (0x11A8)
1636 #define HANGUL_JONGSEONG_END (0x11F9)
1637 #define HANGUL_SYLLABLE_START (0xAC00)
1638 #define HANGUL_SYLLABLE_END (0xD7AF)
1639 #define HANGUL_JONGSEONG_COUNT (28)
1650 inline bool isHangulLVT(UChar32 character)
1652 return (character - HANGUL_SYLLABLE_START) % HANGUL_JONGSEONG_COUNT;
1655 inline bool isMark(UChar32 c)
1657 int8_t charType = u_charType(c);
1658 return charType == U_NON_SPACING_MARK || charType == U_ENCLOSING_MARK || charType == U_COMBINING_SPACING_MARK;
1661 inline bool isRegionalIndicator(UChar32 c)
1663 // National flag emoji each consists of a pair of regional indicator symbols.
1664 return 0x1F1E6 <= c && c <= 0x1F1FF;
1669 int RenderText::previousOffsetForBackwardDeletion(int current) const
1671 #if PLATFORM(MAC) || PLATFORM(CHROMIUM) && OS(MAC_OS_X)
1673 StringImpl& text = *m_text.impl();
1675 bool sawRegionalIndicator = false;
1676 while (current > 0) {
1677 if (U16_IS_TRAIL(text[--current]))
1682 UChar32 character = text.characterStartingAt(current);
1684 if (sawRegionalIndicator) {
1685 // We don't check if the pair of regional indicator symbols before current position can actually be combined
1686 // into a flag, and just delete it. This may not agree with how the pair is rendered in edge cases,
1687 // but is good enough in practice.
1688 if (isRegionalIndicator(character))
1690 // Don't delete a preceding character that isn't a regional indicator symbol.
1691 U16_FWD_1_UNSAFE(text, current);
1694 // We don't combine characters in Armenian ... Limbu range for backward deletion.
1695 if ((character >= 0x0530) && (character < 0x1950))
1698 if (isRegionalIndicator(character)) {
1699 sawRegionalIndicator = true;
1703 if (!isMark(character) && (character != 0xFF9E) && (character != 0xFF9F))
1711 character = text.characterStartingAt(current);
1712 if (((character >= HANGUL_CHOSEONG_START) && (character <= HANGUL_JONGSEONG_END)) || ((character >= HANGUL_SYLLABLE_START) && (character <= HANGUL_SYLLABLE_END))) {
1714 HangulState initialState;
1716 if (character < HANGUL_JUNGSEONG_START)
1717 state = HangulStateL;
1718 else if (character < HANGUL_JONGSEONG_START)
1719 state = HangulStateV;
1720 else if (character < HANGUL_SYLLABLE_START)
1721 state = HangulStateT;
1723 state = isHangulLVT(character) ? HangulStateLVT : HangulStateLV;
1725 initialState = state;
1727 while (current > 0 && ((character = text.characterStartingAt(current - 1)) >= HANGUL_CHOSEONG_START) && (character <= HANGUL_SYLLABLE_END) && ((character <= HANGUL_JONGSEONG_END) || (character >= HANGUL_SYLLABLE_START))) {
1730 if (character <= HANGUL_CHOSEONG_END)
1731 state = HangulStateL;
1732 else if ((character >= HANGUL_SYLLABLE_START) && (character <= HANGUL_SYLLABLE_END) && !isHangulLVT(character))
1733 state = HangulStateLV;
1734 else if (character > HANGUL_JUNGSEONG_END)
1735 state = HangulStateBreak;
1738 if ((character >= HANGUL_JUNGSEONG_START) && (character <= HANGUL_JUNGSEONG_END))
1739 state = HangulStateV;
1740 else if ((character >= HANGUL_SYLLABLE_START) && (character <= HANGUL_SYLLABLE_END))
1741 state = (isHangulLVT(character) ? HangulStateLVT : HangulStateLV);
1742 else if (character < HANGUL_JUNGSEONG_START)
1743 state = HangulStateBreak;
1746 state = (character < HANGUL_JUNGSEONG_START) ? HangulStateL : HangulStateBreak;
1749 if (state == HangulStateBreak)
1758 // Platforms other than Mac delete by one code point.
1759 if (U16_IS_TRAIL(m_text[--current]))
1767 int RenderText::nextOffset(int current) const
1769 StringImpl* si = m_text.impl();
1770 TextBreakIterator* iterator = cursorMovementIterator(si->characters(), si->length());
1774 long result = textBreakFollowing(iterator, current);
1775 if (result == TextBreakDone)
1776 result = current + 1;
1784 void RenderText::checkConsistency() const
1786 #ifdef CHECK_CONSISTENCY
1787 const InlineTextBox* prev = 0;
1788 for (const InlineTextBox* child = m_firstTextBox; child != 0; child = child->nextTextBox()) {
1789 ASSERT(child->renderer() == this);
1790 ASSERT(child->prevTextBox() == prev);
1793 ASSERT(prev == m_lastTextBox);
1799 void RenderText::momentarilyRevealLastTypedCharacter(unsigned lastTypedCharacterOffset)
1801 if (!gSecureTextTimers)
1802 gSecureTextTimers = new SecureTextTimerMap;
1804 SecureTextTimer* secureTextTimer = gSecureTextTimers->get(this);
1805 if (!secureTextTimer) {
1806 secureTextTimer = new SecureTextTimer(this);
1807 gSecureTextTimers->add(this, secureTextTimer);
1809 secureTextTimer->restartWithNewText(lastTypedCharacterOffset);
1812 } // namespace WebCore