summaryrefslogtreecommitdiff
path: root/Source/WebCore/rendering/mathml/RenderMathMLRoot.cpp
blob: 14afbdfa57e0530b45a3dc23bdec68ce5f4f7a2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*
 * Copyright (C) 2009 Alex Milowski (alex@milowski.com). All rights reserved.
 * Copyright (C) 2010 François Sausset (sausset@gmail.com). All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#if ENABLE(MATHML)

#include "RenderMathMLRoot.h"

#include "FontCache.h"
#include "GraphicsContext.h"
#include "PaintInfo.h"
#include "RenderIterator.h"
#include "RenderMathMLRadicalOperator.h"
#include "RenderMathMLSquareRoot.h"

namespace WebCore {
    
// RenderMathMLRoot implements drawing of radicals via the <mroot> and <msqrt> elements. For valid MathML elements, the DOM is
//
// <mroot> Base Index </mroot>
// <msqrt> Child1 Child2 ... ChildN </msqrt>
//
// and the structure of the render tree will be
//
// IndexWrapper RadicalWrapper BaseWrapper
//
// where RadicalWrapper contains an <mo>&#x221A;</mo>.
// For <mroot>, the IndexWrapper and BaseWrapper should contain exactly one child (Index and Base respectively).
// For <msqrt>, the IndexWrapper should be empty and the BaseWrapper can contain any number of children (Child1, ... ChildN).
//
// In order to accept invalid markup and to handle <mroot> and <msqrt> consistently, we will allow any number of children in the BaseWrapper of <mroot> too.
// We will allow the IndexWrapper to be empty and it will always contain the last child of the <mroot> if there are at least 2 elements.

RenderMathMLRoot::RenderMathMLRoot(Element& element, Ref<RenderStyle>&& style)
    : RenderMathMLBlock(element, WTFMove(style))
{
}

RenderMathMLRoot::RenderMathMLRoot(Document& document, Ref<RenderStyle>&& style)
    : RenderMathMLBlock(document, WTFMove(style))
{
}

RenderMathMLRootWrapper* RenderMathMLRoot::baseWrapper() const
{
    ASSERT(!isEmpty());
    return downcast<RenderMathMLRootWrapper>(lastChild());
}

RenderMathMLBlock* RenderMathMLRoot::radicalWrapper() const
{
    ASSERT(!isEmpty());
    return downcast<RenderMathMLBlock>(lastChild()->previousSibling());
}

RenderMathMLRootWrapper* RenderMathMLRoot::indexWrapper() const
{
    ASSERT(!isEmpty());
    return is<RenderMathMLSquareRoot>(*this) ? nullptr : downcast<RenderMathMLRootWrapper>(firstChild());
}

RenderMathMLRadicalOperator* RenderMathMLRoot::radicalOperator() const
{
    ASSERT(!isEmpty());
    return downcast<RenderMathMLRadicalOperator>(radicalWrapper()->firstChild());
}

void RenderMathMLRoot::restructureWrappers()
{
    ASSERT(!isEmpty());

    auto base = baseWrapper();
    auto index = indexWrapper();
    auto radical = radicalWrapper();

    // For visual consistency with the initial state, we remove the radical when the base/index wrappers become empty.
    if (base->isEmpty() && (!index || index->isEmpty())) {
        if (!radical->isEmpty()) {
            auto child = radicalOperator();
            radical->removeChild(*child);
            child->destroy();
        }
        // FIXME: early return!!!
    }

    if (radical->isEmpty()) {
        // We create the radical operator.
        RenderPtr<RenderMathMLRadicalOperator> radicalOperator = createRenderer<RenderMathMLRadicalOperator>(document(), RenderStyle::createAnonymousStyleWithDisplay(&style(), FLEX));
        radicalOperator->initializeStyle();
        radical->addChild(radicalOperator.leakPtr());
    }

    if (isRenderMathMLSquareRoot())
        return;

    if (auto childToMove = base->lastChild()) {
        // We move the last child of the base wrapper into the index wrapper if the index wrapper is empty and the base wrapper has at least two children.
        if (childToMove->previousSibling() && index->isEmpty()) {
            base->removeChildWithoutRestructuring(*childToMove);
            index->addChild(childToMove);
        }
    }

    if (auto childToMove = index->firstChild()) {
        // We move the first child of the index wrapper into the base wrapper if:
        // - either the index wrapper has at least two children.
        // - or the base wrapper is empty but the index wrapper is not.
        if (childToMove->nextSibling() || base->isEmpty()) {
            index->removeChildWithoutRestructuring(*childToMove);
            base->addChild(childToMove);
        }
    }
}

void RenderMathMLRoot::addChild(RenderObject* newChild, RenderObject* beforeChild)
{
    if (isEmpty()) {
        if (!isRenderMathMLSquareRoot()) {
            // We add the IndexWrapper.
            RenderMathMLBlock::addChild(RenderMathMLRootWrapper::createAnonymousWrapper(this).leakPtr());
        }

        // We create the radicalWrapper
        RenderMathMLBlock::addChild(RenderMathMLBlock::createAnonymousMathMLBlock().leakPtr());

        // We create the BaseWrapper.
        RenderMathMLBlock::addChild(RenderMathMLRootWrapper::createAnonymousWrapper(this).leakPtr());

        updateStyle();
    }

    // We insert the child.
    auto base = baseWrapper();
    auto index = indexWrapper();
    RenderElement* actualParent;
    RenderElement* actualBeforeChild;
    if (is<RenderMathMLSquareRoot>(*this)) {
        // For square root, we always insert the child into the base wrapper.
        actualParent = base;
        if (beforeChild && beforeChild->parent() == base)
            actualBeforeChild = downcast<RenderElement>(beforeChild);
        else
            actualBeforeChild = nullptr;
    } else {
        // For mroot, we insert the child into the parent of beforeChild, or at the end of the index. The wrapper structure is reorganize below.
        actualParent = beforeChild ? beforeChild->parent() : nullptr;
        if (actualParent == base || actualParent == index)
            actualBeforeChild = downcast<RenderElement>(beforeChild);
        else {
            actualParent = index;
            actualBeforeChild = nullptr;
        }
    }
    actualParent->addChild(newChild, actualBeforeChild);
    restructureWrappers();
}

void RenderMathMLRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
    RenderMathMLBlock::styleDidChange(diff, oldStyle);
    if (!isEmpty())
        updateStyle();
}

