1/*
2 * Copyright (C) 2009 Alex Milowski (alex@milowski.com). All rights reserved.
3 * Copyright (C) 2012 David Barton (dbarton@mathscribe.com). All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
18 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
20 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include "config.h"
28
29#if ENABLE(MATHML)
30
31#include "RenderMathMLBlock.h"
32
33#include "GraphicsContext.h"
34#include "MathMLNames.h"
35#include "RenderView.h"
36#include <wtf/text/StringBuilder.h>
37
38#if ENABLE(DEBUG_MATH_LAYOUT)
39#include "PaintInfo.h"
40#endif
41
42namespace WebCore {
43
44using namespace MathMLNames;
45
46RenderMathMLBlock::RenderMathMLBlock(Element& container, PassRef<RenderStyle> style)
47    : RenderFlexibleBox(container, WTF::move(style))
48{
49}
50
51RenderMathMLBlock::RenderMathMLBlock(Document& document, PassRef<RenderStyle> style)
52    : RenderFlexibleBox(document, WTF::move(style))
53{
54}
55
56bool RenderMathMLBlock::isChildAllowed(const RenderObject& child, const RenderStyle&) const
57{
58    return child.node() && isElement(*child.node());
59}
60
61RenderPtr<RenderMathMLBlock> RenderMathMLBlock::createAnonymousMathMLBlock()
62{
63    RenderPtr<RenderMathMLBlock> newBlock = createRenderer<RenderMathMLBlock>(document(), RenderStyle::createAnonymousStyleWithDisplay(&style(), FLEX));
64    newBlock->initializeStyle();
65    return newBlock;
66}
67
68int RenderMathMLBlock::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
69{
70    // mathml.css sets math { -webkit-line-box-contain: glyphs replaced; line-height: 0; }, so when linePositionMode == PositionOfInteriorLineBoxes we want to
71    // return 0 here to match our line-height. This matters when RootInlineBox::ascentAndDescentForBox is called on a RootInlineBox for an inline-block.
72    if (linePositionMode == PositionOfInteriorLineBoxes)
73        return 0;
74
75    LayoutUnit baseline = firstLineBaseline(); // FIXME: This may be unnecessary after flex baselines are implemented (https://bugs.webkit.org/show_bug.cgi?id=96188).
76    if (baseline != -1)
77        return baseline;
78
79    return RenderFlexibleBox::baselinePosition(baselineType, firstLine, direction, linePositionMode);
80}
81
82const char* RenderMathMLBlock::renderName() const
83{
84    EDisplay display = style().display();
85    if (display == FLEX)
86        return isAnonymous() ? "RenderMathMLBlock (anonymous, flex)" : "RenderMathMLBlock (flex)";
87    if (display == INLINE_FLEX)
88        return isAnonymous() ? "RenderMathMLBlock (anonymous, inline-flex)" : "RenderMathMLBlock (inline-flex)";
89    // |display| should be one of the above.
90    ASSERT_NOT_REACHED();
91    return isAnonymous() ? "RenderMathMLBlock (anonymous)" : "RenderMathMLBlock";
92}
93
94#if ENABLE(DEBUG_MATH_LAYOUT)
95void RenderMathMLBlock::paint(PaintInfo& info, const LayoutPoint& paintOffset)
96{
97    RenderFlexibleBox::paint(info, paintOffset);
98
99    if (info.context->paintingDisabled() || info.phase != PaintPhaseForeground)
100        return;
101
102    IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset + location());
103
104    GraphicsContextStateSaver stateSaver(*info.context);
105
106    info.context->setStrokeThickness(1.0f);
107    info.context->setStrokeStyle(SolidStroke);
108    info.context->setStrokeColor(Color(0, 0, 255), ColorSpaceSRGB);
109
110    info.context->drawLine(adjustedPaintOffset, IntPoint(adjustedPaintOffset.x() + pixelSnappedOffsetWidth(), adjustedPaintOffset.y()));
111    info.context->drawLine(IntPoint(adjustedPaintOffset.x() + pixelSnappedOffsetWidth(), adjustedPaintOffset.y()), IntPoint(adjustedPaintOffset.x() + pixelSnappedOffsetWidth(), adjustedPaintOffset.y() + pixelSnappedOffsetHeight()));
112    info.context->drawLine(IntPoint(adjustedPaintOffset.x(), adjustedPaintOffset.y() + pixelSnappedOffsetHeight()), IntPoint(adjustedPaintOffset.x() + pixelSnappedOffsetWidth(), adjustedPaintOffset.y() + pixelSnappedOffsetHeight()));
113    info.context->drawLine(adjustedPaintOffset, IntPoint(adjustedPaintOffset.x(), adjustedPaintOffset.y() + pixelSnappedOffsetHeight()));
114
115    int topStart = paddingTop();
116
117    info.context->setStrokeColor(Color(0, 255, 0), ColorSpaceSRGB);
118
119    info.context->drawLine(IntPoint(adjustedPaintOffset.x(), adjustedPaintOffset.y() + topStart), IntPoint(adjustedPaintOffset.x() + pixelSnappedOffsetWidth(), adjustedPaintOffset.y() + topStart));
120
121    int baseline = roundToInt(baselinePosition(AlphabeticBaseline, true, HorizontalLine));
122
123    info.context->setStrokeColor(Color(255, 0, 0), ColorSpaceSRGB);
124
125    info.context->drawLine(IntPoint(adjustedPaintOffset.x(), adjustedPaintOffset.y() + baseline), IntPoint(adjustedPaintOffset.x() + pixelSnappedOffsetWidth(), adjustedPaintOffset.y() + baseline));
126}
127#endif // ENABLE(DEBUG_MATH_LAYOUT)
128
129//
130// The MathML specification says:
131// (http://www.w3.org/TR/MathML/chapter2.html#fund.units)
132//
133// "Most presentation elements have attributes that accept values representing
134// lengths to be used for size, spacing or similar properties. The syntax of a
135// length is specified as
136//
137// number | number unit | namedspace
138//
139// There should be no space between the number and the unit of a length."
140//
141// "A trailing '%' represents a percent of the default value. The default
142// value, or how it is obtained, is listed in the table of attributes for each
143// element. [...] A number without a unit is intepreted as a multiple of the
144// default value."
145//
146// "The possible units in MathML are:
147//
148// Unit Description
149// em   an em (font-relative unit traditionally used for horizontal lengths)
150// ex   an ex (font-relative unit traditionally used for vertical lengths)
151// px   pixels, or size of a pixel in the current display
152// in   inches (1 inch = 2.54 centimeters)
153// cm   centimeters
154// mm   millimeters
155// pt   points (1 point = 1/72 inch)
156// pc   picas (1 pica = 12 points)
157// %    percentage of default value"
158//
159// The numbers are defined that way:
160// - unsigned-number: "a string of decimal digits with up to one decimal point
161//   (U+002E), representing a non-negative terminating decimal number (a type of
162//   rational number)"
163// - number: "an optional prefix of '-' (U+002D), followed by an unsigned
164//   number, representing a terminating decimal number (a type of rational
165//   number)"
166//
167bool parseMathMLLength(const String& string, LayoutUnit& lengthValue, const RenderStyle* style, bool allowNegative)
168{
169    String s = string.simplifyWhiteSpace();
170
171    int stringLength = s.length();
172    if (!stringLength)
173        return false;
174
175    if (parseMathMLNamedSpace(s, lengthValue, style, allowNegative))
176        return true;
177
178    StringBuilder number;
179    String unit;
180
181    // This verifies whether the negative sign is there.
182    int i = 0;
183    UChar c = s[0];
184    if (c == '-') {
185        number.append(c);
186        i++;
187    }
188
189    // This gathers up characters that make up the number.
190    bool gotDot = false;
191    for ( ; i < stringLength; i++) {
192        c = s[i];
193        // The string is invalid if it contains two dots.
194        if (gotDot && c == '.')
195            return false;
196        if (c == '.')
197            gotDot = true;
198        else if (!isASCIIDigit(c)) {
199            unit = s.substring(i, stringLength - i);
200            // Some authors leave blanks before the unit, but that shouldn't
201            // be allowed, so don't simplifyWhitespace on 'unit'.
202            break;
203        }
204        number.append(c);
205    }
206
207    // Convert number to floating point
208    bool ok;
209    float floatValue = number.toString().toFloat(&ok);
210    if (!ok)
211        return false;
212    if (floatValue < 0 && !allowNegative)
213        return false;
214
215    if (unit.isEmpty()) {
216        // no explicit unit, this is a number that will act as a multiplier
217        lengthValue *= floatValue;
218        return true;
219    }
220    if (unit == "%") {
221        lengthValue *= floatValue / 100;
222        return true;
223    }
224    if (unit == "em") {
225        lengthValue = floatValue * style->font().size();
226        return true;
227    }
228    if (unit == "ex") {
229        lengthValue = floatValue * style->fontMetrics().xHeight();
230        return true;
231    }
232    if (unit == "px") {
233        lengthValue = floatValue;
234        return true;
235    }
236    if (unit == "pt") {
237        lengthValue = 4 * (floatValue / 3);
238        return true;
239    }
240    if (unit == "pc") {
241        lengthValue = 16 * floatValue;
242        return true;
243    }
244    if (unit == "in") {
245        lengthValue = 96 * floatValue;
246        return true;
247    }
248    if (unit == "cm") {
249        lengthValue = 96 * (floatValue / 2.54);
250        return true;
251    }
252    if (unit == "mm") {
253        lengthValue = 96 * (floatValue / 25.4);
254        return true;
255    }
256
257    // unexpected unit
258    return false;
259}
260
261bool parseMathMLNamedSpace(const String& string, LayoutUnit& lengthValue, const RenderStyle* style, bool allowNegative)
262{
263    float length = 0;
264    // See if it is one of the namedspaces (ranging -7/18em, -6/18, ... 7/18em)
265    if (string == "veryverythinmathspace")
266        length = 1;
267    else if (string == "verythinmathspace")
268        length = 2;
269    else if (string == "thinmathspace")
270        length = 3;
271    else if (string == "mediummathspace")
272        length = 4;
273    else if (string == "thickmathspace")
274        length = 5;
275    else if (string == "verythickmathspace")
276        length = 6;
277    else if (string == "veryverythickmathspace")
278        length = 7;
279    else if (allowNegative) {
280        if (string == "negativeveryverythinmathspace")
281            length = -1;
282        else if (string == "negativeverythinmathspace")
283            length = -2;
284        else if (string == "negativethinmathspace")
285            length = -3;
286        else if (string == "negativemediummathspace")
287            length = -4;
288        else if (string == "negativethickmathspace")
289            length = -5;
290        else if (string == "negativeverythickmathspace")
291            length = -6;
292        else if (string == "negativeveryverythickmathspace")
293            length = -7;
294    }
295    if (length) {
296        lengthValue = length * style->font().size() / 18;
297        return true;
298    }
299    return false;
300}
301
302int RenderMathMLTable::firstLineBaseline() const
303{
304    // In legal MathML, we'll have a MathML parent. That RenderFlexibleBox parent will use our firstLineBaseline() for baseline alignment, per
305    // http://dev.w3.org/csswg/css3-flexbox/#flex-baselines. We want to vertically center an <mtable>, such as a matrix. Essentially the whole <mtable> element fits on a
306    // single line, whose baseline gives this centering. This is different than RenderTable::firstLineBoxBaseline, which returns the baseline of the first row of a <table>.
307    return (logicalHeight() + style().fontMetrics().xHeight()) / 2;
308}
309
310}
311
312#endif
313