• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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)
7  *
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.
12  *
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.
17  *
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.
22  *
23  */
24 
25 #include "config.h"
26 #include "RenderText.h"
27 
28 #include "CharacterNames.h"
29 #include "FloatQuad.h"
30 #include "FrameView.h"
31 #include "InlineTextBox.h"
32 #include "Range.h"
33 #include "RenderArena.h"
34 #include "RenderBlock.h"
35 #include "RenderLayer.h"
36 #include "RenderView.h"
37 #include "Text.h"
38 #include "TextBreakIterator.h"
39 #include "VisiblePosition.h"
40 #include "break_lines.h"
41 #include <wtf/AlwaysInline.h>
42 
43 using namespace std;
44 using namespace WTF;
45 using namespace Unicode;
46 
47 namespace WebCore {
48 
49 // FIXME: Move to StringImpl.h eventually.
charactersAreAllASCII(StringImpl * text)50 static inline bool charactersAreAllASCII(StringImpl* text)
51 {
52     return charactersAreAllASCII(text->characters(), text->length());
53 }
54 
RenderText(Node * node,PassRefPtr<StringImpl> str)55 RenderText::RenderText(Node* node, PassRefPtr<StringImpl> str)
56      : RenderObject(node)
57      , m_minWidth(-1)
58      , m_text(document()->displayStringModifiedByEncoding(str))
59      , m_firstTextBox(0)
60      , m_lastTextBox(0)
61      , m_maxWidth(-1)
62      , m_beginMinWidth(0)
63      , m_endMinWidth(0)
64      , m_hasTab(false)
65      , m_linesDirty(false)
66      , m_containsReversedText(false)
67      , m_isAllASCII(charactersAreAllASCII(m_text.get()))
68      , m_knownNotToUseFallbackFonts(false)
69 {
70     ASSERT(m_text);
71 
72     setIsText();
73 
74     // FIXME: It would be better to call this only if !m_text->containsOnlyWhitespace().
75     // But that might slow things down, and maybe should only be done if visuallyNonEmpty
76     // is still false. Not making any change for now, but should consider in the future.
77     view()->frameView()->setIsVisuallyNonEmpty();
78 }
79 
80 #ifndef NDEBUG
81 
~RenderText()82 RenderText::~RenderText()
83 {
84     ASSERT(!m_firstTextBox);
85     ASSERT(!m_lastTextBox);
86 }
87 
88 #endif
89 
renderName() const90 const char* RenderText::renderName() const
91 {
92     return "RenderText";
93 }
94 
isTextFragment() const95 bool RenderText::isTextFragment() const
96 {
97     return false;
98 }
99 
isWordBreak() const100 bool RenderText::isWordBreak() const
101 {
102     return false;
103 }
104 
styleDidChange(StyleDifference diff,const RenderStyle * oldStyle)105 void RenderText::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
106 {
107     // There is no need to ever schedule repaints from a style change of a text run, since
108     // we already did this for the parent of the text run.
109     // We do have to schedule layouts, though, since a style change can force us to
110     // need to relayout.
111     if (diff == StyleDifferenceLayout) {
112         setNeedsLayoutAndPrefWidthsRecalc();
113         m_knownNotToUseFallbackFonts = false;
114     }
115 
116     ETextTransform oldTransform = oldStyle ? oldStyle->textTransform() : TTNONE;
117     ETextSecurity oldSecurity = oldStyle ? oldStyle->textSecurity() : TSNONE;
118 
119     if (oldTransform != style()->textTransform() || oldSecurity != style()->textSecurity()) {
120         if (RefPtr<StringImpl> textToTransform = originalText())
121             setText(textToTransform.release(), true);
122     }
123 }
124 
destroy()125 void RenderText::destroy()
126 {
127     if (!documentBeingDestroyed()) {
128         if (firstTextBox()) {
129             if (isBR()) {
130                 RootInlineBox* next = firstTextBox()->root()->nextRootBox();
131                 if (next)
132                     next->markDirty();
133             }
134             for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
135                 box->remove();
136         } else if (parent())
137             parent()->dirtyLinesFromChangedChild(this);
138     }
139     deleteTextBoxes();
140     RenderObject::destroy();
141 }
142 
extractTextBox(InlineTextBox * box)143 void RenderText::extractTextBox(InlineTextBox* box)
144 {
145     checkConsistency();
146 
147     m_lastTextBox = box->prevTextBox();
148     if (box == m_firstTextBox)
149         m_firstTextBox = 0;
150     if (box->prevTextBox())
151         box->prevTextBox()->setNextLineBox(0);
152     box->setPreviousLineBox(0);
153     for (InlineRunBox* curr = box; curr; curr = curr->nextLineBox())
154         curr->setExtracted();
155 
156     checkConsistency();
157 }
158 
attachTextBox(InlineTextBox * box)159 void RenderText::attachTextBox(InlineTextBox* box)
160 {
161     checkConsistency();
162 
163     if (m_lastTextBox) {
164         m_lastTextBox->setNextLineBox(box);
165         box->setPreviousLineBox(m_lastTextBox);
166     } else
167         m_firstTextBox = box;
168     InlineTextBox* last = box;
169     for (InlineTextBox* curr = box; curr; curr = curr->nextTextBox()) {
170         curr->setExtracted(false);
171         last = curr;
172     }
173     m_lastTextBox = last;
174 
175     checkConsistency();
176 }
177 
removeTextBox(InlineTextBox * box)178 void RenderText::removeTextBox(InlineTextBox* box)
179 {
180     checkConsistency();
181 
182     if (box == m_firstTextBox)
183         m_firstTextBox = box->nextTextBox();
184     if (box == m_lastTextBox)
185         m_lastTextBox = box->prevTextBox();
186     if (box->nextTextBox())
187         box->nextTextBox()->setPreviousLineBox(box->prevTextBox());
188     if (box->prevTextBox())
189         box->prevTextBox()->setNextLineBox(box->nextTextBox());
190 
191     checkConsistency();
192 }
193 
deleteTextBoxes()194 void RenderText::deleteTextBoxes()
195 {
196     if (firstTextBox()) {
197         RenderArena* arena = renderArena();
198         InlineTextBox* next;
199         for (InlineTextBox* curr = firstTextBox(); curr; curr = next) {
200             next = curr->nextTextBox();
201             curr->destroy(arena);
202         }
203         m_firstTextBox = m_lastTextBox = 0;
204     }
205 }
206 
originalText() const207 PassRefPtr<StringImpl> RenderText::originalText() const
208 {
209     Node* e = node();
210     return e ? static_cast<Text*>(e)->string() : 0;
211 }
212 
absoluteRects(Vector<IntRect> & rects,int tx,int ty)213 void RenderText::absoluteRects(Vector<IntRect>& rects, int tx, int ty)
214 {
215     for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
216         rects.append(IntRect(tx + box->x(), ty + box->y(), box->width(), box->height()));
217 }
218 
absoluteRectsForRange(Vector<IntRect> & rects,unsigned start,unsigned end,bool useSelectionHeight)219 void RenderText::absoluteRectsForRange(Vector<IntRect>& rects, unsigned start, unsigned end, bool useSelectionHeight)
220 {
221     // Work around signed/unsigned issues. This function takes unsigneds, and is often passed UINT_MAX
222     // to mean "all the way to the end". InlineTextBox coordinates are unsigneds, so changing this
223     // function to take ints causes various internal mismatches. But selectionRect takes ints, and
224     // passing UINT_MAX to it causes trouble. Ideally we'd change selectionRect to take unsigneds, but
225     // that would cause many ripple effects, so for now we'll just clamp our unsigned parameters to INT_MAX.
226     ASSERT(end == UINT_MAX || end <= INT_MAX);
227     ASSERT(start <= INT_MAX);
228     start = min(start, static_cast<unsigned>(INT_MAX));
229     end = min(end, static_cast<unsigned>(INT_MAX));
230 
231     FloatPoint absPos = localToAbsolute(FloatPoint());
232 
233     for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
234         // Note: box->end() returns the index of the last character, not the index past it
235         if (start <= box->start() && box->end() < end) {
236             IntRect r = IntRect(absPos.x() + box->x(), absPos.y() + box->y(), box->width(), box->height());
237             if (useSelectionHeight) {
238                 IntRect selectionRect = box->selectionRect(absPos.x(), absPos.y(), start, end);
239                 r.setHeight(selectionRect.height());
240                 r.setY(selectionRect.y());
241             }
242             rects.append(r);
243         } else {
244             unsigned realEnd = min(box->end() + 1, end);
245             IntRect r = box->selectionRect(absPos.x(), absPos.y(), start, realEnd);
246             if (!r.isEmpty()) {
247                 if (!useSelectionHeight) {
248                     // change the height and y position because selectionRect uses selection-specific values
249                     r.setHeight(box->height());
250                     r.setY(absPos.y() + box->y());
251                 }
252                 rects.append(r);
253             }
254         }
255     }
256 }
257 
absoluteQuads(Vector<FloatQuad> & quads)258 void RenderText::absoluteQuads(Vector<FloatQuad>& quads)
259 {
260     for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
261         quads.append(localToAbsoluteQuad(FloatRect(box->x(), box->y(), box->width(), box->height())));
262 }
263 
absoluteQuadsForRange(Vector<FloatQuad> & quads,unsigned start,unsigned end,bool useSelectionHeight)264 void RenderText::absoluteQuadsForRange(Vector<FloatQuad>& quads, unsigned start, unsigned end, bool useSelectionHeight)
265 {
266     // Work around signed/unsigned issues. This function takes unsigneds, and is often passed UINT_MAX
267     // to mean "all the way to the end". InlineTextBox coordinates are unsigneds, so changing this
268     // function to take ints causes various internal mismatches. But selectionRect takes ints, and
269     // passing UINT_MAX to it causes trouble. Ideally we'd change selectionRect to take unsigneds, but
270     // that would cause many ripple effects, so for now we'll just clamp our unsigned parameters to INT_MAX.
271     ASSERT(end == UINT_MAX || end <= INT_MAX);
272     ASSERT(start <= INT_MAX);
273     start = min(start, static_cast<unsigned>(INT_MAX));
274     end = min(end, static_cast<unsigned>(INT_MAX));
275 
276     for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
277         // Note: box->end() returns the index of the last character, not the index past it
278         if (start <= box->start() && box->end() < end) {
279             IntRect r = IntRect(box->x(), box->y(), box->width(), box->height());
280             if (useSelectionHeight) {
281                 IntRect selectionRect = box->selectionRect(0, 0, start, end);
282                 r.setHeight(selectionRect.height());
283                 r.setY(selectionRect.y());
284             }
285             quads.append(localToAbsoluteQuad(FloatRect(r)));
286         } else {
287             unsigned realEnd = min(box->end() + 1, end);
288             IntRect r = box->selectionRect(0, 0, start, realEnd);
289             if (!r.isEmpty()) {
290                 if (!useSelectionHeight) {
291                     // change the height and y position because selectionRect uses selection-specific values
292                     r.setHeight(box->height());
293                     r.setY(box->y());
294                 }
295                 quads.append(localToAbsoluteQuad(FloatRect(r)));
296             }
297         }
298     }
299 }
300 
findNextInlineTextBox(int offset,int & pos) const301 InlineTextBox* RenderText::findNextInlineTextBox(int offset, int& pos) const
302 {
303     // The text runs point to parts of the RenderText's m_text
304     // (they don't include '\n')
305     // Find the text run that includes the character at offset
306     // and return pos, which is the position of the char in the run.
307 
308     if (!m_firstTextBox)
309         return 0;
310 
311     InlineTextBox* s = m_firstTextBox;
312     int off = s->len();
313     while (offset > off && s->nextTextBox()) {
314         s = s->nextTextBox();
315         off = s->start() + s->len();
316     }
317     // we are now in the correct text run
318     pos = (offset > off ? s->len() : s->len() - (off - offset) );
319     return s;
320 }
321 
positionForPoint(const IntPoint & point)322 VisiblePosition RenderText::positionForPoint(const IntPoint& point)
323 {
324     if (!firstTextBox() || textLength() == 0)
325         return createVisiblePosition(0, DOWNSTREAM);
326 
327     // Get the offset for the position, since this will take rtl text into account.
328     int offset;
329 
330     // FIXME: We should be able to roll these special cases into the general cases in the loop below.
331     if (firstTextBox() && point.y() <  firstTextBox()->root()->bottomOverflow() && point.x() < firstTextBox()->m_x) {
332         // at the y coordinate of the first line or above
333         // and the x coordinate is to the left of the first text box left edge
334         offset = firstTextBox()->offsetForPosition(point.x());
335         return createVisiblePosition(offset + firstTextBox()->start(), DOWNSTREAM);
336     }
337     if (lastTextBox() && point.y() >= lastTextBox()->root()->topOverflow() && point.x() >= lastTextBox()->m_x + lastTextBox()->m_width) {
338         // at the y coordinate of the last line or below
339         // and the x coordinate is to the right of the last text box right edge
340         offset = lastTextBox()->offsetForPosition(point.x());
341         return createVisiblePosition(offset + lastTextBox()->start(), DOWNSTREAM);
342     }
343 
344     InlineTextBox* lastBoxAbove = 0;
345     for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
346         if (point.y() >= box->root()->topOverflow()) {
347             int bottom = box->root()->nextRootBox() ? box->root()->nextRootBox()->topOverflow() : box->root()->bottomOverflow();
348             if (point.y() < bottom) {
349                 offset = box->offsetForPosition(point.x());
350 
351                 if (point.x() == box->m_x)
352                     // the x coordinate is equal to the left edge of this box
353                     // the affinity must be downstream so the position doesn't jump back to the previous line
354                     return createVisiblePosition(offset + box->start(), DOWNSTREAM);
355 
356                 if (point.x() < box->m_x + box->m_width)
357                     // and the x coordinate is to the left of the right edge of this box
358                     // check to see if position goes in this box
359                     return createVisiblePosition(offset + box->start(), offset > 0 ? VP_UPSTREAM_IF_POSSIBLE : DOWNSTREAM);
360 
361                 if (!box->prevOnLine() && point.x() < box->m_x)
362                     // box is first on line
363                     // and the x coordinate is to the left of the first text box left edge
364                     return createVisiblePosition(offset + box->start(), DOWNSTREAM);
365 
366                 if (!box->nextOnLine())
367                     // box is last on line
368                     // and the x coordinate is to the right of the last text box right edge
369                     // generate VisiblePosition, use UPSTREAM affinity if possible
370                     return createVisiblePosition(offset + box->start(), offset > 0 ? VP_UPSTREAM_IF_POSSIBLE : DOWNSTREAM);
371             }
372             lastBoxAbove = box;
373         }
374     }
375 
376     return createVisiblePosition(lastBoxAbove ? lastBoxAbove->start() + lastBoxAbove->len() : 0, DOWNSTREAM);
377 }
378 
localCaretRect(InlineBox * inlineBox,int caretOffset,int * extraWidthToEndOfLine)379 IntRect RenderText::localCaretRect(InlineBox* inlineBox, int caretOffset, int* extraWidthToEndOfLine)
380 {
381     if (!inlineBox)
382         return IntRect();
383 
384     ASSERT(inlineBox->isInlineTextBox());
385     if (!inlineBox->isInlineTextBox())
386         return IntRect();
387 
388     InlineTextBox* box = static_cast<InlineTextBox*>(inlineBox);
389 
390     int height = box->root()->bottomOverflow() - box->root()->topOverflow();
391     int top = box->root()->topOverflow();
392 
393     int left = box->positionForOffset(caretOffset);
394 
395     // Distribute the caret's width to either side of the offset.
396     int caretWidthLeftOfOffset = caretWidth / 2;
397     left -= caretWidthLeftOfOffset;
398     int caretWidthRightOfOffset = caretWidth - caretWidthLeftOfOffset;
399 
400     int rootLeft = box->root()->x();
401     int rootRight = rootLeft + box->root()->width();
402     // FIXME: should we use the width of the root inline box or the
403     // width of the containing block for this?
404     if (extraWidthToEndOfLine)
405         *extraWidthToEndOfLine = (box->root()->width() + rootLeft) - (left + 1);
406 
407     RenderBlock* cb = containingBlock();
408     if (style()->autoWrap()) {
409         int availableWidth = cb->lineWidth(top, false);
410         if (box->direction() == LTR)
411             left = min(left, rootLeft + availableWidth - caretWidthRightOfOffset);
412         else
413             left = max(left, cb->x());
414     } else {
415         // If there is no wrapping, the caret can leave its containing block, but not its root line box.
416         if (cb->style()->direction() == LTR) {
417             int rightEdge = max(cb->width(), rootRight);
418             left = min(left, rightEdge - caretWidthRightOfOffset);
419             left = max(left, rootLeft);
420         } else {
421             int leftEdge = min(cb->x(), rootLeft);
422             left = max(left, leftEdge);
423             left = min(left, rootRight - caretWidth);
424         }
425     }
426 
427     return IntRect(left, top, caretWidth, height);
428 }
429 
widthFromCache(const Font & f,int start,int len,int xPos,HashSet<const SimpleFontData * > * fallbackFonts) const430 ALWAYS_INLINE int RenderText::widthFromCache(const Font& f, int start, int len, int xPos, HashSet<const SimpleFontData*>* fallbackFonts) const
431 {
432     if (f.isFixedPitch() && !f.isSmallCaps() && m_isAllASCII) {
433         int monospaceCharacterWidth = f.spaceWidth();
434         int tabWidth = allowTabs() ? monospaceCharacterWidth * 8 : 0;
435         int w = 0;
436         bool isSpace;
437         bool previousCharWasSpace = true; // FIXME: Preserves historical behavior, but seems wrong for start > 0.
438         for (int i = start; i < start + len; i++) {
439             char c = (*m_text)[i];
440             if (c <= ' ') {
441                 if (c == ' ' || c == '\n') {
442                     w += monospaceCharacterWidth;
443                     isSpace = true;
444                 } else if (c == '\t') {
445                     w += tabWidth ? tabWidth - ((xPos + w) % tabWidth) : monospaceCharacterWidth;
446                     isSpace = true;
447                 } else
448                     isSpace = false;
449             } else {
450                 w += monospaceCharacterWidth;
451                 isSpace = false;
452             }
453             if (isSpace && !previousCharWasSpace)
454                 w += f.wordSpacing();
455             previousCharWasSpace = isSpace;
456         }
457         return w;
458     }
459 
460     return f.width(TextRun(text()->characters() + start, len, allowTabs(), xPos), fallbackFonts);
461 }
462 
trimmedPrefWidths(int leadWidth,int & beginMinW,bool & beginWS,int & endMinW,bool & endWS,bool & hasBreakableChar,bool & hasBreak,int & beginMaxW,int & endMaxW,int & minW,int & maxW,bool & stripFrontSpaces)463 void RenderText::trimmedPrefWidths(int leadWidth,
464                                    int& beginMinW, bool& beginWS,
465                                    int& endMinW, bool& endWS,
466                                    bool& hasBreakableChar, bool& hasBreak,
467                                    int& beginMaxW, int& endMaxW,
468                                    int& minW, int& maxW, bool& stripFrontSpaces)
469 {
470     bool collapseWhiteSpace = style()->collapseWhiteSpace();
471     if (!collapseWhiteSpace)
472         stripFrontSpaces = false;
473 
474     if (m_hasTab || prefWidthsDirty())
475         calcPrefWidths(leadWidth);
476 
477     beginWS = !stripFrontSpaces && m_hasBeginWS;
478     endWS = m_hasEndWS;
479 
480     int len = textLength();
481 
482     if (!len || (stripFrontSpaces && m_text->containsOnlyWhitespace())) {
483         beginMinW = 0;
484         endMinW = 0;
485         beginMaxW = 0;
486         endMaxW = 0;
487         minW = 0;
488         maxW = 0;
489         hasBreak = false;
490         return;
491     }
492 
493     minW = m_minWidth;
494     maxW = m_maxWidth;
495 
496     beginMinW = m_beginMinWidth;
497     endMinW = m_endMinWidth;
498 
499     hasBreakableChar = m_hasBreakableChar;
500     hasBreak = m_hasBreak;
501 
502     if ((*m_text)[0] == ' ' || ((*m_text)[0] == '\n' && !style()->preserveNewline()) || (*m_text)[0] == '\t') {
503         const Font& f = style()->font(); // FIXME: This ignores first-line.
504         if (stripFrontSpaces) {
505             const UChar space = ' ';
506             int spaceWidth = f.width(TextRun(&space, 1));
507             maxW -= spaceWidth;
508         } else
509             maxW += f.wordSpacing();
510     }
511 
512     stripFrontSpaces = collapseWhiteSpace && m_hasEndWS;
513 
514     if (!style()->autoWrap() || minW > maxW)
515         minW = maxW;
516 
517     // Compute our max widths by scanning the string for newlines.
518     if (hasBreak) {
519         const Font& f = style()->font(); // FIXME: This ignores first-line.
520         bool firstLine = true;
521         beginMaxW = maxW;
522         endMaxW = maxW;
523         for (int i = 0; i < len; i++) {
524             int linelen = 0;
525             while (i + linelen < len && (*m_text)[i + linelen] != '\n')
526                 linelen++;
527 
528             if (linelen) {
529                 endMaxW = widthFromCache(f, i, linelen, leadWidth + endMaxW, 0);
530                 if (firstLine) {
531                     firstLine = false;
532                     leadWidth = 0;
533                     beginMaxW = endMaxW;
534                 }
535                 i += linelen;
536             } else if (firstLine) {
537                 beginMaxW = 0;
538                 firstLine = false;
539                 leadWidth = 0;
540             }
541 
542             if (i == len - 1)
543                 // A <pre> run that ends with a newline, as in, e.g.,
544                 // <pre>Some text\n\n<span>More text</pre>
545                 endMaxW = 0;
546         }
547     }
548 }
549 
isSpaceAccordingToStyle(UChar c,RenderStyle * style)550 static inline bool isSpaceAccordingToStyle(UChar c, RenderStyle* style)
551 {
552     return c == ' ' || (c == noBreakSpace && style->nbspMode() == SPACE);
553 }
554 
minPrefWidth() const555 int RenderText::minPrefWidth() const
556 {
557     if (prefWidthsDirty())
558         const_cast<RenderText*>(this)->calcPrefWidths(0);
559 
560     return m_minWidth;
561 }
562 
maxPrefWidth() const563 int RenderText::maxPrefWidth() const
564 {
565     if (prefWidthsDirty())
566         const_cast<RenderText*>(this)->calcPrefWidths(0);
567 
568     return m_maxWidth;
569 }
570 
calcPrefWidths(int leadWidth)571 void RenderText::calcPrefWidths(int leadWidth)
572 {
573     HashSet<const SimpleFontData*> fallbackFonts;
574     calcPrefWidths(leadWidth, fallbackFonts);
575     if (fallbackFonts.isEmpty())
576         m_knownNotToUseFallbackFonts = true;
577 }
578 
calcPrefWidths(int leadWidth,HashSet<const SimpleFontData * > & fallbackFonts)579 void RenderText::calcPrefWidths(int leadWidth, HashSet<const SimpleFontData*>& fallbackFonts)
580 {
581     ASSERT(m_hasTab || prefWidthsDirty() || !m_knownNotToUseFallbackFonts);
582 
583     m_minWidth = 0;
584     m_beginMinWidth = 0;
585     m_endMinWidth = 0;
586     m_maxWidth = 0;
587 
588     if (isBR())
589         return;
590 
591     int currMinWidth = 0;
592     int currMaxWidth = 0;
593     m_hasBreakableChar = false;
594     m_hasBreak = false;
595     m_hasTab = false;
596     m_hasBeginWS = false;
597     m_hasEndWS = false;
598 
599     const Font& f = style()->font(); // FIXME: This ignores first-line.
600     int wordSpacing = style()->wordSpacing();
601     int len = textLength();
602     const UChar* txt = characters();
603     bool needsWordSpacing = false;
604     bool ignoringSpaces = false;
605     bool isSpace = false;
606     bool firstWord = true;
607     bool firstLine = true;
608     int nextBreakable = -1;
609     int lastWordBoundary = 0;
610 
611     bool breakNBSP = style()->autoWrap() && style()->nbspMode() == SPACE;
612     bool breakAll = (style()->wordBreak() == BreakAllWordBreak || style()->wordBreak() == BreakWordBreak) && style()->autoWrap();
613 
614     for (int i = 0; i < len; i++) {
615         UChar c = txt[i];
616 
617         bool previousCharacterIsSpace = isSpace;
618 
619         bool isNewline = false;
620         if (c == '\n') {
621             if (style()->preserveNewline()) {
622                 m_hasBreak = true;
623                 isNewline = true;
624                 isSpace = false;
625             } else
626                 isSpace = true;
627         } else if (c == '\t') {
628             if (!style()->collapseWhiteSpace()) {
629                 m_hasTab = true;
630                 isSpace = false;
631             } else
632                 isSpace = true;
633         } else
634             isSpace = c == ' ';
635 
636         if ((isSpace || isNewline) && !i)
637             m_hasBeginWS = true;
638         if ((isSpace || isNewline) && i == len - 1)
639             m_hasEndWS = true;
640 
641         if (!ignoringSpaces && style()->collapseWhiteSpace() && previousCharacterIsSpace && isSpace)
642             ignoringSpaces = true;
643 
644         if (ignoringSpaces && !isSpace)
645             ignoringSpaces = false;
646 
647         // Ignore spaces and soft hyphens
648         if (ignoringSpaces) {
649             ASSERT(lastWordBoundary == i);
650             lastWordBoundary++;
651             continue;
652         } else if (c == softHyphen) {
653             currMaxWidth += widthFromCache(f, lastWordBoundary, i - lastWordBoundary, leadWidth + currMaxWidth, &fallbackFonts);
654             lastWordBoundary = i + 1;
655             continue;
656         }
657 
658         bool hasBreak = breakAll || isBreakable(txt, i, len, nextBreakable, breakNBSP);
659         bool betweenWords = true;
660         int j = i;
661         while (c != '\n' && !isSpaceAccordingToStyle(c, style()) && c != '\t' && c != softHyphen) {
662             j++;
663             if (j == len)
664                 break;
665             c = txt[j];
666             if (isBreakable(txt, j, len, nextBreakable, breakNBSP))
667                 break;
668             if (breakAll) {
669                 betweenWords = false;
670                 break;
671             }
672         }
673 
674         int wordLen = j - i;
675         if (wordLen) {
676             int w = widthFromCache(f, i, wordLen, leadWidth + currMaxWidth, &fallbackFonts);
677             currMinWidth += w;
678             if (betweenWords) {
679                 if (lastWordBoundary == i)
680                     currMaxWidth += w;
681                 else
682                     currMaxWidth += widthFromCache(f, lastWordBoundary, j - lastWordBoundary, leadWidth + currMaxWidth, &fallbackFonts);
683                 lastWordBoundary = j;
684             }
685 
686             bool isSpace = (j < len) && isSpaceAccordingToStyle(c, style());
687             bool isCollapsibleWhiteSpace = (j < len) && style()->isCollapsibleWhiteSpace(c);
688             if (j < len && style()->autoWrap())
689                 m_hasBreakableChar = true;
690 
691             // Add in wordSpacing to our currMaxWidth, but not if this is the last word on a line or the
692             // last word in the run.
693             if (wordSpacing && (isSpace || isCollapsibleWhiteSpace) && !containsOnlyWhitespace(j, len-j))
694                 currMaxWidth += wordSpacing;
695 
696             if (firstWord) {
697                 firstWord = false;
698                 // If the first character in the run is breakable, then we consider ourselves to have a beginning
699                 // minimum width of 0, since a break could occur right before our run starts, preventing us from ever
700                 // being appended to a previous text run when considering the total minimum width of the containing block.
701                 if (hasBreak)
702                     m_hasBreakableChar = true;
703                 m_beginMinWidth = hasBreak ? 0 : w;
704             }
705             m_endMinWidth = w;
706 
707             if (currMinWidth > m_minWidth)
708                 m_minWidth = currMinWidth;
709             currMinWidth = 0;
710 
711             i += wordLen - 1;
712         } else {
713             // Nowrap can never be broken, so don't bother setting the
714             // breakable character boolean. Pre can only be broken if we encounter a newline.
715             if (style()->autoWrap() || isNewline)
716                 m_hasBreakableChar = true;
717 
718             if (currMinWidth > m_minWidth)
719                 m_minWidth = currMinWidth;
720             currMinWidth = 0;
721 
722             if (isNewline) { // Only set if preserveNewline was true and we saw a newline.
723                 if (firstLine) {
724                     firstLine = false;
725                     leadWidth = 0;
726                     if (!style()->autoWrap())
727                         m_beginMinWidth = currMaxWidth;
728                 }
729 
730                 if (currMaxWidth > m_maxWidth)
731                     m_maxWidth = currMaxWidth;
732                 currMaxWidth = 0;
733             } else {
734                 currMaxWidth += f.width(TextRun(txt + i, 1, allowTabs(), leadWidth + currMaxWidth));
735                 needsWordSpacing = isSpace && !previousCharacterIsSpace && i == len - 1;
736             }
737             ASSERT(lastWordBoundary == i);
738             lastWordBoundary++;
739         }
740     }
741 
742     if ((needsWordSpacing && len > 1) || (ignoringSpaces && !firstWord))
743         currMaxWidth += wordSpacing;
744 
745     m_minWidth = max(currMinWidth, m_minWidth);
746     m_maxWidth = max(currMaxWidth, m_maxWidth);
747 
748     if (!style()->autoWrap())
749         m_minWidth = m_maxWidth;
750 
751     if (style()->whiteSpace() == PRE) {
752         if (firstLine)
753             m_beginMinWidth = m_maxWidth;
754         m_endMinWidth = currMaxWidth;
755     }
756 
757     setPrefWidthsDirty(false);
758 }
759 
containsOnlyWhitespace(unsigned from,unsigned len) const760 bool RenderText::containsOnlyWhitespace(unsigned from, unsigned len) const
761 {
762     unsigned currPos;
763     for (currPos = from;
764          currPos < from + len && ((*m_text)[currPos] == '\n' || (*m_text)[currPos] == ' ' || (*m_text)[currPos] == '\t');
765          currPos++) { }
766     return currPos >= (from + len);
767 }
768 
firstRunOrigin() const769 IntPoint RenderText::firstRunOrigin() const
770 {
771     return IntPoint(firstRunX(), firstRunY());
772 }
773 
firstRunX() const774 int RenderText::firstRunX() const
775 {
776     return m_firstTextBox ? m_firstTextBox->m_x : 0;
777 }
778 
firstRunY() const779 int RenderText::firstRunY() const
780 {
781     return m_firstTextBox ? m_firstTextBox->m_y : 0;
782 }
783 
setSelectionState(SelectionState state)784 void RenderText::setSelectionState(SelectionState state)
785 {
786     InlineTextBox* box;
787 
788     RenderObject::setSelectionState(state);
789     if (state == SelectionStart || state == SelectionEnd || state == SelectionBoth) {
790         int startPos, endPos;
791         selectionStartEnd(startPos, endPos);
792         if (selectionState() == SelectionStart) {
793             endPos = textLength();
794 
795             // to handle selection from end of text to end of line
796             if (startPos != 0 && startPos == endPos)
797                 startPos = endPos - 1;
798         } else if (selectionState() == SelectionEnd)
799             startPos = 0;
800 
801         for (box = firstTextBox(); box; box = box->nextTextBox()) {
802             if (box->isSelected(startPos, endPos)) {
803                 RootInlineBox* line = box->root();
804                 if (line)
805                     line->setHasSelectedChildren(true);
806             }
807         }
808     } else {
809         for (box = firstTextBox(); box; box = box->nextTextBox()) {
810             RootInlineBox* line = box->root();
811             if (line)
812                 line->setHasSelectedChildren(state == SelectionInside);
813         }
814     }
815 
816     containingBlock()->setSelectionState(state);
817 }
818 
setTextWithOffset(PassRefPtr<StringImpl> text,unsigned offset,unsigned len,bool force)819 void RenderText::setTextWithOffset(PassRefPtr<StringImpl> text, unsigned offset, unsigned len, bool force)
820 {
821     unsigned oldLen = textLength();
822     unsigned newLen = text->length();
823     int delta = newLen - oldLen;
824     unsigned end = len ? offset + len - 1 : offset;
825 
826     RootInlineBox* firstRootBox = 0;
827     RootInlineBox* lastRootBox = 0;
828 
829     bool dirtiedLines = false;
830 
831     // Dirty all text boxes that include characters in between offset and offset+len.
832     for (InlineTextBox* curr = firstTextBox(); curr; curr = curr->nextTextBox()) {
833         // Text run is entirely before the affected range.
834         if (curr->end() < offset)
835             continue;
836 
837         // Text run is entirely after the affected range.
838         if (curr->start() > end) {
839             curr->offsetRun(delta);
840             RootInlineBox* root = curr->root();
841             if (!firstRootBox) {
842                 firstRootBox = root;
843                 if (!dirtiedLines) {
844                     // The affected area was in between two runs. Go ahead and mark the root box of
845                     // the run after the affected area as dirty.
846                     firstRootBox->markDirty();
847                     dirtiedLines = true;
848                 }
849             }
850             lastRootBox = root;
851         } else if (curr->end() >= offset && curr->end() <= end) {
852             // Text run overlaps with the left end of the affected range.
853             curr->dirtyLineBoxes();
854             dirtiedLines = true;
855         } else if (curr->start() <= offset && curr->end() >= end) {
856             // Text run subsumes the affected range.
857             curr->dirtyLineBoxes();
858             dirtiedLines = true;
859         } else if (curr->start() <= end && curr->end() >= end) {
860             // Text run overlaps with right end of the affected range.
861             curr->dirtyLineBoxes();
862             dirtiedLines = true;
863         }
864     }
865 
866     // Now we have to walk all of the clean lines and adjust their cached line break information
867     // to reflect our updated offsets.
868     if (lastRootBox)
869         lastRootBox = lastRootBox->nextRootBox();
870     if (firstRootBox) {
871         RootInlineBox* prev = firstRootBox->prevRootBox();
872         if (prev)
873             firstRootBox = prev;
874     } else if (lastTextBox()) {
875         ASSERT(!lastRootBox);
876         firstRootBox = lastTextBox()->root();
877         firstRootBox->markDirty();
878         dirtiedLines = true;
879     }
880     for (RootInlineBox* curr = firstRootBox; curr && curr != lastRootBox; curr = curr->nextRootBox()) {
881         if (curr->lineBreakObj() == this && curr->lineBreakPos() > end)
882             curr->setLineBreakPos(curr->lineBreakPos() + delta);
883     }
884 
885     // If the text node is empty, dirty the line where new text will be inserted.
886     if (!firstTextBox() && parent()) {
887         parent()->dirtyLinesFromChangedChild(this);
888         dirtiedLines = true;
889     }
890 
891     m_linesDirty = dirtiedLines;
892     setText(text, force);
893 }
894 
isInlineFlowOrEmptyText(RenderObject * o)895 static inline bool isInlineFlowOrEmptyText(RenderObject* o)
896 {
897     if (o->isRenderInline())
898         return true;
899     if (!o->isText())
900         return false;
901     StringImpl* text = toRenderText(o)->text();
902     if (!text)
903         return true;
904     return !text->length();
905 }
906 
previousCharacter()907 UChar RenderText::previousCharacter()
908 {
909     // find previous text renderer if one exists
910     RenderObject* previousText = this;
911     while ((previousText = previousText->previousInPreOrder()))
912         if (!isInlineFlowOrEmptyText(previousText))
913             break;
914     UChar prev = ' ';
915     if (previousText && previousText->isText())
916         if (StringImpl* previousString = toRenderText(previousText)->text())
917             prev = (*previousString)[previousString->length() - 1];
918     return prev;
919 }
920 
setTextInternal(PassRefPtr<StringImpl> text)921 void RenderText::setTextInternal(PassRefPtr<StringImpl> text)
922 {
923     ASSERT(text);
924     m_text = document()->displayStringModifiedByEncoding(text);
925     ASSERT(m_text);
926 
927 #if ENABLE(SVG)
928     if (isSVGText()) {
929         if (style() && style()->whiteSpace() == PRE) {
930             // Spec: When xml:space="preserve", the SVG user agent will do the following using a
931             // copy of the original character data content. It will convert all newline and tab
932             // characters into space characters. Then, it will draw all space characters, including
933             // leading, trailing and multiple contiguous space characters.
934 
935             m_text = m_text->replace('\n', ' ');
936 
937             // If xml:space="preserve" is set, white-space is set to "pre", which
938             // preserves leading, trailing & contiguous space character for us.
939        } else {
940             // Spec: When xml:space="default", the SVG user agent will do the following using a
941             // copy of the original character data content. First, it will remove all newline
942             // characters. Then it will convert all tab characters into space characters.
943             // Then, it will strip off all leading and trailing space characters.
944             // Then, all contiguous space characters will be consolidated.
945 
946            m_text = m_text->replace('\n', StringImpl::empty());
947 
948            // If xml:space="default" is set, white-space is set to "nowrap", which handles
949            // leading, trailing & contiguous space character removal for us.
950         }
951 
952         m_text = m_text->replace('\t', ' ');
953     }
954 #endif
955 
956     if (style()) {
957         switch (style()->textTransform()) {
958             case TTNONE:
959                 break;
960             case CAPITALIZE: {
961                 m_text = m_text->capitalize(previousCharacter());
962                 break;
963             }
964             case UPPERCASE:
965                 m_text = m_text->upper();
966                 break;
967             case LOWERCASE:
968                 m_text = m_text->lower();
969                 break;
970         }
971 
972         // We use the same characters here as for list markers.
973         // See the listMarkerText function in RenderListMarker.cpp.
974         switch (style()->textSecurity()) {
975             case TSNONE:
976                 break;
977             case TSCIRCLE:
978                 m_text = m_text->secure(whiteBullet);
979                 break;
980             case TSDISC:
981                 m_text = m_text->secure(bullet);
982                 break;
983             case TSSQUARE:
984                 m_text = m_text->secure(blackSquare);
985         }
986     }
987 
988     ASSERT(m_text);
989     ASSERT(!isBR() || (textLength() == 1 && (*m_text)[0] == '\n'));
990 
991     m_isAllASCII = charactersAreAllASCII(m_text.get());
992 }
993 
setText(PassRefPtr<StringImpl> text,bool force)994 void RenderText::setText(PassRefPtr<StringImpl> text, bool force)
995 {
996     ASSERT(text);
997 
998     if (!force && equal(m_text.get(), text.get()))
999         return;
1000 
1001     setTextInternal(text);
1002     setNeedsLayoutAndPrefWidthsRecalc();
1003     m_knownNotToUseFallbackFonts = false;
1004 }
1005 
lineHeight(bool firstLine,bool) const1006 int RenderText::lineHeight(bool firstLine, bool) const
1007 {
1008     // Always use the interior line height of the parent (e.g., if our parent is an inline block).
1009     return parent()->lineHeight(firstLine, true);
1010 }
1011 
dirtyLineBoxes(bool fullLayout)1012 void RenderText::dirtyLineBoxes(bool fullLayout)
1013 {
1014     if (fullLayout)
1015         deleteTextBoxes();
1016     else if (!m_linesDirty) {
1017         for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
1018             box->dirtyLineBoxes();
1019     }
1020     m_linesDirty = false;
1021 }
1022 
createTextBox()1023 InlineTextBox* RenderText::createTextBox()
1024 {
1025     return new (renderArena()) InlineTextBox(this);
1026 }
1027 
createInlineTextBox()1028 InlineTextBox* RenderText::createInlineTextBox()
1029 {
1030     InlineTextBox* textBox = createTextBox();
1031     if (!m_firstTextBox)
1032         m_firstTextBox = m_lastTextBox = textBox;
1033     else {
1034         m_lastTextBox->setNextLineBox(textBox);
1035         textBox->setPreviousLineBox(m_lastTextBox);
1036         m_lastTextBox = textBox;
1037     }
1038     textBox->setIsText(true);
1039     return textBox;
1040 }
1041 
positionLineBox(InlineBox * box)1042 void RenderText::positionLineBox(InlineBox* box)
1043 {
1044     InlineTextBox* s = static_cast<InlineTextBox*>(box);
1045 
1046     // FIXME: should not be needed!!!
1047     if (!s->len()) {
1048         // We want the box to be destroyed.
1049         s->remove();
1050         s->destroy(renderArena());
1051         m_firstTextBox = m_lastTextBox = 0;
1052         return;
1053     }
1054 
1055     m_containsReversedText |= s->direction() == RTL;
1056 }
1057 
width(unsigned from,unsigned len,int xPos,bool firstLine,HashSet<const SimpleFontData * > * fallbackFonts) const1058 unsigned RenderText::width(unsigned from, unsigned len, int xPos, bool firstLine, HashSet<const SimpleFontData*>* fallbackFonts) const
1059 {
1060     if (from >= textLength())
1061         return 0;
1062 
1063     if (from + len > textLength())
1064         len = textLength() - from;
1065 
1066     return width(from, len, style(firstLine)->font(), xPos, fallbackFonts);
1067 }
1068 
width(unsigned from,unsigned len,const Font & f,int xPos,HashSet<const SimpleFontData * > * fallbackFonts) const1069 unsigned RenderText::width(unsigned from, unsigned len, const Font& f, int xPos, HashSet<const SimpleFontData*>* fallbackFonts) const
1070 {
1071     ASSERT(from + len <= textLength());
1072     if (!characters())
1073         return 0;
1074 
1075     int w;
1076     if (&f == &style()->font()) {
1077         if (!style()->preserveNewline() && !from && len == textLength()) {
1078             if (fallbackFonts) {
1079                 if (prefWidthsDirty() || !m_knownNotToUseFallbackFonts) {
1080                     const_cast<RenderText*>(this)->calcPrefWidths(0, *fallbackFonts);
1081                     if (fallbackFonts->isEmpty())
1082                         m_knownNotToUseFallbackFonts = true;
1083                 }
1084                 w = m_maxWidth;
1085             } else
1086                 w = maxPrefWidth();
1087         } else
1088             w = widthFromCache(f, from, len, xPos, fallbackFonts);
1089     } else
1090         w = f.width(TextRun(text()->characters() + from, len, allowTabs(), xPos), fallbackFonts);
1091 
1092     return w;
1093 }
1094 
linesBoundingBox() const1095 IntRect RenderText::linesBoundingBox() const
1096 {
1097     IntRect result;
1098 
1099     ASSERT(!firstTextBox() == !lastTextBox());  // Either both are null or both exist.
1100     if (firstTextBox() && lastTextBox()) {
1101         // Return the width of the minimal left side and the maximal right side.
1102         int leftSide = 0;
1103         int rightSide = 0;
1104         for (InlineTextBox* curr = firstTextBox(); curr; curr = curr->nextTextBox()) {
1105             if (curr == firstTextBox() || curr->x() < leftSide)
1106                 leftSide = curr->x();
1107             if (curr == firstTextBox() || curr->x() + curr->width() > rightSide)
1108                 rightSide = curr->x() + curr->width();
1109         }
1110         result.setWidth(rightSide - leftSide);
1111         result.setX(leftSide);
1112         result.setHeight(lastTextBox()->y() + lastTextBox()->height() - firstTextBox()->y());
1113         result.setY(firstTextBox()->y());
1114     }
1115 
1116     return result;
1117 }
1118 
clippedOverflowRectForRepaint(RenderBoxModelObject * repaintContainer)1119 IntRect RenderText::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer)
1120 {
1121     RenderObject* cb = containingBlock();
1122     return cb->clippedOverflowRectForRepaint(repaintContainer);
1123 }
1124 
selectionRectForRepaint(RenderBoxModelObject * repaintContainer,bool clipToVisibleContent)1125 IntRect RenderText::selectionRectForRepaint(RenderBoxModelObject* repaintContainer, bool clipToVisibleContent)
1126 {
1127     ASSERT(!needsLayout());
1128 
1129     if (selectionState() == SelectionNone)
1130         return IntRect();
1131     RenderBlock* cb =  containingBlock();
1132     if (!cb)
1133         return IntRect();
1134 
1135     // Now calculate startPos and endPos for painting selection.
1136     // We include a selection while endPos > 0
1137     int startPos, endPos;
1138     if (selectionState() == SelectionInside) {
1139         // We are fully selected.
1140         startPos = 0;
1141         endPos = textLength();
1142     } else {
1143         selectionStartEnd(startPos, endPos);
1144         if (selectionState() == SelectionStart)
1145             endPos = textLength();
1146         else if (selectionState() == SelectionEnd)
1147             startPos = 0;
1148     }
1149 
1150     if (startPos == endPos)
1151         return IntRect();
1152 
1153     IntRect rect;
1154     for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
1155         rect.unite(box->selectionRect(0, 0, startPos, endPos));
1156 
1157     if (clipToVisibleContent)
1158         computeRectForRepaint(repaintContainer, rect);
1159     else {
1160         if (cb->hasColumns())
1161             cb->adjustRectForColumns(rect);
1162 
1163         rect = localToContainerQuad(FloatRect(rect), repaintContainer).enclosingBoundingBox();
1164     }
1165 
1166     return rect;
1167 }
1168 
caretMinOffset() const1169 int RenderText::caretMinOffset() const
1170 {
1171     InlineTextBox* box = firstTextBox();
1172     if (!box)
1173         return 0;
1174     int minOffset = box->start();
1175     for (box = box->nextTextBox(); box; box = box->nextTextBox())
1176         minOffset = min<int>(minOffset, box->start());
1177     return minOffset;
1178 }
1179 
caretMaxOffset() const1180 int RenderText::caretMaxOffset() const
1181 {
1182     InlineTextBox* box = lastTextBox();
1183     if (!box)
1184         return textLength();
1185     int maxOffset = box->start() + box->len();
1186     for (box = box->prevTextBox(); box; box = box->prevTextBox())
1187         maxOffset = max<int>(maxOffset, box->start() + box->len());
1188     return maxOffset;
1189 }
1190 
caretMaxRenderedOffset() const1191 unsigned RenderText::caretMaxRenderedOffset() const
1192 {
1193     int l = 0;
1194     for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
1195         l += box->len();
1196     return l;
1197 }
1198 
previousOffset(int current) const1199 int RenderText::previousOffset(int current) const
1200 {
1201     StringImpl* si = m_text.get();
1202     TextBreakIterator* iterator = cursorMovementIterator(si->characters(), si->length());
1203     if (!iterator)
1204         return current - 1;
1205 
1206     long result = textBreakPreceding(iterator, current);
1207     if (result == TextBreakDone)
1208         result = current - 1;
1209 
1210 #ifdef BUILDING_ON_TIGER
1211     // ICU 3.2 allows character breaks before a half-width Katakana voiced mark.
1212     if (static_cast<unsigned>(result) < si->length()) {
1213         UChar character = (*si)[result];
1214         if (character == 0xFF9E || character == 0xFF9F)
1215             --result;
1216     }
1217 #endif
1218 
1219     return result;
1220 }
1221 
1222 #define HANGUL_CHOSEONG_START (0x1100)
1223 #define HANGUL_CHOSEONG_END (0x115F)
1224 #define HANGUL_JUNGSEONG_START (0x1160)
1225 #define HANGUL_JUNGSEONG_END (0x11A2)
1226 #define HANGUL_JONGSEONG_START (0x11A8)
1227 #define HANGUL_JONGSEONG_END (0x11F9)
1228 #define HANGUL_SYLLABLE_START (0xAC00)
1229 #define HANGUL_SYLLABLE_END (0xD7AF)
1230 #define HANGUL_JONGSEONG_COUNT (28)
1231 
1232 enum HangulState {
1233     HangulStateL,
1234     HangulStateV,
1235     HangulStateT,
1236     HangulStateLV,
1237     HangulStateLVT,
1238     HangulStateBreak
1239 };
1240 
isHangulLVT(UChar32 character)1241 inline bool isHangulLVT(UChar32 character)
1242 {
1243     return (character - HANGUL_SYLLABLE_START) % HANGUL_JONGSEONG_COUNT;
1244 }
1245 
previousOffsetForBackwardDeletion(int current) const1246 int RenderText::previousOffsetForBackwardDeletion(int current) const
1247 {
1248 #if PLATFORM(MAC)
1249     UChar32 character;
1250     while (current > 0) {
1251         if (U16_IS_TRAIL((*m_text)[--current]))
1252             --current;
1253         if (current < 0)
1254             break;
1255 
1256         UChar32 character = m_text->characterStartingAt(current);
1257 
1258         // We don't combine characters in Armenian ... Limbu range for backward deletion.
1259         if ((character >= 0x0530) && (character < 0x1950))
1260             break;
1261 
1262         if (u_isbase(character) && (character != 0xFF9E) && (character != 0xFF9F))
1263             break;
1264     }
1265 
1266     if (current <= 0)
1267         return current;
1268 
1269     // Hangul
1270     character = m_text->characterStartingAt(current);
1271     if (((character >= HANGUL_CHOSEONG_START) && (character <= HANGUL_JONGSEONG_END)) || ((character >= HANGUL_SYLLABLE_START) && (character <= HANGUL_SYLLABLE_END))) {
1272         HangulState state;
1273         HangulState initialState;
1274 
1275         if (character < HANGUL_JUNGSEONG_START)
1276             state = HangulStateL;
1277         else if (character < HANGUL_JONGSEONG_START)
1278             state = HangulStateV;
1279         else if (character < HANGUL_SYLLABLE_START)
1280             state = HangulStateT;
1281         else
1282             state = isHangulLVT(character) ? HangulStateLVT : HangulStateLV;
1283 
1284         initialState = state;
1285 
1286         while (current > 0 && ((character = m_text->characterStartingAt(current - 1)) >= HANGUL_CHOSEONG_START) && (character <= HANGUL_SYLLABLE_END) && ((character <= HANGUL_JONGSEONG_END) || (character >= HANGUL_SYLLABLE_START))) {
1287             switch (state) {
1288             case HangulStateV:
1289                 if (character <= HANGUL_CHOSEONG_END)
1290                     state = HangulStateL;
1291                 else if ((character >= HANGUL_SYLLABLE_START) && (character <= HANGUL_SYLLABLE_END) && !isHangulLVT(character))
1292                     state = HangulStateLV;
1293                 else if (character > HANGUL_JUNGSEONG_END)
1294                     state = HangulStateBreak;
1295                 break;
1296             case HangulStateT:
1297                 if ((character >= HANGUL_JUNGSEONG_START) && (character <= HANGUL_JUNGSEONG_END))
1298                     state = HangulStateV;
1299                 else if ((character >= HANGUL_SYLLABLE_START) && (character <= HANGUL_SYLLABLE_END))
1300                     state = (isHangulLVT(character) ? HangulStateLVT : HangulStateLV);
1301                 else if (character < HANGUL_JUNGSEONG_START)
1302                     state = HangulStateBreak;
1303                 break;
1304             default:
1305                 state = (character < HANGUL_JUNGSEONG_START) ? HangulStateL : HangulStateBreak;
1306                 break;
1307             }
1308             if (state == HangulStateBreak)
1309                 break;
1310 
1311             --current;
1312         }
1313     }
1314 
1315     return current;
1316 #else
1317     // Platforms other than Mac delete by one code point.
1318     return current - 1;
1319 #endif
1320 }
1321 
nextOffset(int current) const1322 int RenderText::nextOffset(int current) const
1323 {
1324     StringImpl* si = m_text.get();
1325     TextBreakIterator* iterator = cursorMovementIterator(si->characters(), si->length());
1326     if (!iterator)
1327         return current + 1;
1328 
1329     long result = textBreakFollowing(iterator, current);
1330     if (result == TextBreakDone)
1331         result = current + 1;
1332 
1333 #ifdef BUILDING_ON_TIGER
1334     // ICU 3.2 allows character breaks before a half-width Katakana voiced mark.
1335     if (static_cast<unsigned>(result) < si->length()) {
1336         UChar character = (*si)[result];
1337         if (character == 0xFF9E || character == 0xFF9F)
1338             ++result;
1339     }
1340 #endif
1341 
1342     return result;
1343 }
1344 
1345 #ifndef NDEBUG
1346 
checkConsistency() const1347 void RenderText::checkConsistency() const
1348 {
1349 #ifdef CHECK_CONSISTENCY
1350     const InlineTextBox* prev = 0;
1351     for (const InlineTextBox* child = m_firstTextBox; child != 0; child = child->nextTextBox()) {
1352         ASSERT(child->object() == this);
1353         ASSERT(child->prevTextBox() == prev);
1354         prev = child;
1355     }
1356     ASSERT(prev == m_lastTextBox);
1357 #endif
1358 }
1359 
1360 #endif
1361 
1362 } // namespace WebCore
1363