Bumping manifests a=b2g-bump
[gecko.git] / dom / mathml / nsMathMLElement.cpp
blob2b63f09798844dbaa478d6bc1f7df283521e007b
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "nsMathMLElement.h"
8 #include "base/compiler_specific.h"
9 #include "mozilla/ArrayUtils.h"
10 #include "nsGkAtoms.h"
11 #include "nsCRT.h"
12 #include "nsLayoutStylesheetCache.h"
13 #include "nsRuleData.h"
14 #include "nsCSSValue.h"
15 #include "nsCSSParser.h"
16 #include "nsMappedAttributes.h"
17 #include "nsStyleConsts.h"
18 #include "nsIDocument.h"
19 #include "nsIPresShell.h"
20 #include "nsPresContext.h"
21 #include "mozAutoDocUpdate.h"
22 #include "nsIScriptError.h"
23 #include "nsContentUtils.h"
24 #include "nsIURI.h"
26 #include "mozilla/EventDispatcher.h"
27 #include "mozilla/EventStates.h"
28 #include "mozilla/dom/ElementBinding.h"
30 using namespace mozilla;
31 using namespace mozilla::dom;
33 //----------------------------------------------------------------------
34 // nsISupports methods:
36 NS_IMPL_ISUPPORTS_INHERITED(nsMathMLElement, nsMathMLElementBase,
37 nsIDOMElement, nsIDOMNode, Link)
39 static nsresult
40 WarnDeprecated(const char16_t* aDeprecatedAttribute,
41 const char16_t* aFavoredAttribute, nsIDocument* aDocument)
43 const char16_t *argv[] =
44 { aDeprecatedAttribute, aFavoredAttribute };
45 return nsContentUtils::
46 ReportToConsole(nsIScriptError::warningFlag,
47 NS_LITERAL_CSTRING("MathML"), aDocument,
48 nsContentUtils::eMATHML_PROPERTIES,
49 "DeprecatedSupersededBy", argv, 2);
52 static nsresult
53 ReportLengthParseError(const nsString& aValue, nsIDocument* aDocument)
55 const char16_t *arg = aValue.get();
56 return nsContentUtils::
57 ReportToConsole(nsIScriptError::errorFlag,
58 NS_LITERAL_CSTRING("MathML"), aDocument,
59 nsContentUtils::eMATHML_PROPERTIES,
60 "LengthParsingError", &arg, 1);
63 static nsresult
64 ReportParseErrorNoTag(const nsString& aValue,
65 nsIAtom* aAtom,
66 nsIDocument* aDocument)
68 const char16_t *argv[] =
69 { aValue.get(), aAtom->GetUTF16String() };
70 return nsContentUtils::
71 ReportToConsole(nsIScriptError::errorFlag,
72 NS_LITERAL_CSTRING("MathML"), aDocument,
73 nsContentUtils::eMATHML_PROPERTIES,
74 "AttributeParsingErrorNoTag", argv, 2);
77 nsMathMLElement::nsMathMLElement(already_AddRefed<mozilla::dom::NodeInfo>& aNodeInfo)
78 : nsMathMLElementBase(aNodeInfo),
79 ALLOW_THIS_IN_INITIALIZER_LIST(Link(this)),
80 mIncrementScriptLevel(false)
84 nsMathMLElement::nsMathMLElement(already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo)
85 : nsMathMLElementBase(aNodeInfo),
86 ALLOW_THIS_IN_INITIALIZER_LIST(Link(this)),
87 mIncrementScriptLevel(false)
91 nsresult
92 nsMathMLElement::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
93 nsIContent* aBindingParent,
94 bool aCompileEventHandlers)
96 Link::ResetLinkState(false, Link::ElementHasHref());
98 nsresult rv = nsMathMLElementBase::BindToTree(aDocument, aParent,
99 aBindingParent,
100 aCompileEventHandlers);
101 NS_ENSURE_SUCCESS(rv, rv);
103 if (aDocument) {
104 aDocument->RegisterPendingLinkUpdate(this);
106 if (!aDocument->GetMathMLEnabled()) {
107 // Enable MathML and setup the style sheet during binding, not element
108 // construction, because we could move a MathML element from the document
109 // that created it to another document.
110 aDocument->SetMathMLEnabled();
111 aDocument->
112 EnsureOnDemandBuiltInUASheet(nsLayoutStylesheetCache::MathMLSheet());
114 // Rebuild style data for the presshell, because style system
115 // optimizations may have taken place assuming MathML was disabled.
116 // (See nsRuleNode::CheckSpecifiedProperties.)
117 nsCOMPtr<nsIPresShell> shell = aDocument->GetShell();
118 if (shell) {
119 shell->GetPresContext()->PostRebuildAllStyleDataEvent(nsChangeHint(0));
124 return rv;
127 void
128 nsMathMLElement::UnbindFromTree(bool aDeep, bool aNullParent)
130 // If this link is ever reinserted into a document, it might
131 // be under a different xml:base, so forget the cached state now.
132 Link::ResetLinkState(false, Link::ElementHasHref());
134 nsIDocument* doc = GetCurrentDoc();
135 if (doc) {
136 doc->UnregisterPendingLinkUpdate(this);
139 nsMathMLElementBase::UnbindFromTree(aDeep, aNullParent);
142 bool
143 nsMathMLElement::ParseAttribute(int32_t aNamespaceID,
144 nsIAtom* aAttribute,
145 const nsAString& aValue,
146 nsAttrValue& aResult)
148 if (aNamespaceID == kNameSpaceID_None) {
149 if (Tag() == nsGkAtoms::math && aAttribute == nsGkAtoms::mode) {
150 WarnDeprecated(nsGkAtoms::mode->GetUTF16String(),
151 nsGkAtoms::display->GetUTF16String(), OwnerDoc());
153 if (aAttribute == nsGkAtoms::color) {
154 WarnDeprecated(nsGkAtoms::color->GetUTF16String(),
155 nsGkAtoms::mathcolor_->GetUTF16String(), OwnerDoc());
157 if (aAttribute == nsGkAtoms::color ||
158 aAttribute == nsGkAtoms::mathcolor_ ||
159 aAttribute == nsGkAtoms::background ||
160 aAttribute == nsGkAtoms::mathbackground_) {
161 return aResult.ParseColor(aValue);
165 return nsMathMLElementBase::ParseAttribute(aNamespaceID, aAttribute,
166 aValue, aResult);
169 static Element::MappedAttributeEntry sMtableStyles[] = {
170 { &nsGkAtoms::width },
171 { nullptr }
174 static Element::MappedAttributeEntry sTokenStyles[] = {
175 { &nsGkAtoms::mathsize_ },
176 { &nsGkAtoms::fontsize_ },
177 { &nsGkAtoms::color },
178 { &nsGkAtoms::fontfamily_ },
179 { &nsGkAtoms::fontstyle_ },
180 { &nsGkAtoms::fontweight_ },
181 { &nsGkAtoms::mathvariant_},
182 { nullptr }
185 static Element::MappedAttributeEntry sEnvironmentStyles[] = {
186 { &nsGkAtoms::scriptlevel_ },
187 { &nsGkAtoms::scriptminsize_ },
188 { &nsGkAtoms::scriptsizemultiplier_ },
189 { &nsGkAtoms::background },
190 { nullptr }
193 static Element::MappedAttributeEntry sCommonPresStyles[] = {
194 { &nsGkAtoms::mathcolor_ },
195 { &nsGkAtoms::mathbackground_ },
196 { nullptr }
199 static Element::MappedAttributeEntry sDirStyles[] = {
200 { &nsGkAtoms::dir },
201 { nullptr }
204 bool
205 nsMathMLElement::IsAttributeMapped(const nsIAtom* aAttribute) const
207 static const MappedAttributeEntry* const mtableMap[] = {
208 sMtableStyles,
209 sCommonPresStyles
211 static const MappedAttributeEntry* const tokenMap[] = {
212 sTokenStyles,
213 sCommonPresStyles,
214 sDirStyles
216 static const MappedAttributeEntry* const mstyleMap[] = {
217 sTokenStyles,
218 sEnvironmentStyles,
219 sCommonPresStyles,
220 sDirStyles
222 static const MappedAttributeEntry* const commonPresMap[] = {
223 sCommonPresStyles
225 static const MappedAttributeEntry* const mrowMap[] = {
226 sCommonPresStyles,
227 sDirStyles
230 // We don't support mglyph (yet).
231 nsIAtom* tag = Tag();
232 if (tag == nsGkAtoms::ms_ || tag == nsGkAtoms::mi_ ||
233 tag == nsGkAtoms::mn_ || tag == nsGkAtoms::mo_ ||
234 tag == nsGkAtoms::mtext_ || tag == nsGkAtoms::mspace_)
235 return FindAttributeDependence(aAttribute, tokenMap);
236 if (tag == nsGkAtoms::mstyle_ ||
237 tag == nsGkAtoms::math)
238 return FindAttributeDependence(aAttribute, mstyleMap);
240 if (tag == nsGkAtoms::mtable_)
241 return FindAttributeDependence(aAttribute, mtableMap);
243 if (tag == nsGkAtoms::mrow_)
244 return FindAttributeDependence(aAttribute, mrowMap);
246 if (tag == nsGkAtoms::maction_ ||
247 tag == nsGkAtoms::maligngroup_ ||
248 tag == nsGkAtoms::malignmark_ ||
249 tag == nsGkAtoms::menclose_ ||
250 tag == nsGkAtoms::merror_ ||
251 tag == nsGkAtoms::mfenced_ ||
252 tag == nsGkAtoms::mfrac_ ||
253 tag == nsGkAtoms::mover_ ||
254 tag == nsGkAtoms::mpadded_ ||
255 tag == nsGkAtoms::mphantom_ ||
256 tag == nsGkAtoms::mprescripts_ ||
257 tag == nsGkAtoms::mroot_ ||
258 tag == nsGkAtoms::msqrt_ ||
259 tag == nsGkAtoms::msub_ ||
260 tag == nsGkAtoms::msubsup_ ||
261 tag == nsGkAtoms::msup_ ||
262 tag == nsGkAtoms::mtd_ ||
263 tag == nsGkAtoms::mtr_ ||
264 tag == nsGkAtoms::munder_ ||
265 tag == nsGkAtoms::munderover_ ||
266 tag == nsGkAtoms::none) {
267 return FindAttributeDependence(aAttribute, commonPresMap);
270 return false;
273 nsMapRuleToAttributesFunc
274 nsMathMLElement::GetAttributeMappingFunction() const
276 // It doesn't really matter what our tag is here, because only attributes
277 // that satisfy IsAttributeMapped will be stored in the mapped attributes
278 // list and available to the mapping function
279 return &MapMathMLAttributesInto;
282 /* static */ bool
283 nsMathMLElement::ParseNamedSpaceValue(const nsString& aString,
284 nsCSSValue& aCSSValue,
285 uint32_t aFlags)
287 int32_t i = 0;
288 // See if it is one of the 'namedspace' (ranging -7/18em, -6/18, ... 7/18em)
289 if (aString.EqualsLiteral("veryverythinmathspace")) {
290 i = 1;
291 } else if (aString.EqualsLiteral("verythinmathspace")) {
292 i = 2;
293 } else if (aString.EqualsLiteral("thinmathspace")) {
294 i = 3;
295 } else if (aString.EqualsLiteral("mediummathspace")) {
296 i = 4;
297 } else if (aString.EqualsLiteral("thickmathspace")) {
298 i = 5;
299 } else if (aString.EqualsLiteral("verythickmathspace")) {
300 i = 6;
301 } else if (aString.EqualsLiteral("veryverythickmathspace")) {
302 i = 7;
303 } else if (aFlags & PARSE_ALLOW_NEGATIVE) {
304 if (aString.EqualsLiteral("negativeveryverythinmathspace")) {
305 i = -1;
306 } else if (aString.EqualsLiteral("negativeverythinmathspace")) {
307 i = -2;
308 } else if (aString.EqualsLiteral("negativethinmathspace")) {
309 i = -3;
310 } else if (aString.EqualsLiteral("negativemediummathspace")) {
311 i = -4;
312 } else if (aString.EqualsLiteral("negativethickmathspace")) {
313 i = -5;
314 } else if (aString.EqualsLiteral("negativeverythickmathspace")) {
315 i = -6;
316 } else if (aString.EqualsLiteral("negativeveryverythickmathspace")) {
317 i = -7;
320 if (0 != i) {
321 aCSSValue.SetFloatValue(float(i)/float(18), eCSSUnit_EM);
322 return true;
325 return false;
328 // The REC says:
330 // "Most presentation elements have attributes that accept values representing
331 // lengths to be used for size, spacing or similar properties. The syntax of a
332 // length is specified as
334 // number | number unit | namedspace
336 // There should be no space between the number and the unit of a length."
338 // "A trailing '%' represents a percent of the default value. The default
339 // value, or how it is obtained, is listed in the table of attributes for each
340 // element. [...] A number without a unit is intepreted as a multiple of the
341 // default value."
343 // "The possible units in MathML are:
345 // Unit Description
346 // em an em (font-relative unit traditionally used for horizontal lengths)
347 // ex an ex (font-relative unit traditionally used for vertical lengths)
348 // px pixels, or size of a pixel in the current display
349 // in inches (1 inch = 2.54 centimeters)
350 // cm centimeters
351 // mm millimeters
352 // pt points (1 point = 1/72 inch)
353 // pc picas (1 pica = 12 points)
354 // % percentage of default value"
356 // The numbers are defined that way:
357 // - unsigned-number: "a string of decimal digits with up to one decimal point
358 // (U+002E), representing a non-negative terminating decimal number (a type of
359 // rational number)"
360 // - number: "an optional prefix of '-' (U+002D), followed by an unsigned
361 // number, representing a terminating decimal number (a type of rational
362 // number)"
364 /* static */ bool
365 nsMathMLElement::ParseNumericValue(const nsString& aString,
366 nsCSSValue& aCSSValue,
367 uint32_t aFlags,
368 nsIDocument* aDocument)
370 nsAutoString str(aString);
371 str.CompressWhitespace(); // aString is const in this code...
373 int32_t stringLength = str.Length();
374 if (!stringLength) {
375 if (!(aFlags & PARSE_SUPPRESS_WARNINGS)) {
376 ReportLengthParseError(aString, aDocument);
378 return false;
381 if (ParseNamedSpaceValue(aString, aCSSValue, aFlags)) {
382 return true;
385 nsAutoString number, unit;
387 // see if the negative sign is there
388 int32_t i = 0;
389 char16_t c = str[0];
390 if (c == '-') {
391 number.Append(c);
392 i++;
395 // Gather up characters that make up the number
396 bool gotDot = false;
397 for ( ; i < stringLength; i++) {
398 c = str[i];
399 if (gotDot && c == '.') {
400 if (!(aFlags & PARSE_SUPPRESS_WARNINGS)) {
401 ReportLengthParseError(aString, aDocument);
403 return false; // two dots encountered
405 else if (c == '.')
406 gotDot = true;
407 else if (!nsCRT::IsAsciiDigit(c)) {
408 str.Right(unit, stringLength - i);
409 // some authors leave blanks before the unit, but that shouldn't
410 // be allowed, so don't CompressWhitespace on 'unit'.
411 break;
413 number.Append(c);
416 // Convert number to floating point
417 nsresult errorCode;
418 float floatValue = number.ToFloat(&errorCode);
419 if (NS_FAILED(errorCode)) {
420 if (!(aFlags & PARSE_SUPPRESS_WARNINGS)) {
421 ReportLengthParseError(aString, aDocument);
423 return false;
425 if (floatValue < 0 && !(aFlags & PARSE_ALLOW_NEGATIVE)) {
426 if (!(aFlags & PARSE_SUPPRESS_WARNINGS)) {
427 ReportLengthParseError(aString, aDocument);
429 return false;
432 nsCSSUnit cssUnit;
433 if (unit.IsEmpty()) {
434 if (aFlags & PARSE_ALLOW_UNITLESS) {
435 // no explicit unit, this is a number that will act as a multiplier
436 if (!(aFlags & PARSE_SUPPRESS_WARNINGS)) {
437 nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
438 NS_LITERAL_CSTRING("MathML"), aDocument,
439 nsContentUtils::eMATHML_PROPERTIES,
440 "UnitlessValuesAreDeprecated");
442 if (aFlags & CONVERT_UNITLESS_TO_PERCENT) {
443 aCSSValue.SetPercentValue(floatValue);
444 return true;
446 else
447 cssUnit = eCSSUnit_Number;
448 } else {
449 // We are supposed to have a unit, but there isn't one.
450 // If the value is 0 we can just call it "pixels" otherwise
451 // this is illegal.
452 if (floatValue != 0.0) {
453 if (!(aFlags & PARSE_SUPPRESS_WARNINGS)) {
454 ReportLengthParseError(aString, aDocument);
456 return false;
458 cssUnit = eCSSUnit_Pixel;
461 else if (unit.EqualsLiteral("%")) {
462 aCSSValue.SetPercentValue(floatValue / 100.0f);
463 return true;
465 else if (unit.EqualsLiteral("em")) cssUnit = eCSSUnit_EM;
466 else if (unit.EqualsLiteral("ex")) cssUnit = eCSSUnit_XHeight;
467 else if (unit.EqualsLiteral("px")) cssUnit = eCSSUnit_Pixel;
468 else if (unit.EqualsLiteral("in")) cssUnit = eCSSUnit_Inch;
469 else if (unit.EqualsLiteral("cm")) cssUnit = eCSSUnit_Centimeter;
470 else if (unit.EqualsLiteral("mm")) cssUnit = eCSSUnit_Millimeter;
471 else if (unit.EqualsLiteral("pt")) cssUnit = eCSSUnit_Point;
472 else if (unit.EqualsLiteral("pc")) cssUnit = eCSSUnit_Pica;
473 else { // unexpected unit
474 if (!(aFlags & PARSE_SUPPRESS_WARNINGS)) {
475 ReportLengthParseError(aString, aDocument);
477 return false;
480 aCSSValue.SetFloatValue(floatValue, cssUnit);
481 return true;
484 void
485 nsMathMLElement::MapMathMLAttributesInto(const nsMappedAttributes* aAttributes,
486 nsRuleData* aData)
488 if (aData->mSIDs & NS_STYLE_INHERIT_BIT(Font)) {
489 // scriptsizemultiplier
491 // "Specifies the multiplier to be used to adjust font size due to changes
492 // in scriptlevel.
494 // values: number
495 // default: 0.71
497 const nsAttrValue* value =
498 aAttributes->GetAttr(nsGkAtoms::scriptsizemultiplier_);
499 nsCSSValue* scriptSizeMultiplier =
500 aData->ValueForScriptSizeMultiplier();
501 if (value && value->Type() == nsAttrValue::eString &&
502 scriptSizeMultiplier->GetUnit() == eCSSUnit_Null) {
503 nsAutoString str(value->GetStringValue());
504 str.CompressWhitespace();
505 // MathML numbers can't have leading '+'
506 if (str.Length() > 0 && str.CharAt(0) != '+') {
507 nsresult errorCode;
508 float floatValue = str.ToFloat(&errorCode);
509 // Negative scriptsizemultipliers are not parsed
510 if (NS_SUCCEEDED(errorCode) && floatValue >= 0.0f) {
511 scriptSizeMultiplier->SetFloatValue(floatValue, eCSSUnit_Number);
512 } else {
513 ReportParseErrorNoTag(str,
514 nsGkAtoms::scriptsizemultiplier_,
515 aData->mPresContext->Document());
520 // scriptminsize
522 // "Specifies the minimum font size allowed due to changes in scriptlevel.
523 // Note that this does not limit the font size due to changes to mathsize."
525 // values: length
526 // default: 8pt
528 // We don't allow negative values.
529 // Unitless and percent values give a multiple of the default value.
531 value = aAttributes->GetAttr(nsGkAtoms::scriptminsize_);
532 nsCSSValue* scriptMinSize = aData->ValueForScriptMinSize();
533 if (value && value->Type() == nsAttrValue::eString &&
534 scriptMinSize->GetUnit() == eCSSUnit_Null) {
535 ParseNumericValue(value->GetStringValue(), *scriptMinSize,
536 PARSE_ALLOW_UNITLESS | CONVERT_UNITLESS_TO_PERCENT,
537 aData->mPresContext->Document());
539 if (scriptMinSize->GetUnit() == eCSSUnit_Percent) {
540 scriptMinSize->SetFloatValue(8.0 * scriptMinSize->GetPercentValue(),
541 eCSSUnit_Point);
545 // scriptlevel
547 // "Changes the scriptlevel in effect for the children. When the value is
548 // given without a sign, it sets scriptlevel to the specified value; when a
549 // sign is given, it increments ("+") or decrements ("-") the current
550 // value. (Note that large decrements can result in negative values of
551 // scriptlevel, but these values are considered legal.)"
553 // values: ( "+" | "-" )? unsigned-integer
554 // default: inherited
556 value = aAttributes->GetAttr(nsGkAtoms::scriptlevel_);
557 nsCSSValue* scriptLevel = aData->ValueForScriptLevel();
558 if (value && value->Type() == nsAttrValue::eString &&
559 scriptLevel->GetUnit() == eCSSUnit_Null) {
560 nsAutoString str(value->GetStringValue());
561 str.CompressWhitespace();
562 if (str.Length() > 0) {
563 nsresult errorCode;
564 int32_t intValue = str.ToInteger(&errorCode);
565 if (NS_SUCCEEDED(errorCode)) {
566 // This is kind of cheesy ... if the scriptlevel has a sign,
567 // then it's a relative value and we store the nsCSSValue as an
568 // Integer to indicate that. Otherwise we store it as a Number
569 // to indicate that the scriptlevel is absolute.
570 char16_t ch = str.CharAt(0);
571 if (ch == '+' || ch == '-') {
572 scriptLevel->SetIntValue(intValue, eCSSUnit_Integer);
573 } else {
574 scriptLevel->SetFloatValue(intValue, eCSSUnit_Number);
576 } else {
577 ReportParseErrorNoTag(str,
578 nsGkAtoms::scriptlevel_,
579 aData->mPresContext->Document());
584 // mathsize
586 // "Specifies the size to display the token content. The values 'small' and
587 // 'big' choose a size smaller or larger than the current font size, but
588 // leave the exact proportions unspecified; 'normal' is allowed for
589 // completeness, but since it is equivalent to '100%' or '1em', it has no
590 // effect."
592 // values: "small" | "normal" | "big" | length
593 // default: inherited
595 // fontsize
597 // "Specified the size for the token. Deprecated in favor of mathsize."
599 // values: length
600 // default: inherited
602 // In both cases, we don't allow negative values.
603 // Unitless values give a multiple of the default value.
605 bool parseSizeKeywords = true;
606 value = aAttributes->GetAttr(nsGkAtoms::mathsize_);
607 if (!value) {
608 parseSizeKeywords = false;
609 value = aAttributes->GetAttr(nsGkAtoms::fontsize_);
610 if (value) {
611 WarnDeprecated(nsGkAtoms::fontsize_->GetUTF16String(),
612 nsGkAtoms::mathsize_->GetUTF16String(),
613 aData->mPresContext->Document());
616 nsCSSValue* fontSize = aData->ValueForFontSize();
617 if (value && value->Type() == nsAttrValue::eString &&
618 fontSize->GetUnit() == eCSSUnit_Null) {
619 nsAutoString str(value->GetStringValue());
620 if (!ParseNumericValue(str, *fontSize, PARSE_SUPPRESS_WARNINGS |
621 PARSE_ALLOW_UNITLESS | CONVERT_UNITLESS_TO_PERCENT,
622 nullptr)
623 && parseSizeKeywords) {
624 static const char sizes[3][7] = { "small", "normal", "big" };
625 static const int32_t values[MOZ_ARRAY_LENGTH(sizes)] = {
626 NS_STYLE_FONT_SIZE_SMALL, NS_STYLE_FONT_SIZE_MEDIUM,
627 NS_STYLE_FONT_SIZE_LARGE
629 str.CompressWhitespace();
630 for (uint32_t i = 0; i < ArrayLength(sizes); ++i) {
631 if (str.EqualsASCII(sizes[i])) {
632 fontSize->SetIntValue(values[i], eCSSUnit_Enumerated);
633 break;
639 // fontfamily
641 // "Should be the name of a font that may be available to a MathML renderer,
642 // or a CSS font specification; See Section 6.5 Using CSS with MathML and
643 // CSS for more information. Deprecated in favor of mathvariant."
645 // values: string
647 value = aAttributes->GetAttr(nsGkAtoms::fontfamily_);
648 nsCSSValue* fontFamily = aData->ValueForFontFamily();
649 if (value) {
650 WarnDeprecated(nsGkAtoms::fontfamily_->GetUTF16String(),
651 nsGkAtoms::mathvariant_->GetUTF16String(),
652 aData->mPresContext->Document());
654 if (value && value->Type() == nsAttrValue::eString &&
655 fontFamily->GetUnit() == eCSSUnit_Null) {
656 nsCSSParser parser;
657 parser.ParseFontFamilyListString(value->GetStringValue(),
658 nullptr, 0, *fontFamily);
661 // fontstyle
663 // "Specified the font style to use for the token. Deprecated in favor of
664 // mathvariant."
666 // values: "normal" | "italic"
667 // default: normal (except on <mi>)
669 // Note that the font-style property is reset in layout/style/ when
670 // -moz-math-variant is specified.
671 nsCSSValue* fontStyle = aData->ValueForFontStyle();
672 value = aAttributes->GetAttr(nsGkAtoms::fontstyle_);
673 if (value) {
674 WarnDeprecated(nsGkAtoms::fontstyle_->GetUTF16String(),
675 nsGkAtoms::mathvariant_->GetUTF16String(),
676 aData->mPresContext->Document());
677 if (value->Type() == nsAttrValue::eString &&
678 fontStyle->GetUnit() == eCSSUnit_Null) {
679 nsAutoString str(value->GetStringValue());
680 str.CompressWhitespace();
681 if (str.EqualsASCII("normal")) {
682 fontStyle->SetIntValue(NS_STYLE_FONT_STYLE_NORMAL,
683 eCSSUnit_Enumerated);
684 } else if (str.EqualsASCII("italic")) {
685 fontStyle->SetIntValue(NS_STYLE_FONT_STYLE_ITALIC,
686 eCSSUnit_Enumerated);
691 // fontweight
693 // "Specified the font weight for the token. Deprecated in favor of
694 // mathvariant."
696 // values: "normal" | "bold"
697 // default: normal
699 // Note that the font-weight property is reset in layout/style/ when
700 // -moz-math-variant is specified.
701 nsCSSValue* fontWeight = aData->ValueForFontWeight();
702 value = aAttributes->GetAttr(nsGkAtoms::fontweight_);
703 if (value) {
704 WarnDeprecated(nsGkAtoms::fontweight_->GetUTF16String(),
705 nsGkAtoms::mathvariant_->GetUTF16String(),
706 aData->mPresContext->Document());
707 if (value->Type() == nsAttrValue::eString &&
708 fontWeight->GetUnit() == eCSSUnit_Null) {
709 nsAutoString str(value->GetStringValue());
710 str.CompressWhitespace();
711 if (str.EqualsASCII("normal")) {
712 fontWeight->SetIntValue(NS_STYLE_FONT_WEIGHT_NORMAL,
713 eCSSUnit_Enumerated);
714 } else if (str.EqualsASCII("bold")) {
715 fontWeight->SetIntValue(NS_STYLE_FONT_WEIGHT_BOLD,
716 eCSSUnit_Enumerated);
721 // mathvariant
723 // "Specifies the logical class of the token. Note that this class is more
724 // than styling, it typically conveys semantic intent;"
726 // values: "normal" | "bold" | "italic" | "bold-italic" | "double-struck" |
727 // "bold-fraktur" | "script" | "bold-script" | "fraktur" | "sans-serif" |
728 // "bold-sans-serif" | "sans-serif-italic" | "sans-serif-bold-italic" |
729 // "monospace" | "initial" | "tailed" | "looped" | "stretched"
730 // default: normal (except on <mi>)
732 nsCSSValue* mathVariant = aData->ValueForMathVariant();
733 value = aAttributes->GetAttr(nsGkAtoms::mathvariant_);
734 if (value && value->Type() == nsAttrValue::eString &&
735 mathVariant->GetUnit() == eCSSUnit_Null) {
736 nsAutoString str(value->GetStringValue());
737 str.CompressWhitespace();
738 static const char sizes[19][23] = {
739 "normal", "bold", "italic", "bold-italic", "script", "bold-script",
740 "fraktur", "double-struck", "bold-fraktur", "sans-serif",
741 "bold-sans-serif", "sans-serif-italic", "sans-serif-bold-italic",
742 "monospace", "initial", "tailed", "looped", "stretched"
744 static const int32_t values[MOZ_ARRAY_LENGTH(sizes)] = {
745 NS_MATHML_MATHVARIANT_NORMAL, NS_MATHML_MATHVARIANT_BOLD,
746 NS_MATHML_MATHVARIANT_ITALIC, NS_MATHML_MATHVARIANT_BOLD_ITALIC,
747 NS_MATHML_MATHVARIANT_SCRIPT, NS_MATHML_MATHVARIANT_BOLD_SCRIPT,
748 NS_MATHML_MATHVARIANT_FRAKTUR, NS_MATHML_MATHVARIANT_DOUBLE_STRUCK,
749 NS_MATHML_MATHVARIANT_BOLD_FRAKTUR, NS_MATHML_MATHVARIANT_SANS_SERIF,
750 NS_MATHML_MATHVARIANT_BOLD_SANS_SERIF,
751 NS_MATHML_MATHVARIANT_SANS_SERIF_ITALIC,
752 NS_MATHML_MATHVARIANT_SANS_SERIF_BOLD_ITALIC,
753 NS_MATHML_MATHVARIANT_MONOSPACE, NS_MATHML_MATHVARIANT_INITIAL,
754 NS_MATHML_MATHVARIANT_TAILED, NS_MATHML_MATHVARIANT_LOOPED,
755 NS_MATHML_MATHVARIANT_STRETCHED
757 for (uint32_t i = 0; i < ArrayLength(sizes); ++i) {
758 if (str.EqualsASCII(sizes[i])) {
759 mathVariant->SetIntValue(values[i], eCSSUnit_Enumerated);
760 break;
766 // mathbackground
768 // "Specifies the background color to be used to fill in the bounding box of
769 // the element and its children. The default, 'transparent', lets the
770 // background color, if any, used in the current rendering context to show
771 // through."
773 // values: color | "transparent"
774 // default: "transparent"
776 // background
778 // "Specified the background color to be used to fill in the bounding box of
779 // the element and its children. Deprecated in favor of mathbackground."
781 // values: color | "transparent"
782 // default: "transparent"
784 if (aData->mSIDs & NS_STYLE_INHERIT_BIT(Background)) {
785 const nsAttrValue* value =
786 aAttributes->GetAttr(nsGkAtoms::mathbackground_);
787 if (!value) {
788 value = aAttributes->GetAttr(nsGkAtoms::background);
789 if (value) {
790 WarnDeprecated(nsGkAtoms::background->GetUTF16String(),
791 nsGkAtoms::mathbackground_->GetUTF16String(),
792 aData->mPresContext->Document());
795 nsCSSValue* backgroundColor = aData->ValueForBackgroundColor();
796 if (value && backgroundColor->GetUnit() == eCSSUnit_Null) {
797 nscolor color;
798 if (value->GetColorValue(color)) {
799 backgroundColor->SetColorValue(color);
804 // mathcolor
806 // "Specifies the foreground color to use when drawing the components of this
807 // element, such as the content for token elements or any lines, surds, or
808 // other decorations. It also establishes the default mathcolor used for
809 // child elements when used on a layout element."
811 // values: color
812 // default: inherited
814 // color
816 // "Specified the color for the token. Deprecated in favor of mathcolor."
818 // values: color
819 // default: inherited
821 if (aData->mSIDs & NS_STYLE_INHERIT_BIT(Color)) {
822 const nsAttrValue* value = aAttributes->GetAttr(nsGkAtoms::mathcolor_);
823 if (!value) {
824 value = aAttributes->GetAttr(nsGkAtoms::color);
825 if (value) {
826 WarnDeprecated(nsGkAtoms::color->GetUTF16String(),
827 nsGkAtoms::mathcolor_->GetUTF16String(),
828 aData->mPresContext->Document());
831 nscolor color;
832 nsCSSValue* colorValue = aData->ValueForColor();
833 if (value && value->GetColorValue(color) &&
834 colorValue->GetUnit() == eCSSUnit_Null) {
835 colorValue->SetColorValue(color);
839 if (aData->mSIDs & NS_STYLE_INHERIT_BIT(Position)) {
840 // width
842 // "Specifies the desired width of the entire table and is intended for
843 // visual user agents. When the value is a percentage value, the value is
844 // relative to the horizontal space a MathML renderer has available for the
845 // math element. When the value is "auto", the MathML renderer should
846 // calculate the table width from its contents using whatever layout
847 // algorithm it chooses. "
849 // values: "auto" | length
850 // default: auto
852 nsCSSValue* width = aData->ValueForWidth();
853 if (width->GetUnit() == eCSSUnit_Null) {
854 const nsAttrValue* value = aAttributes->GetAttr(nsGkAtoms::width);
855 // This does not handle auto and unitless values
856 if (value && value->Type() == nsAttrValue::eString) {
857 ParseNumericValue(value->GetStringValue(), *width, 0,
858 aData->mPresContext->Document());
863 // dir
865 // Overall Directionality of Mathematics Formulas:
866 // "The overall directionality for a formula, basically the direction of the
867 // Layout Schemata, is specified by the dir attribute on the containing math
868 // element (see Section 2.2 The Top-Level math Element). The default is ltr.
869 // [...] The overall directionality is usually set on the math, but may also
870 // be switched for individual subformula by using the dir attribute on mrow
871 // or mstyle elements."
873 // Bidirectional Layout in Token Elements:
874 // "Specifies the initial directionality for text within the token:
875 // ltr (Left To Right) or rtl (Right To Left). This attribute should only be
876 // needed in rare cases involving weak or neutral characters;
877 // see Section 3.1.5.1 Overall Directionality of Mathematics Formulas for
878 // further discussion. It has no effect on mspace."
880 // values: "ltr" | "rtl"
881 // default: inherited
883 if (aData->mSIDs & NS_STYLE_INHERIT_BIT(Visibility)) {
884 const nsAttrValue* value = aAttributes->GetAttr(nsGkAtoms::dir);
885 nsCSSValue* direction = aData->ValueForDirection();
886 if (value && value->Type() == nsAttrValue::eString &&
887 direction->GetUnit() == eCSSUnit_Null) {
888 nsAutoString str(value->GetStringValue());
889 static const char dirs[][4] = { "ltr", "rtl" };
890 static const int32_t dirValues[MOZ_ARRAY_LENGTH(dirs)] = {
891 NS_STYLE_DIRECTION_LTR, NS_STYLE_DIRECTION_RTL
893 for (uint32_t i = 0; i < ArrayLength(dirs); ++i) {
894 if (str.EqualsASCII(dirs[i])) {
895 direction->SetIntValue(dirValues[i], eCSSUnit_Enumerated);
896 break;
903 nsresult
904 nsMathMLElement::PreHandleEvent(EventChainPreVisitor& aVisitor)
906 nsresult rv = Element::PreHandleEvent(aVisitor);
907 NS_ENSURE_SUCCESS(rv, rv);
909 return PreHandleEventForLinks(aVisitor);
912 nsresult
913 nsMathMLElement::PostHandleEvent(EventChainPostVisitor& aVisitor)
915 return PostHandleEventForLinks(aVisitor);
918 NS_IMPL_ELEMENT_CLONE(nsMathMLElement)
920 EventStates
921 nsMathMLElement::IntrinsicState() const
923 return Link::LinkState() | nsMathMLElementBase::IntrinsicState() |
924 (mIncrementScriptLevel ?
925 NS_EVENT_STATE_INCREMENT_SCRIPT_LEVEL : EventStates());
928 bool
929 nsMathMLElement::IsNodeOfType(uint32_t aFlags) const
931 return !(aFlags & ~eCONTENT);
934 void
935 nsMathMLElement::SetIncrementScriptLevel(bool aIncrementScriptLevel,
936 bool aNotify)
938 if (aIncrementScriptLevel == mIncrementScriptLevel)
939 return;
940 mIncrementScriptLevel = aIncrementScriptLevel;
942 NS_ASSERTION(aNotify, "We always notify!");
944 UpdateState(true);
947 bool
948 nsMathMLElement::IsFocusableInternal(int32_t* aTabIndex, bool aWithMouse)
950 nsCOMPtr<nsIURI> uri;
951 if (IsLink(getter_AddRefs(uri))) {
952 if (aTabIndex) {
953 *aTabIndex = ((sTabFocusModel & eTabFocus_linksMask) == 0 ? -1 : 0);
955 return true;
958 if (aTabIndex) {
959 *aTabIndex = -1;
962 return false;
965 bool
966 nsMathMLElement::IsLink(nsIURI** aURI) const
968 // http://www.w3.org/TR/2010/REC-MathML3-20101021/chapter6.html#interf.link
969 // The REC says that the following elements should not be linking elements:
970 nsIAtom* tag = Tag();
971 if (tag == nsGkAtoms::mprescripts_ ||
972 tag == nsGkAtoms::none ||
973 tag == nsGkAtoms::malignmark_ ||
974 tag == nsGkAtoms::maligngroup_) {
975 *aURI = nullptr;
976 return false;
979 bool hasHref = false;
980 const nsAttrValue* href = mAttrsAndChildren.GetAttr(nsGkAtoms::href,
981 kNameSpaceID_None);
982 if (href) {
983 // MathML href
984 // The REC says: "When user agents encounter MathML elements with both href
985 // and xlink:href attributes, the href attribute should take precedence."
986 hasHref = true;
987 } else {
988 // To be a clickable XLink for styling and interaction purposes, we require:
990 // xlink:href - must be set
991 // xlink:type - must be unset or set to "" or set to "simple"
992 // xlink:show - must be unset or set to "", "new" or "replace"
993 // xlink:actuate - must be unset or set to "" or "onRequest"
995 // For any other values, we're either not a *clickable* XLink, or the end
996 // result is poorly specified. Either way, we return false.
998 static nsIContent::AttrValuesArray sTypeVals[] =
999 { &nsGkAtoms::_empty, &nsGkAtoms::simple, nullptr };
1001 static nsIContent::AttrValuesArray sShowVals[] =
1002 { &nsGkAtoms::_empty, &nsGkAtoms::_new, &nsGkAtoms::replace, nullptr };
1004 static nsIContent::AttrValuesArray sActuateVals[] =
1005 { &nsGkAtoms::_empty, &nsGkAtoms::onRequest, nullptr };
1007 // Optimization: check for href first for early return
1008 href = mAttrsAndChildren.GetAttr(nsGkAtoms::href,
1009 kNameSpaceID_XLink);
1010 if (href &&
1011 FindAttrValueIn(kNameSpaceID_XLink, nsGkAtoms::type,
1012 sTypeVals, eCaseMatters) !=
1013 nsIContent::ATTR_VALUE_NO_MATCH &&
1014 FindAttrValueIn(kNameSpaceID_XLink, nsGkAtoms::show,
1015 sShowVals, eCaseMatters) !=
1016 nsIContent::ATTR_VALUE_NO_MATCH &&
1017 FindAttrValueIn(kNameSpaceID_XLink, nsGkAtoms::actuate,
1018 sActuateVals, eCaseMatters) !=
1019 nsIContent::ATTR_VALUE_NO_MATCH) {
1020 hasHref = true;
1024 if (hasHref) {
1025 nsCOMPtr<nsIURI> baseURI = GetBaseURI();
1026 // Get absolute URI
1027 nsAutoString hrefStr;
1028 href->ToString(hrefStr);
1029 nsContentUtils::NewURIWithDocumentCharset(aURI, hrefStr,
1030 OwnerDoc(), baseURI);
1031 // must promise out param is non-null if we return true
1032 return !!*aURI;
1035 *aURI = nullptr;
1036 return false;
1039 void
1040 nsMathMLElement::GetLinkTarget(nsAString& aTarget)
1042 const nsAttrValue* target = mAttrsAndChildren.GetAttr(nsGkAtoms::target,
1043 kNameSpaceID_XLink);
1044 if (target) {
1045 target->ToString(aTarget);
1048 if (aTarget.IsEmpty()) {
1050 static nsIContent::AttrValuesArray sShowVals[] =
1051 { &nsGkAtoms::_new, &nsGkAtoms::replace, nullptr };
1053 switch (FindAttrValueIn(kNameSpaceID_XLink, nsGkAtoms::show,
1054 sShowVals, eCaseMatters)) {
1055 case 0:
1056 aTarget.AssignLiteral("_blank");
1057 return;
1058 case 1:
1059 return;
1061 OwnerDoc()->GetBaseTarget(aTarget);
1065 already_AddRefed<nsIURI>
1066 nsMathMLElement::GetHrefURI() const
1068 nsCOMPtr<nsIURI> hrefURI;
1069 return IsLink(getter_AddRefs(hrefURI)) ? hrefURI.forget() : nullptr;
1072 nsresult
1073 nsMathMLElement::SetAttr(int32_t aNameSpaceID, nsIAtom* aName,
1074 nsIAtom* aPrefix, const nsAString& aValue,
1075 bool aNotify)
1077 nsresult rv = nsMathMLElementBase::SetAttr(aNameSpaceID, aName, aPrefix,
1078 aValue, aNotify);
1080 // The ordering of the parent class's SetAttr call and Link::ResetLinkState
1081 // is important here! The attribute is not set until SetAttr returns, and
1082 // we will need the updated attribute value because notifying the document
1083 // that content states have changed will call IntrinsicState, which will try
1084 // to get updated information about the visitedness from Link.
1085 if (aName == nsGkAtoms::href &&
1086 (aNameSpaceID == kNameSpaceID_None ||
1087 aNameSpaceID == kNameSpaceID_XLink)) {
1088 if (aNameSpaceID == kNameSpaceID_XLink) {
1089 WarnDeprecated(MOZ_UTF16("xlink:href"),
1090 MOZ_UTF16("href"), OwnerDoc());
1092 Link::ResetLinkState(!!aNotify, true);
1095 return rv;
1098 nsresult
1099 nsMathMLElement::UnsetAttr(int32_t aNameSpaceID, nsIAtom* aAttr,
1100 bool aNotify)
1102 nsresult rv = nsMathMLElementBase::UnsetAttr(aNameSpaceID, aAttr, aNotify);
1104 // The ordering of the parent class's UnsetAttr call and Link::ResetLinkState
1105 // is important here! The attribute is not unset until UnsetAttr returns, and
1106 // we will need the updated attribute value because notifying the document
1107 // that content states have changed will call IntrinsicState, which will try
1108 // to get updated information about the visitedness from Link.
1109 if (aAttr == nsGkAtoms::href &&
1110 (aNameSpaceID == kNameSpaceID_None ||
1111 aNameSpaceID == kNameSpaceID_XLink)) {
1112 // Note: just because we removed a single href attr doesn't mean there's no href,
1113 // since there are 2 possible namespaces.
1114 Link::ResetLinkState(!!aNotify, Link::ElementHasHref());
1117 return rv;
1120 JSObject*
1121 nsMathMLElement::WrapNode(JSContext *aCx)
1123 return ElementBinding::Wrap(aCx, this);