• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * This file is part of the DOM implementation for KDE.
3  *
4  * Copyright (C) 2007 Rob Buis <buis@kde.org>
5  *           (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public License
18  * along with this library; see the file COPYING.LIB.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  *
22  */
23 
24 #include "config.h"
25 
26 #if ENABLE(SVG)
27 #include "SVGInlineTextBox.h"
28 
29 #include "Document.h"
30 #include "Editor.h"
31 #include "Frame.h"
32 #include "GraphicsContext.h"
33 #include "InlineFlowBox.h"
34 #include "Range.h"
35 #include "SVGPaintServer.h"
36 #include "SVGRootInlineBox.h"
37 #include "Text.h"
38 
39 #include <float.h>
40 
41 namespace WebCore {
42 
SVGInlineTextBox(RenderObject * obj)43 SVGInlineTextBox::SVGInlineTextBox(RenderObject* obj)
44     : InlineTextBox(obj)
45     , m_height(0)
46 {
47 }
48 
selectionTop()49 int SVGInlineTextBox::selectionTop()
50 {
51     return m_y;
52 }
53 
selectionHeight()54 int SVGInlineTextBox::selectionHeight()
55 {
56     return m_height;
57 }
58 
svgRootInlineBox() const59 SVGRootInlineBox* SVGInlineTextBox::svgRootInlineBox() const
60 {
61     // Find associated root inline box
62     InlineFlowBox* parentBox = parent();
63 
64     while (parentBox && !parentBox->isRootInlineBox())
65         parentBox = parentBox->parent();
66 
67     ASSERT(parentBox);
68     ASSERT(parentBox->isRootInlineBox());
69 
70     if (!parentBox->isSVGRootInlineBox())
71         return 0;
72 
73     return static_cast<SVGRootInlineBox*>(parentBox);
74 }
75 
calculateGlyphWidth(RenderStyle * style,int offset,int extraCharsAvailable,int & charsConsumed,String & glyphName) const76 float SVGInlineTextBox::calculateGlyphWidth(RenderStyle* style, int offset, int extraCharsAvailable, int& charsConsumed, String& glyphName) const
77 {
78     ASSERT(style);
79     return style->font().floatWidth(svgTextRunForInlineTextBox(textRenderer()->text()->characters() + offset, 1, style, this, 0), extraCharsAvailable, charsConsumed, glyphName);
80 }
81 
calculateGlyphHeight(RenderStyle * style,int,int) const82 float SVGInlineTextBox::calculateGlyphHeight(RenderStyle* style, int, int) const
83 {
84     // This is just a guess, and the only purpose of this function is to centralize this hack.
85     // In real-life top-top-bottom scripts this won't be enough, I fear.
86     return style->font().ascent() + style->font().descent();
87 }
88 
calculateGlyphBoundaries(RenderStyle * style,int offset,const SVGChar & svgChar) const89 FloatRect SVGInlineTextBox::calculateGlyphBoundaries(RenderStyle* style, int offset, const SVGChar& svgChar) const
90 {
91     const Font& font = style->font();
92 
93     // Take RTL text into account and pick right glyph width/height.
94     float glyphWidth = 0.0f;
95 
96     // FIXME: account for multi-character glyphs
97     int charsConsumed;
98     String glyphName;
99     if (direction() == LTR)
100         glyphWidth = calculateGlyphWidth(style, offset, 0, charsConsumed, glyphName);
101     else
102         glyphWidth = calculateGlyphWidth(style, start() + end() - offset, 0, charsConsumed, glyphName);
103 
104     float x1 = svgChar.x;
105     float x2 = svgChar.x + glyphWidth;
106 
107     float y1 = svgChar.y - font.ascent();
108     float y2 = svgChar.y + font.descent();
109 
110     FloatRect glyphRect(x1, y1, x2 - x1, y2 - y1);
111 
112     // Take per-character transformations into account
113     TransformationMatrix ctm = svgChar.characterTransform();
114     if (!ctm.isIdentity())
115         glyphRect = ctm.mapRect(glyphRect);
116 
117     return glyphRect;
118 }
119 
120 // Helper class for closestCharacterToPosition()
121 struct SVGInlineTextBoxClosestCharacterToPositionWalker {
SVGInlineTextBoxClosestCharacterToPositionWalkerWebCore::SVGInlineTextBoxClosestCharacterToPositionWalker122     SVGInlineTextBoxClosestCharacterToPositionWalker(int x, int y)
123         : m_character(0)
124         , m_distance(FLT_MAX)
125         , m_x(x)
126         , m_y(y)
127         , m_offsetOfHitCharacter(0)
128     {
129     }
130 
chunkPortionCallbackWebCore::SVGInlineTextBoxClosestCharacterToPositionWalker131     void chunkPortionCallback(SVGInlineTextBox* textBox, int startOffset, const TransformationMatrix& chunkCtm,
132                               const Vector<SVGChar>::iterator& start, const Vector<SVGChar>::iterator& end)
133     {
134         RenderStyle* style = textBox->textRenderer()->style();
135 
136         Vector<SVGChar>::iterator closestCharacter = 0;
137         unsigned int closestOffset = UINT_MAX;
138 
139         for (Vector<SVGChar>::iterator it = start; it != end; ++it) {
140             if (it->isHidden())
141                 continue;
142 
143             unsigned int newOffset = textBox->start() + (it - start) + startOffset;
144             FloatRect glyphRect = chunkCtm.mapRect(textBox->calculateGlyphBoundaries(style, newOffset, *it));
145 
146             // Take RTL text into account and pick right glyph width/height.
147             // NOTE: This offset has to be corrected _after_ calling calculateGlyphBoundaries
148             if (textBox->direction() == RTL)
149                 newOffset = textBox->start() + textBox->end() - newOffset;
150 
151             // Calculate distances relative to the glyph mid-point. I hope this is accurate enough.
152             float xDistance = glyphRect.x() + glyphRect.width() / 2.0f - m_x;
153             float yDistance = glyphRect.y() - glyphRect.height() / 2.0f - m_y;
154 
155             float newDistance = sqrtf(xDistance * xDistance + yDistance * yDistance);
156             if (newDistance <= m_distance) {
157                 m_distance = newDistance;
158                 closestOffset = newOffset;
159                 closestCharacter = it;
160             }
161         }
162 
163         if (closestOffset != UINT_MAX) {
164             // Record current chunk, if it contains the current closest character next to the mouse.
165             m_character = closestCharacter;
166             m_offsetOfHitCharacter = closestOffset;
167         }
168     }
169 
characterWebCore::SVGInlineTextBoxClosestCharacterToPositionWalker170     SVGChar* character() const
171     {
172         return m_character;
173     }
174 
offsetOfHitCharacterWebCore::SVGInlineTextBoxClosestCharacterToPositionWalker175     int offsetOfHitCharacter() const
176     {
177         if (!m_character)
178             return 0;
179 
180         return m_offsetOfHitCharacter;
181     }
182 
183 private:
184     Vector<SVGChar>::iterator m_character;
185     float m_distance;
186 
187     int m_x;
188     int m_y;
189     int m_offsetOfHitCharacter;
190 };
191 
192 // Helper class for selectionRect()
193 struct SVGInlineTextBoxSelectionRectWalker {
SVGInlineTextBoxSelectionRectWalkerWebCore::SVGInlineTextBoxSelectionRectWalker194     SVGInlineTextBoxSelectionRectWalker()
195     {
196     }
197 
chunkPortionCallbackWebCore::SVGInlineTextBoxSelectionRectWalker198     void chunkPortionCallback(SVGInlineTextBox* textBox, int startOffset, const TransformationMatrix& chunkCtm,
199                               const Vector<SVGChar>::iterator& start, const Vector<SVGChar>::iterator& end)
200     {
201         RenderStyle* style = textBox->textRenderer()->style();
202 
203         for (Vector<SVGChar>::iterator it = start; it != end; ++it) {
204             if (it->isHidden())
205                 continue;
206 
207             unsigned int newOffset = textBox->start() + (it - start) + startOffset;
208             m_selectionRect.unite(textBox->calculateGlyphBoundaries(style, newOffset, *it));
209         }
210 
211         m_selectionRect = chunkCtm.mapRect(m_selectionRect);
212     }
213 
selectionRectWebCore::SVGInlineTextBoxSelectionRectWalker214     FloatRect selectionRect() const
215     {
216         return m_selectionRect;
217     }
218 
219 private:
220     FloatRect m_selectionRect;
221 };
222 
closestCharacterToPosition(int x,int y,int & offsetOfHitCharacter) const223 SVGChar* SVGInlineTextBox::closestCharacterToPosition(int x, int y, int& offsetOfHitCharacter) const
224 {
225     SVGRootInlineBox* rootBox = svgRootInlineBox();
226     if (!rootBox)
227         return 0;
228 
229     SVGInlineTextBoxClosestCharacterToPositionWalker walkerCallback(x, y);
230     SVGTextChunkWalker<SVGInlineTextBoxClosestCharacterToPositionWalker> walker(&walkerCallback, &SVGInlineTextBoxClosestCharacterToPositionWalker::chunkPortionCallback);
231 
232     rootBox->walkTextChunks(&walker, this);
233 
234     offsetOfHitCharacter = walkerCallback.offsetOfHitCharacter();
235     return walkerCallback.character();
236 }
237 
svgCharacterHitsPosition(int x,int y,int & closestOffsetInBox) const238 bool SVGInlineTextBox::svgCharacterHitsPosition(int x, int y, int& closestOffsetInBox) const
239 {
240     int offsetOfHitCharacter = 0;
241     SVGChar* charAtPosPtr = closestCharacterToPosition(x, y, offsetOfHitCharacter);
242     if (!charAtPosPtr)
243         return false;
244 
245     SVGChar& charAtPos = *charAtPosPtr;
246     RenderStyle* style = textRenderer()->style(m_firstLine);
247     FloatRect glyphRect = calculateGlyphBoundaries(style, offsetOfHitCharacter, charAtPos);
248 
249     // FIXME: Why?
250     if (direction() == RTL)
251         offsetOfHitCharacter++;
252 
253     // The caller actually the closest offset before/after the hit char
254     // closestCharacterToPosition returns us offsetOfHitCharacter.
255     closestOffsetInBox = offsetOfHitCharacter;
256 
257     // FIXME: (bug 13910) This code does not handle bottom-to-top/top-to-bottom vertical text.
258 
259     // Check whether y position hits the current character
260     if (y < charAtPos.y - glyphRect.height() || y > charAtPos.y)
261         return false;
262 
263     // Check whether x position hits the current character
264     if (x < charAtPos.x) {
265         if (closestOffsetInBox > 0 && direction() == LTR)
266             return true;
267         else if (closestOffsetInBox < (int) end() && direction() == RTL)
268             return true;
269 
270         return false;
271     }
272 
273     // Adjust the closest offset to after the char if x was after the char midpoint
274     if (x >= charAtPos.x + glyphRect.width() / 2.0)
275         closestOffsetInBox += direction() == RTL ? -1 : 1;
276 
277     // If we are past the last glyph of this box, don't mark it as 'hit'
278     if (x >= charAtPos.x + glyphRect.width() && closestOffsetInBox == (int) end())
279         return false;
280 
281     return true;
282 }
283 
offsetForPosition(int,bool) const284 int SVGInlineTextBox::offsetForPosition(int, bool) const
285 {
286     // SVG doesn't use the offset <-> position selection system.
287     ASSERT_NOT_REACHED();
288     return 0;
289 }
290 
positionForOffset(int) const291 int SVGInlineTextBox::positionForOffset(int) const
292 {
293     // SVG doesn't use the offset <-> position selection system.
294     ASSERT_NOT_REACHED();
295     return 0;
296 }
297 
nodeAtPoint(const HitTestRequest &,HitTestResult & result,int x,int y,int tx,int ty)298 bool SVGInlineTextBox::nodeAtPoint(const HitTestRequest&, HitTestResult& result, int x, int y, int tx, int ty)
299 {
300     ASSERT(!isLineBreak());
301 
302     IntRect rect = selectionRect(0, 0, 0, len());
303     if (renderer()->style()->visibility() == VISIBLE && rect.contains(x, y)) {
304         renderer()->updateHitTestResult(result, IntPoint(x - tx, y - ty));
305         return true;
306     }
307 
308     return false;
309 }
310 
selectionRect(int,int,int startPos,int endPos)311 IntRect SVGInlineTextBox::selectionRect(int, int, int startPos, int endPos)
312 {
313     if (startPos >= endPos)
314         return IntRect();
315 
316     // TODO: Actually respect startPos/endPos - we're returning the _full_ selectionRect
317     // here. This won't lead to visible bugs, but to extra work being done. Investigate.
318     SVGRootInlineBox* rootBox = svgRootInlineBox();
319     if (!rootBox)
320         return IntRect();
321 
322     SVGInlineTextBoxSelectionRectWalker walkerCallback;
323     SVGTextChunkWalker<SVGInlineTextBoxSelectionRectWalker> walker(&walkerCallback, &SVGInlineTextBoxSelectionRectWalker::chunkPortionCallback);
324 
325     rootBox->walkTextChunks(&walker, this);
326     return enclosingIntRect(walkerCallback.selectionRect());
327 }
328 
paintCharacters(RenderObject::PaintInfo & paintInfo,int tx,int ty,const SVGChar & svgChar,const UChar * chars,int length,SVGPaintServer * activePaintServer)329 void SVGInlineTextBox::paintCharacters(RenderObject::PaintInfo& paintInfo, int tx, int ty, const SVGChar& svgChar, const UChar* chars, int length, SVGPaintServer* activePaintServer)
330 {
331     if (renderer()->style()->visibility() != VISIBLE || paintInfo.phase == PaintPhaseOutline)
332         return;
333 
334     ASSERT(paintInfo.phase != PaintPhaseSelfOutline && paintInfo.phase != PaintPhaseChildOutlines);
335 
336     RenderText* text = textRenderer();
337     ASSERT(text);
338 
339     bool isPrinting = text->document()->printing();
340 
341     // Determine whether or not we're selected.
342     bool haveSelection = !isPrinting && selectionState() != RenderObject::SelectionNone;
343     if (!haveSelection && paintInfo.phase == PaintPhaseSelection)
344         // When only painting the selection, don't bother to paint if there is none.
345         return;
346 
347     // Determine whether or not we have a composition.
348     bool containsComposition = text->document()->frame()->editor()->compositionNode() == text->node();
349     bool useCustomUnderlines = containsComposition && text->document()->frame()->editor()->compositionUsesCustomUnderlines();
350 
351     // Set our font
352     RenderStyle* styleToUse = text->style(isFirstLineStyle());
353     const Font& font = styleToUse->font();
354 
355     TransformationMatrix ctm = svgChar.characterTransform();
356     if (!ctm.isIdentity())
357         paintInfo.context->concatCTM(ctm);
358 
359     // 1. Paint backgrounds behind text if needed.  Examples of such backgrounds include selection
360     // and marked text.
361     if (paintInfo.phase != PaintPhaseSelection && !isPrinting) {
362 #if PLATFORM(MAC)
363         // Custom highlighters go behind everything else.
364         if (styleToUse->highlight() != nullAtom && !paintInfo.context->paintingDisabled())
365             paintCustomHighlight(tx, ty, styleToUse->highlight());
366 #endif
367 
368         if (containsComposition && !useCustomUnderlines)
369             paintCompositionBackground(paintInfo.context, tx, ty, styleToUse, font,
370                                        text->document()->frame()->editor()->compositionStart(),
371                                        text->document()->frame()->editor()->compositionEnd());
372 
373         paintDocumentMarkers(paintInfo.context, tx, ty, styleToUse, font, true);
374 
375         if (haveSelection && !useCustomUnderlines) {
376             int boxStartOffset = chars - text->characters() - start();
377             paintSelection(boxStartOffset, svgChar, chars, length, paintInfo.context, styleToUse, font);
378         }
379     }
380 
381     // Set a text shadow if we have one.
382     // FIXME: Support multiple shadow effects.  Need more from the CG API before
383     // we can do this.
384     bool setShadow = false;
385     if (styleToUse->textShadow()) {
386         paintInfo.context->setShadow(IntSize(styleToUse->textShadow()->x, styleToUse->textShadow()->y),
387                                      styleToUse->textShadow()->blur, styleToUse->textShadow()->color);
388         setShadow = true;
389     }
390 
391     IntPoint origin((int) svgChar.x, (int) svgChar.y);
392     TextRun run = svgTextRunForInlineTextBox(chars, length, styleToUse, this, svgChar.x);
393 
394 #if ENABLE(SVG_FONTS)
395     // SVG Fonts need access to the paint server used to draw the current text chunk.
396     // They need to be able to call renderPath() on a SVGPaintServer object.
397     run.setActivePaintServer(activePaintServer);
398 #endif
399 
400     paintInfo.context->drawText(font, run, origin);
401 
402     if (paintInfo.phase != PaintPhaseSelection) {
403         paintDocumentMarkers(paintInfo.context, tx, ty, styleToUse, font, false);
404 
405         if (useCustomUnderlines) {
406             const Vector<CompositionUnderline>& underlines = text->document()->frame()->editor()->customCompositionUnderlines();
407             size_t numUnderlines = underlines.size();
408 
409             for (size_t index = 0; index < numUnderlines; ++index) {
410                 const CompositionUnderline& underline = underlines[index];
411 
412                 if (underline.endOffset <= start())
413                     // underline is completely before this run.  This might be an underline that sits
414                     // before the first run we draw, or underlines that were within runs we skipped
415                     // due to truncation.
416                     continue;
417 
418                 if (underline.startOffset <= end()) {
419                     // underline intersects this run.  Paint it.
420                     paintCompositionUnderline(paintInfo.context, tx, ty, underline);
421                     if (underline.endOffset > end() + 1)
422                         // underline also runs into the next run. Bail now, no more marker advancement.
423                         break;
424                 } else
425                     // underline is completely after this run, bail.  A later run will paint it.
426                     break;
427             }
428         }
429 
430     }
431 
432     if (setShadow)
433         paintInfo.context->clearShadow();
434 
435     if (!ctm.isIdentity())
436         paintInfo.context->concatCTM(ctm.inverse());
437 }
438 
paintSelection(int boxStartOffset,const SVGChar & svgChar,const UChar *,int length,GraphicsContext * p,RenderStyle * style,const Font & font)439 void SVGInlineTextBox::paintSelection(int boxStartOffset, const SVGChar& svgChar, const UChar*, int length, GraphicsContext* p, RenderStyle* style, const Font& font)
440 {
441     if (selectionState() == RenderObject::SelectionNone)
442         return;
443 
444     int startPos, endPos;
445     selectionStartEnd(startPos, endPos);
446 
447     if (startPos >= endPos)
448         return;
449 
450     Color textColor = style->color();
451     Color color = renderer()->selectionBackgroundColor();
452     if (!color.isValid() || color.alpha() == 0)
453         return;
454 
455     // If the text color ends up being the same as the selection background, invert the selection
456     // background.  This should basically never happen, since the selection has transparency.
457     if (textColor == color)
458         color = Color(0xff - color.red(), 0xff - color.green(), 0xff - color.blue());
459 
460     // Map from text box positions and a given start offset to chunk positions
461     // 'boxStartOffset' represents the beginning of the text chunk.
462     if ((startPos > boxStartOffset && endPos > boxStartOffset + length) || boxStartOffset >= endPos)
463         return;
464 
465     if (endPos > boxStartOffset + length)
466         endPos = boxStartOffset + length;
467 
468     if (startPos < boxStartOffset)
469         startPos = boxStartOffset;
470 
471     ASSERT(startPos >= boxStartOffset);
472     ASSERT(endPos <= boxStartOffset + length);
473     ASSERT(startPos < endPos);
474 
475     p->save();
476 
477     int adjust = startPos >= boxStartOffset ? boxStartOffset : 0;
478     p->drawHighlightForText(font, svgTextRunForInlineTextBox(textRenderer()->text()->characters() + start() + boxStartOffset, length, style, this, svgChar.x),
479                             IntPoint((int) svgChar.x, (int) svgChar.y - font.ascent()),
480                             font.ascent() + font.descent(), color, startPos - adjust, endPos - adjust);
481 
482     p->restore();
483 }
484 
pathForDecoration(ETextDecoration decoration,RenderObject * object,float x,float y,float width)485 static inline Path pathForDecoration(ETextDecoration decoration, RenderObject* object, float x, float y, float width)
486 {
487     float thickness = SVGRenderStyle::cssPrimitiveToLength(object, object->style()->svgStyle()->strokeWidth(), 1.0f);
488 
489     const Font& font = object->style()->font();
490     thickness = max(thickness * powf(font.size(), 2.0f) / font.unitsPerEm(), 1.0f);
491 
492     if (decoration == UNDERLINE)
493         y += thickness * 1.5f; // For compatibility with Batik/Opera
494     else if (decoration == OVERLINE)
495         y += thickness;
496 
497     float halfThickness = thickness / 2.0f;
498     return Path::createRectangle(FloatRect(x + halfThickness, y, width - 2.0f * halfThickness, thickness));
499 }
500 
paintDecoration(ETextDecoration decoration,GraphicsContext * context,int tx,int ty,int width,const SVGChar & svgChar,const SVGTextDecorationInfo & info)501 void SVGInlineTextBox::paintDecoration(ETextDecoration decoration, GraphicsContext* context, int tx, int ty, int width, const SVGChar& svgChar, const SVGTextDecorationInfo& info)
502 {
503     if (renderer()->style()->visibility() != VISIBLE)
504         return;
505 
506     // This function does NOT accept combinated text decorations. It's meant to be invoked for just one.
507     ASSERT(decoration == TDNONE || decoration == UNDERLINE || decoration == OVERLINE || decoration == LINE_THROUGH || decoration == BLINK);
508 
509     bool isFilled = info.fillServerMap.contains(decoration);
510     bool isStroked = info.strokeServerMap.contains(decoration);
511 
512     if (!isFilled && !isStroked)
513         return;
514 
515     int baseline = renderer()->style(m_firstLine)->font().ascent();
516     if (decoration == UNDERLINE)
517         ty += baseline;
518     else if (decoration == LINE_THROUGH)
519         ty += 2 * baseline / 3;
520 
521     context->save();
522     context->beginPath();
523 
524     TransformationMatrix ctm = svgChar.characterTransform();
525     if (!ctm.isIdentity())
526         context->concatCTM(ctm);
527 
528     if (isFilled) {
529         if (RenderObject* fillObject = info.fillServerMap.get(decoration)) {
530             if (SVGPaintServer* fillPaintServer = SVGPaintServer::fillPaintServer(fillObject->style(), fillObject)) {
531                 context->addPath(pathForDecoration(decoration, fillObject, tx, ty, width));
532                 fillPaintServer->draw(context, fillObject, ApplyToFillTargetType);
533             }
534         }
535     }
536 
537     if (isStroked) {
538         if (RenderObject* strokeObject = info.strokeServerMap.get(decoration)) {
539             if (SVGPaintServer* strokePaintServer = SVGPaintServer::strokePaintServer(strokeObject->style(), strokeObject)) {
540                 context->addPath(pathForDecoration(decoration, strokeObject, tx, ty, width));
541                 strokePaintServer->draw(context, strokeObject, ApplyToStrokeTargetType);
542             }
543         }
544     }
545 
546     context->restore();
547 }
548 
549 } // namespace WebCore
550 
551 #endif
552