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