void RenderMathMLRoot::updateFromElement()
{
    RenderMathMLBlock::updateFromElement();
    if (!isEmpty())
        updateStyle();
}

void RenderMathMLRoot::updateStyle()
{
    ASSERT(!isEmpty());

    // We set some constants to draw the radical, as defined in the OpenType MATH tables.

    m_ruleThickness = 0.05f * style().fontCascade().size();

    // FIXME: The recommended default for m_verticalGap in displaystyle is rule thickness + 1/4 x-height (https://bugs.webkit.org/show_bug.cgi?id=118737).
    m_verticalGap = 11 * m_ruleThickness / 4;
    m_extraAscender = m_ruleThickness;
    LayoutUnit kernBeforeDegree = 5 * style().fontCascade().size() / 18;
    LayoutUnit kernAfterDegree = -10 * style().fontCascade().size() / 18;
    m_degreeBottomRaisePercent = 0.6f;

    const auto& primaryFont = style().fontCascade().primaryFont();
    if (auto* mathData = style().fontCascade().primaryFont().mathData()) {
        // FIXME: m_verticalGap should use RadicalDisplayStyleVertical in display mode (https://bugs.webkit.org/show_bug.cgi?id=118737).
        m_verticalGap = mathData->getMathConstant(primaryFont, OpenTypeMathData::RadicalVerticalGap);
        m_ruleThickness = mathData->getMathConstant(primaryFont, OpenTypeMathData::RadicalRuleThickness);
        m_extraAscender = mathData->getMathConstant(primaryFont, OpenTypeMathData::RadicalExtraAscender);

        if (!isRenderMathMLSquareRoot()) {
            kernBeforeDegree = mathData->getMathConstant(primaryFont, OpenTypeMathData::RadicalKernBeforeDegree);
            kernAfterDegree = mathData->getMathConstant(primaryFont, OpenTypeMathData::RadicalKernAfterDegree);
            m_degreeBottomRaisePercent = mathData->getMathConstant(primaryFont, OpenTypeMathData::RadicalDegreeBottomRaisePercent);
        }
    }

    // We set the style of the anonymous wrappers.

    auto radical = radicalWrapper();
    auto radicalStyle = RenderStyle::createAnonymousStyleWithDisplay(&style(), FLEX);
    radicalStyle.get().setMarginTop(Length(0, Fixed)); // This will be updated in RenderMathMLRoot::layout().
    radical->setStyle(WTFMove(radicalStyle));
    radical->setNeedsLayoutAndPrefWidthsRecalc();

    auto base = baseWrapper();
    auto baseStyle = RenderStyle::createAnonymousStyleWithDisplay(&style(), FLEX);
    baseStyle.get().setMarginTop(Length(0, Fixed)); // This will be updated in RenderMathMLRoot::layout().
    baseStyle.get().setAlignItemsPosition(ItemPositionBaseline);
    base->setStyle(WTFMove(baseStyle));
    base->setNeedsLayoutAndPrefWidthsRecalc();

    if (!isRenderMathMLSquareRoot()) {
        // For mroot, we also set the style of the index wrapper.
        auto index = indexWrapper();
        auto indexStyle = RenderStyle::createAnonymousStyleWithDisplay(&style(), FLEX);
        indexStyle.get().setMarginTop(Length(0, Fixed)); // This will be updated in RenderMathMLRoot::layout().
        indexStyle.get().setMarginStart(Length(kernBeforeDegree, Fixed));
        indexStyle.get().setMarginEnd(Length(kernAfterDegree, Fixed));
        indexStyle.get().setAlignItemsPosition(ItemPositionBaseline);
        index->setStyle(WTFMove(indexStyle));
        index->setNeedsLayoutAndPrefWidthsRecalc();
    }
}

Optional<int> RenderMathMLRoot::firstLineBaseline() const
{
    if (!isEmpty()) {
        auto base = baseWrapper();
        return static_cast<int>(lroundf(base->firstLineBaseline().valueOr(-1) + base->marginTop()));
    }

    return RenderMathMLBlock::firstLineBaseline();
}

void RenderMathMLRoot::layout()
{
    if (isEmpty()) {
        RenderMathMLBlock::layout();
        return;
    }

    // FIXME: It seems that changing the top margin of the base below modifies its logical height and leads to reftest failures.
    // For now, we workaround that by avoiding to recompute the child margins if they were not reset in updateStyle().
    auto base = baseWrapper();
    if (base->marginTop() > 0) {
        RenderMathMLBlock::layout();
        return;
    }

    // We layout the children.
    for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
        if (child->needsLayout())
            downcast<RenderElement>(*child).layout();
    }

    auto radical = radicalOperator();
    if (radical) {
        // We stretch the radical sign to cover the height of the base wrapper.
        float baseHeight = base->logicalHeight();
        float baseHeightAboveBaseline = base->firstLineBaseline().valueOr(baseHeight);
        float baseDepthBelowBaseline = baseHeight - baseHeightAboveBaseline;
        baseHeightAboveBaseline += m_verticalGap;
        radical->stretchTo(baseHeightAboveBaseline, baseDepthBelowBaseline);

        // We modify the top margins to adjust the vertical positions of wrappers.
        float radicalTopMargin = m_extraAscender;
        float baseTopMargin = m_verticalGap + m_ruleThickness + m_extraAscender;
        if (!isRenderMathMLSquareRoot()) {
            // For mroot, we try to place the index so the space below its baseline is m_degreeBottomRaisePercent times the height of the radical.
            auto index = indexWrapper();
            float indexHeight = 0;
            if (!index->isEmpty())
                indexHeight = downcast<RenderBlock>(*index->firstChild()).logicalHeight();
            float indexTopMargin = (1.0 - m_degreeBottomRaisePercent) * radical->stretchSize() + radicalTopMargin - indexHeight;
            if (indexTopMargin < 0) {
                // If the index is too tall, we must add space at the top of renderer.
                radicalTopMargin -= indexTopMargin;
                baseTopMargin -= indexTopMargin;
                indexTopMargin = 0;
            }
            index->style().setMarginTop(Length(indexTopMargin, Fixed));
        }
        radical->style().setMarginTop(Length(radicalTopMargin, Fixed));
        base->style().setMarginTop(Length(baseTopMargin, Fixed));
    }

    RenderMathMLBlock::layout();
}

void RenderMathMLRoot::paint(PaintInfo& info, const LayoutPoint& paintOffset)
{
    RenderMathMLBlock::paint(info, paintOffset);
    
    if (isEmpty() || info.context().paintingDisabled() || style().visibility() != VISIBLE)
        return;

    auto base = baseWrapper();
    auto radical = radicalOperator();
    if (!base || !radical || !m_ruleThickness)
        return;

    // We draw the radical line.
    GraphicsContextStateSaver stateSaver(info.context());

    info.context().setStrokeThickness(m_ruleThickness);
    info.context().setStrokeStyle(SolidStroke);
    info.context().setStrokeColor(style().visitedDependentColor(CSSPropertyColor));

    // The preferred width of the radical is sometimes incorrect, so we draw a slightly longer line to ensure it touches the radical symbol (https://bugs.webkit.org/show_bug.cgi?id=130326).
    LayoutUnit sizeError = radical->trailingSpaceError();
    IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset + location() + base->location() + LayoutPoint(-sizeError, -(m_verticalGap + m_ruleThickness / 2)));
    info.context().drawLine(adjustedPaintOffset, roundedIntPoint(LayoutPoint(adjustedPaintOffset.x() + base->offsetWidth() + sizeError, adjustedPaintOffset.y())));
}

RenderPtr<RenderMathMLRootWrapper> RenderMathMLRootWrapper::createAnonymousWrapper(RenderMathMLRoot* renderObject)
{
    RenderPtr<RenderMathMLRootWrapper> newBlock = createRenderer<RenderMathMLRootWrapper>(renderObject->document(), RenderStyle::createAnonymousStyleWithDisplay(&renderObject->style(), FLEX));
    newBlock->initializeStyle();
    return newBlock;
}

void RenderMathMLRootWrapper::removeChildWithoutRestructuring(RenderObject& child)
{
    RenderMathMLBlock::removeChild(child);
}

void RenderMathMLRootWrapper::removeChild(RenderObject& child)
{
    RenderMathMLBlock::removeChild(child);

    if (!(beingDestroyed() || documentBeingDestroyed()))
        downcast<RenderMathMLRoot>(*parent()).restructureWrappers();
}

}

#endif // ENABLE(MATHML)