diff --git a/accessible/base/TextAttrs.cpp b/accessible/base/TextAttrs.cpp index c4bb300b5bc8..0f4d16bbf130 100644 --- a/accessible/base/TextAttrs.cpp +++ b/accessible/base/TextAttrs.cpp @@ -501,14 +501,11 @@ void TextAttrsMgr::FontStyleTextAttr::ExposeValue( RefPtr atom = NS_Atomize("italic"); aAttributes->SetAttribute(nsGkAtoms::font_style, atom); } else { - auto angle = aValue.ObliqueAngle(); - nsString string(u"oblique"_ns); - if (angle != FontSlantStyle::kDefaultAngle) { - string.AppendLiteral(" "); - nsStyleUtil::AppendCSSNumber(angle, string); - string.AppendLiteral("deg"); - } - aAttributes->SetAttribute(nsGkAtoms::font_style, std::move(string)); + nsAutoCString s; + aValue.ToString(s); + nsString wide; + CopyUTF8toUTF16(s, wide); + aAttributes->SetAttribute(nsGkAtoms::font_style, std::move(wide)); } } @@ -543,7 +540,8 @@ bool TextAttrsMgr::FontWeightTextAttr::GetValueFor(LocalAccessible* aAccessible, void TextAttrsMgr::FontWeightTextAttr::ExposeValue(AccAttributes* aAttributes, const FontWeight& aValue) { - aAttributes->SetAttribute(nsGkAtoms::fontWeight, aValue.ToIntRounded()); + int value = aValue.ToIntRounded(); + aAttributes->SetAttribute(nsGkAtoms::fontWeight, value); } FontWeight TextAttrsMgr::FontWeightTextAttr::GetFontWeight(nsIFrame* aFrame) { @@ -560,7 +558,7 @@ FontWeight TextAttrsMgr::FontWeightTextAttr::GetFontWeight(nsIFrame* aFrame) { // bold font, i.e. synthetic bolding is used. (Simply returns false on any // platforms that don't use the multi-strike synthetic bolding.) if (font->ApplySyntheticBold()) { - return FontWeight::Bold(); + return FontWeight::BOLD; } // On Windows, font->GetStyle()->weight will give the same weight as diff --git a/build/moz.configure/bindgen.configure b/build/moz.configure/bindgen.configure index 02b4ba818900..77ae4cab0e5b 100644 --- a/build/moz.configure/bindgen.configure +++ b/build/moz.configure/bindgen.configure @@ -22,7 +22,7 @@ option(env="CBINDGEN", nargs=1, when=cbindgen_is_needed, help="Path to cbindgen" def check_cbindgen_version(cbindgen, fatal=False): log.debug("trying cbindgen: %s" % cbindgen) - cbindgen_min_version = Version("0.24.2") + cbindgen_min_version = Version("0.24.3") # cbindgen x.y.z version = Version(check_cmd_output(cbindgen, "--version").strip().split(" ")[1]) diff --git a/dom/canvas/OffscreenCanvasRenderingContext2D.cpp b/dom/canvas/OffscreenCanvasRenderingContext2D.cpp index 9eece4a5e3fd..400a9f8ba311 100644 --- a/dom/canvas/OffscreenCanvasRenderingContext2D.cpp +++ b/dom/canvas/OffscreenCanvasRenderingContext2D.cpp @@ -101,15 +101,9 @@ static void SerializeFontForCanvas(const StyleFontFamilyList& aList, // Re-serialize the font shorthand as required by the canvas spec. aUsedFont.Truncate(); - if (aStyle.style.IsItalic()) { - aUsedFont.Append("italic "); - } else if (aStyle.style.IsOblique()) { - aUsedFont.Append("oblique "); - // Include the angle if it is not the default font-style:oblique value. - if (aStyle.style != FontSlantStyle::Oblique()) { - aUsedFont.AppendFloat(aStyle.style.ObliqueAngle()); - aUsedFont.Append("deg "); - } + if (!aStyle.style.IsNormal()) { + aStyle.style.ToString(aUsedFont); + aUsedFont.Append(" "); } // font-weight is serialized as a number @@ -118,24 +112,9 @@ static void SerializeFontForCanvas(const StyleFontFamilyList& aList, } // font-stretch is serialized using CSS Fonts 3 keywords, not percentages. - if (!aStyle.stretch.IsNormal()) { - if (aStyle.stretch == FontStretch::UltraCondensed()) { - aUsedFont.Append("ultra-condensed "); - } else if (aStyle.stretch == FontStretch::ExtraCondensed()) { - aUsedFont.Append("extra-condensed "); - } else if (aStyle.stretch == FontStretch::Condensed()) { - aUsedFont.Append("condensed "); - } else if (aStyle.stretch == FontStretch::SemiCondensed()) { - aUsedFont.Append("semi-condensed "); - } else if (aStyle.stretch == FontStretch::SemiExpanded()) { - aUsedFont.Append("semi-expanded "); - } else if (aStyle.stretch == FontStretch::Expanded()) { - aUsedFont.Append("expanded "); - } else if (aStyle.stretch == FontStretch::ExtraExpanded()) { - aUsedFont.Append("extra-expanded "); - } else if (aStyle.stretch == FontStretch::UltraExpanded()) { - aUsedFont.Append("ultra-expanded "); - } + if (!aStyle.stretch.IsNormal() && + Servo_FontStretch_SerializeKeyword(&aStyle.stretch, &aUsedFont)) { + aUsedFont.Append(" "); } // Serialize the computed (not specified) size, and the family name(s). @@ -149,31 +128,18 @@ bool OffscreenCanvasRenderingContext2D::SetFontInternal(const nsACString& aFont, // In the OffscreenCanvas case we don't have the context necessary to call // GetFontStyleForServo(), as we do in the main-thread canvas context, so // instead we borrow ParseFontShorthandForMatching to parse the attribute. - float stretch = FontStretch::Normal().Percentage(), - weight = FontWeight::Normal().ToFloat(), size = 10.0; StyleComputedFontStyleDescriptor style( StyleComputedFontStyleDescriptor::Normal()); StyleFontFamilyList list; + gfxFontStyle fontStyle; + float size = 0.0f; if (!ServoCSSParser::ParseFontShorthandForMatching( - aFont, nullptr, list, style, stretch, weight, &size)) { + aFont, nullptr, list, fontStyle.style, fontStyle.stretch, + fontStyle.weight, &size)) { return false; } - gfxFontStyle fontStyle; fontStyle.size = size; - fontStyle.weight = FontWeight(weight); - fontStyle.stretch = FontStretch::FromStyle(stretch); - switch (style.tag) { - case StyleComputedFontStyleDescriptor::Tag::Normal: - fontStyle.style = FontSlantStyle::Normal(); - break; - case StyleComputedFontStyleDescriptor::Tag::Italic: - fontStyle.style = FontSlantStyle::Italic(); - break; - case StyleComputedFontStyleDescriptor::Tag::Oblique: - fontStyle.style = FontSlantStyle::Oblique(style.AsOblique()._0); - break; - } // TODO: Get a userFontSet from the Worker and pass to the fontGroup // TODO: Should we be passing a language? Where from? @@ -189,9 +155,8 @@ bool OffscreenCanvasRenderingContext2D::SetFontInternal(const nsACString& aFont, 1.0); // aDevToCssSize CurrentState().fontGroup = fontGroup; SerializeFontForCanvas(list, fontStyle, CurrentState().font); - CurrentState().fontFont = - nsFont(StyleFontFamily{list, false, false}, - StyleCSSPixelLength::FromPixels(float(fontStyle.size))); + CurrentState().fontFont = nsFont(StyleFontFamily{list, false, false}, + StyleCSSPixelLength::FromPixels(size)); CurrentState().fontLanguage = nullptr; CurrentState().fontExplicitLanguage = false; return true; diff --git a/dom/mathml/MathMLElement.cpp b/dom/mathml/MathMLElement.cpp index 6a532c92dc22..1a6eee57d5ec 100644 --- a/dom/mathml/MathMLElement.cpp +++ b/dom/mathml/MathMLElement.cpp @@ -591,10 +591,10 @@ void MathMLElement::MapMathMLAttributesInto( str.CompressWhitespace(); if (str.EqualsASCII("normal")) { aDecls.SetKeywordValue(eCSSProperty_font_weight, - FontWeight::Normal().ToFloat()); + FontWeight::NORMAL.ToFloat()); } else if (str.EqualsASCII("bold")) { aDecls.SetKeywordValue(eCSSProperty_font_weight, - FontWeight::Bold().ToFloat()); + FontWeight::BOLD.ToFloat()); } } } diff --git a/gfx/2d/ScaledFontDWrite.cpp b/gfx/2d/ScaledFontDWrite.cpp index 6da61de23672..851c0aff89fb 100644 --- a/gfx/2d/ScaledFontDWrite.cpp +++ b/gfx/2d/ScaledFontDWrite.cpp @@ -5,6 +5,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ScaledFontDWrite.h" +#include "gfxDWriteCommon.h" #include "UnscaledFontDWrite.h" #include "PathD2D.h" #include "gfxFont.h" @@ -86,38 +87,6 @@ static bool DoGrayscale(IDWriteFontFace* aDWFace, Float ppem) { return true; } -static inline DWRITE_FONT_STRETCH DWriteFontStretchFromStretch( - FontStretch aStretch) { - if (aStretch == FontStretch::UltraCondensed()) { - return DWRITE_FONT_STRETCH_ULTRA_CONDENSED; - } - if (aStretch == FontStretch::ExtraCondensed()) { - return DWRITE_FONT_STRETCH_EXTRA_CONDENSED; - } - if (aStretch == FontStretch::Condensed()) { - return DWRITE_FONT_STRETCH_CONDENSED; - } - if (aStretch == FontStretch::SemiCondensed()) { - return DWRITE_FONT_STRETCH_SEMI_CONDENSED; - } - if (aStretch == FontStretch::Normal()) { - return DWRITE_FONT_STRETCH_NORMAL; - } - if (aStretch == FontStretch::SemiExpanded()) { - return DWRITE_FONT_STRETCH_SEMI_EXPANDED; - } - if (aStretch == FontStretch::Expanded()) { - return DWRITE_FONT_STRETCH_EXPANDED; - } - if (aStretch == FontStretch::ExtraExpanded()) { - return DWRITE_FONT_STRETCH_EXTRA_EXPANDED; - } - if (aStretch == FontStretch::UltraExpanded()) { - return DWRITE_FONT_STRETCH_ULTRA_EXPANDED; - } - return DWRITE_FONT_STRETCH_UNDEFINED; -} - ScaledFontDWrite::ScaledFontDWrite(IDWriteFontFace* aFontFace, const RefPtr& aUnscaledFont, Float aSize, bool aUseEmbeddedBitmap, @@ -132,7 +101,7 @@ ScaledFontDWrite::ScaledFontDWrite(IDWriteFontFace* aFontFace, mStyle = SkFontStyle(aStyle->weight.ToIntRounded(), DWriteFontStretchFromStretch(aStyle->stretch), // FIXME(jwatt): also use kOblique_Slant - aStyle->style == FontSlantStyle::Normal() + aStyle->style == FontSlantStyle::NORMAL ? SkFontStyle::kUpright_Slant : SkFontStyle::kItalic_Slant); } diff --git a/gfx/src/FontPropertyTypes.h b/gfx/src/FontPropertyTypes.h index 9da6ab939145..fe4f1f06e4bb 100644 --- a/gfx/src/FontPropertyTypes.h +++ b/gfx/src/FontPropertyTypes.h @@ -18,7 +18,7 @@ #include #include "mozilla/Assertions.h" -#include "mozilla/TextUtils.h" +#include "mozilla/ServoStyleConsts.h" #include "nsString.h" /* @@ -28,309 +28,9 @@ namespace mozilla { -/** - * Generic template for font property type classes that use a fixed-point - * internal representation. - * Template parameters: - * InternalType - the integer type to use as the internal representation (e.g. - * uint16_t) - * * NOTE that T must NOT be plain /int/, as that would result in - * ambiguity between constructors from /int/ and /T/, which mean - * different things. - * FractionBits - number of bits to use for the fractional part - * Min, Max - [inclusive] limits to the range of values that may be stored - * Values are constructed from and exposed as floating-point, but stored - * internally as fixed point, so there will be a quantization effect on - * fractional values, depending on the number of fractional bits used. - * Using (16-bit) fixed-point types rather than floats for these style - * attributes reduces the memory footprint of gfxFontEntry and gfxFontStyle; - * it will also tend to reduce the number of distinct font instances that - * get created, particularly when styles are animated or set to arbitrary - * values (e.g. by sliders in the UI), which should reduce pressure on - * graphics resources and improve cache hit rates. - */ -template -class FontPropertyValue { - public: - // Initialize to the minimum value by default. - constexpr FontPropertyValue() : FontPropertyValue(Min) {} - - explicit FontPropertyValue(const FontPropertyValue& aOther) = default; - FontPropertyValue& operator=(const FontPropertyValue& aOther) = default; - - bool operator==(const FontPropertyValue& aOther) const { - return mValue == aOther.mValue; - } - bool operator!=(const FontPropertyValue& aOther) const { - return mValue != aOther.mValue; - } - bool operator<(const FontPropertyValue& aOther) const { - return mValue < aOther.mValue; - } - bool operator>(const FontPropertyValue& aOther) const { - return mValue > aOther.mValue; - } - bool operator<=(const FontPropertyValue& aOther) const { - return mValue <= aOther.mValue; - } - bool operator>=(const FontPropertyValue& aOther) const { - return mValue >= aOther.mValue; - } - - // The difference between two values, returned as a raw floating-point number - // (which might not be a valid property value in its own right). - float operator-(const FontPropertyValue& aOther) const { - return (mValue - aOther.mValue) * kInverseScale; - } - - /// Return the raw internal representation, for purposes of hashing. - /// (Do not try to interpret the numeric value of this.) - uint16_t ForHash() const { return uint16_t(mValue); } - - static constexpr const float kMin = float(Min); - static constexpr const float kMax = float(Max); - - protected: - // Construct from a floating-point or integer value, checking that it is - // within the allowed range and converting to fixed-point representation. - explicit constexpr FontPropertyValue(float aValue) - : mValue(std::round(aValue * kScale)) { - MOZ_ASSERT(aValue >= kMin && aValue <= kMax); - } - explicit constexpr FontPropertyValue(int aValue) - : mValue(static_cast(aValue * kScale)) { - MOZ_ASSERT(aValue >= Min && aValue <= Max); - } - - // Construct directly from a fixed-point value of type T, with no check; - // note that there may be special "flag" values that are outside the normal - // min/max range (e.g. for font-style:italic, distinct from oblique angle). - explicit constexpr FontPropertyValue(InternalType aValue) : mValue(aValue) {} - - // This is protected as it may not be the most appropriate accessor for a - // given instance to expose. It's up to each individual property to provide - // public accessors that forward to this as required. - float ToFloat() const { return mValue * kInverseScale; } - int ToIntRounded() const { return (mValue + kPointFive) >> FractionBits; } - - static constexpr int kScale = 1 << FractionBits; - static constexpr float kInverseScale = 1.0f / kScale; - static const unsigned kFractionBits = FractionBits; - - // Constant representing 0.5 in the internal representation (note this - // assumes that kFractionBits is greater than zero!) - static const InternalType kPointFive = 1u << (kFractionBits - 1); - - InternalType mValue; -}; - -/** - * font-weight: range 1..1000, fractional values permitted; keywords - * 'normal', 'bold' aliased to 400, 700 respectively; relative keywords - * 'lighter', 'bolder' (not currently handled here). - * - * We use an unsigned 10.6 fixed-point value (range 0.0 - 1023.984375) - */ -class FontWeight final : public FontPropertyValue { - public: - constexpr FontWeight() = default; - - explicit constexpr FontWeight(float aValue) : FontPropertyValue(aValue) {} - - /** - * CSS font weights can have fractional values, but this constructor exists - * for convenience when writing constants such as FontWeight(700) in code. - */ - explicit constexpr FontWeight(int aValue) : FontPropertyValue(aValue) {} - - static constexpr FontWeight Normal() { return FontWeight(kNormal); } - - static constexpr FontWeight Thin() { return FontWeight(kThin); } - - static constexpr FontWeight Bold() { return FontWeight(kBold); } - - bool IsNormal() const { return mValue == kNormal; } - bool IsBold() const { return mValue >= kBoldThreshold; } - - float ToFloat() const { return FontPropertyValue::ToFloat(); } - int ToIntRounded() const { return FontPropertyValue::ToIntRounded(); } - - typedef uint16_t InternalType; - - private: - friend class WeightRange; - - explicit constexpr FontWeight(InternalType aValue) - : FontPropertyValue(aValue) {} - - static const InternalType kNormal = 400u << kFractionBits; - static const InternalType kBold = 700u << kFractionBits; - static const InternalType kBoldThreshold = 600u << kFractionBits; - static const InternalType kThin = 100u << kFractionBits; - static const InternalType kExtraBold = 900u << kFractionBits; -}; - -/** - * font-stretch is represented as a percentage relative to 'normal'. - * - * css-fonts says the value must be >= 0%, and normal is 100%. Keywords - * from ultra-condensed to ultra-expanded are aliased to percentages - * from 50% to 200%; values outside that range are unlikely to be common, - * but could occur. - * - * Like font-weight, we use an unsigned 10.6 fixed-point value (range - * 0.0 - 1023.984375). - * - * We arbitrarily limit here to 1000%. (If that becomes a problem, we - * could reduce the number of fractional bits and increase the limit.) - */ -class FontStretch final : public FontPropertyValue { - public: - constexpr FontStretch() = default; - - explicit constexpr FontStretch(float aPercent) - : FontPropertyValue(aPercent) {} - - static constexpr FontStretch Normal() { return FontStretch(kNormal); } - static constexpr FontStretch UltraCondensed() { - return FontStretch(kUltraCondensed); - } - static constexpr FontStretch ExtraCondensed() { - return FontStretch(kExtraCondensed); - } - static constexpr FontStretch Condensed() { return FontStretch(kCondensed); } - static constexpr FontStretch SemiCondensed() { - return FontStretch(kSemiCondensed); - } - static constexpr FontStretch SemiExpanded() { - return FontStretch(kSemiExpanded); - } - static constexpr FontStretch Expanded() { return FontStretch(kExpanded); } - static constexpr FontStretch ExtraExpanded() { - return FontStretch(kExtraExpanded); - } - static constexpr FontStretch UltraExpanded() { - return FontStretch(kUltraExpanded); - } - - // The style system represents percentages in the 0.0..1.0 range, and - // FontStretch does it in the 0.0..100.0 range. - // - // TODO(emilio): We should consider changing this class to deal with the same - // range as the style system. - static FontStretch FromStyle(float aStylePercentage) { - return FontStretch(std::min(aStylePercentage * 100.0f, float(kMax))); - } - - bool IsNormal() const { return mValue == kNormal; } - float Percentage() const { return ToFloat(); } - - typedef uint16_t InternalType; - - private: - friend class StretchRange; - - explicit constexpr FontStretch(InternalType aValue) - : FontPropertyValue(aValue) {} - - static const InternalType kUltraCondensed = 50u << kFractionBits; - static const InternalType kExtraCondensed = - (62u << kFractionBits) + kPointFive; - static const InternalType kCondensed = 75u << kFractionBits; - static const InternalType kSemiCondensed = - (87u << kFractionBits) + kPointFive; - static const InternalType kNormal = 100u << kFractionBits; - static const InternalType kSemiExpanded = - (112u << kFractionBits) + kPointFive; - static const InternalType kExpanded = 125u << kFractionBits; - static const InternalType kExtraExpanded = 150u << kFractionBits; - static const InternalType kUltraExpanded = 200u << kFractionBits; -}; - -/** - * font-style: normal | italic | oblique ? - * values of below -90 or above 90 not permitted - * - Use a signed 8.8 fixed-point value - * (representable range -128.0 - 127.99609375) - * - Define min value (-128.0) as meaning 'normal' - * - Define max value (127.99609375) as 'italic' - * - Other values represent 'oblique ' - * - Note that 'oblique 0deg' is distinct from 'normal' (should it be?) - */ -class FontSlantStyle final : public FontPropertyValue { - public: - const static constexpr float kDefaultAngle = 14.0; - - constexpr FontSlantStyle() = default; - - static constexpr FontSlantStyle Normal() { return FontSlantStyle(kNormal); } - - static constexpr FontSlantStyle Italic() { return FontSlantStyle(kItalic); } - - static constexpr FontSlantStyle Oblique(float aAngle = kDefaultAngle) { - return FontSlantStyle(aAngle); - } - - // Create from a string as generated by ToString. This is for internal use - // when serializing/deserializing entries for the startupcache, and is not - // intended to parse arbitrary (untrusted) strings. - static FontSlantStyle FromString(const char* aString) { - if (strcmp(aString, "normal") == 0) { - return Normal(); - } - if (strcmp(aString, "italic") == 0) { - return Italic(); - } - if (mozilla::IsAsciiDigit(aString[0]) && strstr(aString, "deg")) { - float angle = strtof(aString, nullptr); - return Oblique(angle); - } - // Not recognized as an oblique angle; maybe it's from a startup-cache - // created by an older version. The style field there used a simple 0/1 - // for normal/italic respectively. - return aString[0] == '0' ? Normal() : Italic(); - } - - bool IsNormal() const { return mValue == kNormal; } - bool IsItalic() const { return mValue == kItalic; } - bool IsOblique() const { return mValue != kItalic && mValue != kNormal; } - - float ObliqueAngle() const { - // It's not meaningful to get the oblique angle from a style that is - // actually 'normal' or 'italic'. - MOZ_ASSERT(IsOblique()); - return ToFloat(); - } - - /** - * Write a string representation of the value to aOutString. - * - * NOTE that this APPENDS to the output string, it does not replace - * any existing contents. - */ - void ToString(nsACString& aOutString) const { - if (IsNormal()) { - aOutString.Append("normal"); - } else if (IsItalic()) { - aOutString.Append("italic"); - } else { - aOutString.AppendPrintf("%gdeg", ObliqueAngle()); - } - } - - typedef int16_t InternalType; - - private: - friend class SlantStyleRange; - - explicit constexpr FontSlantStyle(InternalType aConstant) - : FontPropertyValue(aConstant) {} - - explicit constexpr FontSlantStyle(float aAngle) : FontPropertyValue(aAngle) {} - - static const InternalType kNormal = INT16_MIN; - static const InternalType kItalic = INT16_MAX; -}; +using FontSlantStyle = StyleFontStyle; +using FontWeight = StyleFontWeight; +using FontStretch = StyleFontStretch; /** * Convenience type to hold a pair representing a range of values. @@ -338,7 +38,7 @@ class FontSlantStyle final : public FontPropertyValue { * The min and max are both inclusive, so when min == max the range represents * a single value (not an empty range). */ -template +template class FontPropertyRange { // This implementation assumes the underlying property type is a 16-bit value // (see FromScalar and AsScalar below). @@ -392,29 +92,22 @@ class FontPropertyRange { * * This depends on the underlying property type being a 16-bit value! */ - typedef uint32_t ScalarType; + using ScalarType = uint32_t; ScalarType AsScalar() const { - return (mValues.first.ForHash() << 16) | mValues.second.ForHash(); + return (mValues.first.UnsignedRaw() << 16) | mValues.second.UnsignedRaw(); } - /* - * FIXME: - * FromScalar is defined in each individual subclass, because I can't - * persuade the compiler to accept a definition here in the template. :\ - * - static FontPropertyRange FromScalar(ScalarType aScalar) - { - return FontPropertyRange(T(typename T::InternalType(aScalar >> 16)), - T(typename T::InternalType(aScalar & 0xffff))); + static Derived FromScalar(ScalarType aScalar) { + static_assert(std::is_base_of_v); + return Derived(T::FromRaw(aScalar >> 16), T::FromRaw(aScalar & 0xffff)); } - */ protected: std::pair mValues; }; -class WeightRange : public FontPropertyRange { +class WeightRange : public FontPropertyRange { public: WeightRange(FontWeight aMin, FontWeight aMax) : FontPropertyRange(aMin, aMax) {} @@ -430,14 +123,9 @@ class WeightRange : public FontPropertyRange { aOutString.AppendFloat(Max().ToFloat()); } } - - static WeightRange FromScalar(ScalarType aScalar) { - return WeightRange(FontWeight(FontWeight::InternalType(aScalar >> 16)), - FontWeight(FontWeight::InternalType(aScalar & 0xffff))); - } }; -class StretchRange : public FontPropertyRange { +class StretchRange : public FontPropertyRange { public: StretchRange(FontStretch aMin, FontStretch aMax) : FontPropertyRange(aMin, aMax) {} @@ -447,21 +135,16 @@ class StretchRange : public FontPropertyRange { StretchRange(const StretchRange& aOther) = default; void ToString(nsACString& aOutString, const char* aDelim = "..") const { - aOutString.AppendFloat(Min().Percentage()); + aOutString.AppendFloat(Min().ToFloat()); if (!IsSingle()) { aOutString.Append(aDelim); - aOutString.AppendFloat(Max().Percentage()); + aOutString.AppendFloat(Max().ToFloat()); } } - - static StretchRange FromScalar(ScalarType aScalar) { - return StretchRange( - FontStretch(FontStretch::InternalType(aScalar >> 16)), - FontStretch(FontStretch::InternalType(aScalar & 0xffff))); - } }; -class SlantStyleRange : public FontPropertyRange { +class SlantStyleRange + : public FontPropertyRange { public: SlantStyleRange(FontSlantStyle aMin, FontSlantStyle aMax) : FontPropertyRange(aMin, aMax) {} @@ -477,12 +160,6 @@ class SlantStyleRange : public FontPropertyRange { Max().ToString(aOutString); } } - - static SlantStyleRange FromScalar(ScalarType aScalar) { - return SlantStyleRange( - FontSlantStyle(FontSlantStyle::InternalType(aScalar >> 16)), - FontSlantStyle(FontSlantStyle::InternalType(aScalar & 0xffff))); - } }; } // namespace mozilla diff --git a/gfx/src/nsFont.h b/gfx/src/nsFont.h index f842f8246dc7..b4fd3b7fad89 100644 --- a/gfx/src/nsFont.h +++ b/gfx/src/nsFont.h @@ -10,7 +10,6 @@ #include #include "gfxFontConstants.h" // for NS_FONT_KERNING_AUTO, etc #include "gfxFontVariations.h" -#include "mozilla/FontPropertyTypes.h" #include "mozilla/ServoStyleConstsInlines.h" #include "mozilla/StyleColorInlines.h" // for StyleRGBA #include "nsTArray.h" // for nsTArray @@ -54,9 +53,9 @@ struct nsFont final { // Font-selection/rendering properties corresponding to CSS font-style, // font-weight, font-stretch. These are all 16-bit types. - FontSlantStyle style = FontSlantStyle::Normal(); - FontWeight weight = FontWeight::Normal(); - FontStretch stretch = FontStretch::Normal(); + FontSlantStyle style = FontSlantStyle::NORMAL; + FontWeight weight = FontWeight::NORMAL; + FontStretch stretch = FontStretch::NORMAL; // Some font-variant-alternates property values require // font-specific settings defined via @font-feature-values rules. diff --git a/gfx/thebes/SharedFontList.cpp b/gfx/thebes/SharedFontList.cpp index d442f79f781c..103b34460793 100644 --- a/gfx/thebes/SharedFontList.cpp +++ b/gfx/thebes/SharedFontList.cpp @@ -278,7 +278,7 @@ bool Family::FindAllFacesForStyleInternal(FontList* aList, // calculate which one we want. // Note that we cannot simply return it as not all 4 faces are necessarily // present. - bool wantBold = aStyle.weight >= FontWeight(600); + bool wantBold = aStyle.weight.IsBold(); bool wantItalic = !aStyle.style.IsNormal(); uint8_t faceIndex = (wantItalic ? kItalicMask : 0) | (wantBold ? kBoldMask : 0); diff --git a/gfx/thebes/gfxDWriteCommon.h b/gfx/thebes/gfxDWriteCommon.h index f3a1b039651a..8daf02fd1458 100644 --- a/gfx/thebes/gfxDWriteCommon.h +++ b/gfx/thebes/gfxDWriteCommon.h @@ -35,33 +35,34 @@ #define ENHANCED_CONTRAST_VALUE_NAME L"EnhancedContrastLevel" +// FIXME: This shouldn't look at constants probably. static inline DWRITE_FONT_STRETCH DWriteFontStretchFromStretch( mozilla::FontStretch aStretch) { - if (aStretch == mozilla::FontStretch::UltraCondensed()) { + if (aStretch == mozilla::FontStretch::ULTRA_CONDENSED) { return DWRITE_FONT_STRETCH_ULTRA_CONDENSED; } - if (aStretch == mozilla::FontStretch::ExtraCondensed()) { + if (aStretch == mozilla::FontStretch::EXTRA_CONDENSED) { return DWRITE_FONT_STRETCH_EXTRA_CONDENSED; } - if (aStretch == mozilla::FontStretch::Condensed()) { + if (aStretch == mozilla::FontStretch::CONDENSED) { return DWRITE_FONT_STRETCH_CONDENSED; } - if (aStretch == mozilla::FontStretch::SemiCondensed()) { + if (aStretch == mozilla::FontStretch::SEMI_CONDENSED) { return DWRITE_FONT_STRETCH_SEMI_CONDENSED; } - if (aStretch == mozilla::FontStretch::Normal()) { + if (aStretch == mozilla::FontStretch::NORMAL) { return DWRITE_FONT_STRETCH_NORMAL; } - if (aStretch == mozilla::FontStretch::SemiExpanded()) { + if (aStretch == mozilla::FontStretch::SEMI_EXPANDED) { return DWRITE_FONT_STRETCH_SEMI_EXPANDED; } - if (aStretch == mozilla::FontStretch::Expanded()) { + if (aStretch == mozilla::FontStretch::EXPANDED) { return DWRITE_FONT_STRETCH_EXPANDED; } - if (aStretch == mozilla::FontStretch::ExtraExpanded()) { + if (aStretch == mozilla::FontStretch::EXTRA_EXPANDED) { return DWRITE_FONT_STRETCH_EXTRA_EXPANDED; } - if (aStretch == mozilla::FontStretch::UltraExpanded()) { + if (aStretch == mozilla::FontStretch::ULTRA_EXPANDED) { return DWRITE_FONT_STRETCH_ULTRA_EXPANDED; } return DWRITE_FONT_STRETCH_UNDEFINED; @@ -71,25 +72,25 @@ static inline mozilla::FontStretch FontStretchFromDWriteStretch( DWRITE_FONT_STRETCH aStretch) { switch (aStretch) { case DWRITE_FONT_STRETCH_ULTRA_CONDENSED: - return mozilla::FontStretch::UltraCondensed(); + return mozilla::FontStretch::ULTRA_CONDENSED; case DWRITE_FONT_STRETCH_EXTRA_CONDENSED: - return mozilla::FontStretch::ExtraCondensed(); + return mozilla::FontStretch::EXTRA_CONDENSED; case DWRITE_FONT_STRETCH_CONDENSED: - return mozilla::FontStretch::Condensed(); + return mozilla::FontStretch::CONDENSED; case DWRITE_FONT_STRETCH_SEMI_CONDENSED: - return mozilla::FontStretch::SemiCondensed(); + return mozilla::FontStretch::SEMI_CONDENSED; case DWRITE_FONT_STRETCH_NORMAL: - return mozilla::FontStretch::Normal(); + return mozilla::FontStretch::NORMAL; case DWRITE_FONT_STRETCH_SEMI_EXPANDED: - return mozilla::FontStretch::SemiExpanded(); + return mozilla::FontStretch::SEMI_EXPANDED; case DWRITE_FONT_STRETCH_EXPANDED: - return mozilla::FontStretch::Expanded(); + return mozilla::FontStretch::EXPANDED; case DWRITE_FONT_STRETCH_EXTRA_EXPANDED: - return mozilla::FontStretch::ExtraExpanded(); + return mozilla::FontStretch::EXTRA_EXPANDED; case DWRITE_FONT_STRETCH_ULTRA_EXPANDED: - return mozilla::FontStretch::UltraExpanded(); + return mozilla::FontStretch::ULTRA_EXPANDED; default: - return mozilla::FontStretch::Normal(); + return mozilla::FontStretch::NORMAL; } } diff --git a/gfx/thebes/gfxDWriteFontList.cpp b/gfx/thebes/gfxDWriteFontList.cpp index 370645667dd3..b05f1533eae1 100644 --- a/gfx/thebes/gfxDWriteFontList.cpp +++ b/gfx/thebes/gfxDWriteFontList.cpp @@ -1284,7 +1284,7 @@ void gfxDWriteFontList::GetFacesInitDataForFamily( aFamily->Key().AsString(SharedFontList()).EqualsLiteral("meiryo")) { continue; } - WeightRange weight(FontWeight(dwFont->GetWeight())); + WeightRange weight(FontWeight::FromInt(dwFont->GetWeight())); StretchRange stretch(FontStretchFromDWriteStretch(dwFont->GetStretch())); // Try to read PSName as a unique face identifier; if this fails we'll get // it directly from the 'name' table, and if that also fails we consider @@ -1324,9 +1324,9 @@ void gfxDWriteFontList::GetFacesInitDataForFamily( continue; } SlantStyleRange slant( - dwstyle == DWRITE_FONT_STYLE_NORMAL ? FontSlantStyle::Normal() - : dwstyle == DWRITE_FONT_STYLE_ITALIC ? FontSlantStyle::Italic() - : FontSlantStyle::Oblique()); + dwstyle == DWRITE_FONT_STYLE_NORMAL ? FontSlantStyle::NORMAL + : dwstyle == DWRITE_FONT_STYLE_ITALIC ? FontSlantStyle::ITALIC + : FontSlantStyle::OBLIQUE); aFaces.AppendElement(fontlist::Face::InitData{ name, uint16_t(i), false, weight, stretch, slant, charmap}); } diff --git a/gfx/thebes/gfxDWriteFontList.h b/gfx/thebes/gfxDWriteFontList.h index bde397a09240..2a1711c6913a 100644 --- a/gfx/thebes/gfxDWriteFontList.h +++ b/gfx/thebes/gfxDWriteFontList.h @@ -116,10 +116,10 @@ class gfxDWriteFontEntry final : public gfxFontEntry { mHasVariationsInitialized(false) { DWRITE_FONT_STYLE dwriteStyle = aFont->GetStyle(); FontSlantStyle style = (dwriteStyle == DWRITE_FONT_STYLE_ITALIC - ? FontSlantStyle::Italic() + ? FontSlantStyle::ITALIC : (dwriteStyle == DWRITE_FONT_STYLE_OBLIQUE - ? FontSlantStyle::Oblique() - : FontSlantStyle::Normal())); + ? FontSlantStyle::OBLIQUE + : FontSlantStyle::NORMAL)); mStyleRange = SlantStyleRange(style); mStretchRange = @@ -127,7 +127,7 @@ class gfxDWriteFontEntry final : public gfxFontEntry { int weight = NS_ROUNDUP(aFont->GetWeight() - 50, 100); weight = mozilla::Clamp(weight, 100, 900); - mWeightRange = WeightRange(FontWeight(weight)); + mWeightRange = WeightRange(FontWeight::FromInt(weight)); mIsCJK = UNINITIALIZED_VALUE; } diff --git a/gfx/thebes/gfxDWriteFonts.cpp b/gfx/thebes/gfxDWriteFonts.cpp index 7522c7b4ec5e..631b6ca87a2b 100644 --- a/gfx/thebes/gfxDWriteFonts.cpp +++ b/gfx/thebes/gfxDWriteFonts.cpp @@ -289,7 +289,7 @@ gfxFont* gfxDWriteFont::CopyWithAntialiasOption( bool gfxDWriteFont::GetFakeMetricsForArialBlack( DWRITE_FONT_METRICS* aFontMetrics) { gfxFontStyle style(mStyle); - style.weight = FontWeight(700); + style.weight = FontWeight::FromInt(700); gfxFontEntry* fe = gfxPlatformFontList::PlatformFontList()->FindFontForFamily( nullptr, "Arial"_ns, &style); @@ -306,8 +306,8 @@ bool gfxDWriteFont::GetFakeMetricsForArialBlack( void gfxDWriteFont::ComputeMetrics(AntialiasOption anAAOption) { DWRITE_FONT_METRICS fontMetrics; - if (!(mFontEntry->Weight().Min() == FontWeight(900) && - mFontEntry->Weight().Max() == FontWeight(900) && + if (!(mFontEntry->Weight().Min() == FontWeight::FromInt(900) && + mFontEntry->Weight().Max() == FontWeight::FromInt(900) && !mFontEntry->IsUserFont() && mFontEntry->Name().EqualsLiteral("Arial Black") && GetFakeMetricsForArialBlack(&fontMetrics))) { diff --git a/gfx/thebes/gfxFT2FontList.cpp b/gfx/thebes/gfxFT2FontList.cpp index 920c82a15ad5..7b8089c3db34 100644 --- a/gfx/thebes/gfxFT2FontList.cpp +++ b/gfx/thebes/gfxFT2FontList.cpp @@ -5,7 +5,6 @@ #include "mozilla/ArrayUtils.h" #include "mozilla/Base64.h" -#include "mozilla/FontPropertyTypes.h" #include "mozilla/MemoryReporting.h" #include "mozilla/dom/ContentChild.h" @@ -304,9 +303,9 @@ static void SetPropertiesFromFace(gfxFontEntry* aFontEntry, hb_blob_destroy(blob); aFontEntry->mStyleRange = SlantStyleRange( - (style & 2) ? FontSlantStyle::Italic() : FontSlantStyle::Normal()); - aFontEntry->mWeightRange = WeightRange(FontWeight(int(os2weight))); - aFontEntry->mStretchRange = StretchRange(FontStretch(stretch)); + (style & 2) ? FontSlantStyle::ITALIC : FontSlantStyle::NORMAL); + aFontEntry->mWeightRange = WeightRange(FontWeight::FromInt(int(os2weight))); + aFontEntry->mStretchRange = StretchRange(FontStretch::FromFloat(stretch)); // For variable fonts, update the style/weight/stretch attributes if the // corresponding variation axes are present. @@ -331,9 +330,9 @@ FT2FontEntry* FT2FontEntry::CreateFontEntry(const nsACString& aName, } else { // If nullptr is passed for aFace, the caller is intending to override // these attributes anyway. We just set defaults here to be safe. - fe->mStyleRange = SlantStyleRange(FontSlantStyle::Normal()); - fe->mWeightRange = WeightRange(FontWeight::Normal()); - fe->mStretchRange = StretchRange(FontStretch::Normal()); + fe->mStyleRange = SlantStyleRange(FontSlantStyle::NORMAL); + fe->mWeightRange = WeightRange(FontWeight::NORMAL); + fe->mStretchRange = StretchRange(FontStretch::NORMAL); } return fe; @@ -996,36 +995,31 @@ bool gfxFT2FontList::AppendFacesFromCachedFaceList(CollectFunc aCollectFace, if (!nextField(start, end)) { break; } - nsAutoCString minStyle(start, end - start); - nsAutoCString maxStyle(minStyle); - int32_t colon = minStyle.FindChar(FontNameCache::kRangeSep); - if (colon > 0) { - maxStyle.Assign(minStyle.BeginReading() + colon + 1); - minStyle.Truncate(colon); - } + + auto readIntPair = [&](int32_t& aStart, int32_t& aEnd) { + char* limit = nullptr; + aStart = strtol(start, &limit, 10); + if (*limit == FontNameCache::kRangeSep && limit + 1 < end) { + aEnd = strtof(limit + 1, nullptr); + } + }; + + int32_t minStyle, maxStyle; + readIntPair(minStyle, maxStyle); if (!nextField(start, end)) { break; } - char* limit; - float minWeight = strtof(start, &limit); - float maxWeight; - if (*limit == FontNameCache::kRangeSep && limit + 1 < end) { - maxWeight = strtof(limit + 1, nullptr); - } else { - maxWeight = minWeight; - } + + int32_t minWeight, maxWeight; + readIntPair(minWeight, maxWeight); if (!nextField(start, end)) { break; } - float minStretch = strtof(start, &limit); - float maxStretch; - if (*limit == FontNameCache::kRangeSep && limit + 1 < end) { - maxStretch = strtof(limit + 1, nullptr); - } else { - maxStretch = minStretch; - } + + int32_t minStretch, maxStretch; + readIntPair(minStretch, maxStretch); if (!nextField(start, end)) { break; @@ -1042,15 +1036,17 @@ bool gfxFT2FontList::AppendFacesFromCachedFaceList(CollectFunc aCollectFace, } FontVisibility visibility = FontVisibility(strtoul(start, nullptr, 10)); - FontListEntry fle( - familyName, faceName, aFileName, - WeightRange(FontWeight(minWeight), FontWeight(maxWeight)).AsScalar(), - StretchRange(FontStretch(minStretch), FontStretch(maxStretch)) - .AsScalar(), - SlantStyleRange(FontSlantStyle::FromString(minStyle.get()), - FontSlantStyle::FromString(maxStyle.get())) - .AsScalar(), - index, visibility); + FontListEntry fle(familyName, faceName, aFileName, + WeightRange(FontWeight::FromRaw(minWeight), + FontWeight::FromRaw(maxWeight)) + .AsScalar(), + StretchRange(FontStretch::FromRaw(minStretch), + FontStretch::FromRaw(maxStretch)) + .AsScalar(), + SlantStyleRange(FontSlantStyle::FromRaw(minStyle), + FontSlantStyle::FromRaw(maxStyle)) + .AsScalar(), + index, visibility); aCollectFace(fle, psname, fullname, aStdFile); count++; @@ -1072,19 +1068,17 @@ void FT2FontEntry::AppendToFaceList(nsCString& aFaceList, aFaceList.Append(FontNameCache::kFieldSep); aFaceList.AppendInt(mFTFontIndex); aFaceList.Append(FontNameCache::kFieldSep); - // Note that ToString() appends to the destination string without - // replacing existing contents (see FontPropertyTypes.h) - SlantStyle().Min().ToString(aFaceList); + aFaceList.AppendInt(SlantStyle().Min().Raw()); aFaceList.Append(FontNameCache::kRangeSep); - SlantStyle().Max().ToString(aFaceList); + aFaceList.AppendInt(SlantStyle().Max().Raw()); aFaceList.Append(FontNameCache::kFieldSep); - aFaceList.AppendFloat(Weight().Min().ToFloat()); + aFaceList.AppendInt(Weight().Min().Raw()); aFaceList.Append(FontNameCache::kRangeSep); - aFaceList.AppendFloat(Weight().Max().ToFloat()); + aFaceList.AppendInt(Weight().Max().Raw()); aFaceList.Append(FontNameCache::kFieldSep); - aFaceList.AppendFloat(Stretch().Min().Percentage()); + aFaceList.AppendInt(Stretch().Min().Raw()); aFaceList.Append(FontNameCache::kRangeSep); - aFaceList.AppendFloat(Stretch().Max().Percentage()); + aFaceList.AppendInt(Stretch().Max().Raw()); aFaceList.Append(FontNameCache::kFieldSep); aFaceList.Append(aPSName); aFaceList.Append(FontNameCache::kFieldSep); diff --git a/gfx/thebes/gfxFcPlatformFontList.cpp b/gfx/thebes/gfxFcPlatformFontList.cpp index 0d12972b37e9..7e114a87af68 100644 --- a/gfx/thebes/gfxFcPlatformFontList.cpp +++ b/gfx/thebes/gfxFcPlatformFontList.cpp @@ -145,65 +145,65 @@ static void GetFaceNames(FcPattern* aFont, const nsACString& aFamilyName, static FontWeight MapFcWeight(int aFcWeight) { if (aFcWeight <= (FC_WEIGHT_THIN + FC_WEIGHT_EXTRALIGHT) / 2) { - return FontWeight(100); + return FontWeight::FromInt(100); } if (aFcWeight <= (FC_WEIGHT_EXTRALIGHT + FC_WEIGHT_LIGHT) / 2) { - return FontWeight(200); + return FontWeight::FromInt(200); } if (aFcWeight <= (FC_WEIGHT_LIGHT + FC_WEIGHT_BOOK) / 2) { - return FontWeight(300); + return FontWeight::FromInt(300); } if (aFcWeight <= (FC_WEIGHT_REGULAR + FC_WEIGHT_MEDIUM) / 2) { // This includes FC_WEIGHT_BOOK - return FontWeight(400); + return FontWeight::FromInt(400); } if (aFcWeight <= (FC_WEIGHT_MEDIUM + FC_WEIGHT_DEMIBOLD) / 2) { - return FontWeight(500); + return FontWeight::FromInt(500); } if (aFcWeight <= (FC_WEIGHT_DEMIBOLD + FC_WEIGHT_BOLD) / 2) { - return FontWeight(600); + return FontWeight::FromInt(600); } if (aFcWeight <= (FC_WEIGHT_BOLD + FC_WEIGHT_EXTRABOLD) / 2) { - return FontWeight(700); + return FontWeight::FromInt(700); } if (aFcWeight <= (FC_WEIGHT_EXTRABOLD + FC_WEIGHT_BLACK) / 2) { - return FontWeight(800); + return FontWeight::FromInt(800); } if (aFcWeight <= FC_WEIGHT_BLACK) { - return FontWeight(900); + return FontWeight::FromInt(900); } // including FC_WEIGHT_EXTRABLACK - return FontWeight(901); + return FontWeight::FromInt(901); } // TODO(emilio, jfkthame): I think this can now be more fine-grained. static FontStretch MapFcWidth(int aFcWidth) { if (aFcWidth <= (FC_WIDTH_ULTRACONDENSED + FC_WIDTH_EXTRACONDENSED) / 2) { - return FontStretch::UltraCondensed(); + return FontStretch::ULTRA_CONDENSED; } if (aFcWidth <= (FC_WIDTH_EXTRACONDENSED + FC_WIDTH_CONDENSED) / 2) { - return FontStretch::ExtraCondensed(); + return FontStretch::EXTRA_CONDENSED; } if (aFcWidth <= (FC_WIDTH_CONDENSED + FC_WIDTH_SEMICONDENSED) / 2) { - return FontStretch::Condensed(); + return FontStretch::CONDENSED; } if (aFcWidth <= (FC_WIDTH_SEMICONDENSED + FC_WIDTH_NORMAL) / 2) { - return FontStretch::SemiCondensed(); + return FontStretch::SEMI_CONDENSED; } if (aFcWidth <= (FC_WIDTH_NORMAL + FC_WIDTH_SEMIEXPANDED) / 2) { - return FontStretch::Normal(); + return FontStretch::NORMAL; } if (aFcWidth <= (FC_WIDTH_SEMIEXPANDED + FC_WIDTH_EXPANDED) / 2) { - return FontStretch::SemiExpanded(); + return FontStretch::SEMI_EXPANDED; } if (aFcWidth <= (FC_WIDTH_EXPANDED + FC_WIDTH_EXTRAEXPANDED) / 2) { - return FontStretch::Expanded(); + return FontStretch::EXPANDED; } if (aFcWidth <= (FC_WIDTH_EXTRAEXPANDED + FC_WIDTH_ULTRAEXPANDED) / 2) { - return FontStretch::ExtraExpanded(); + return FontStretch::EXTRA_EXPANDED; } - return FontStretch::UltraExpanded(); + return FontStretch::ULTRA_EXPANDED; } static void GetFontProperties(FcPattern* aFontPattern, WeightRange* aWeight, @@ -231,9 +231,9 @@ static void GetFontProperties(FcPattern* aFontPattern, WeightRange* aWeight, slant = FC_SLANT_ROMAN; } if (slant == FC_SLANT_OBLIQUE) { - *aSlantStyle = SlantStyleRange(FontSlantStyle::Oblique()); + *aSlantStyle = SlantStyleRange(FontSlantStyle::OBLIQUE); } else if (slant > 0) { - *aSlantStyle = SlantStyleRange(FontSlantStyle::Italic()); + *aSlantStyle = SlantStyleRange(FontSlantStyle::ITALIC); } if (aSize) { @@ -888,7 +888,7 @@ gfxFont* gfxFontconfigFontEntry::CreateFontInstance( } // will synthetic oblique be applied using a transform? - if (IsUpright() && aFontStyle->style != FontSlantStyle::Normal() && + if (IsUpright() && !aFontStyle->style.IsNormal() && aFontStyle->allowSyntheticStyle) { // disable embedded bitmaps (mimics behavior in 90-synthetic.conf) FcPatternDel(renderPattern, FC_EMBEDDED_BITMAP); @@ -1752,9 +1752,9 @@ void gfxFcPlatformFontList::InitSharedFontListForPlatform() { } } - WeightRange weight(FontWeight::Normal()); - StretchRange stretch(FontStretch::Normal()); - SlantStyleRange style(FontSlantStyle::Normal()); + WeightRange weight(FontWeight::NORMAL); + StretchRange stretch(FontStretch::NORMAL); + SlantStyleRange style(FontSlantStyle::NORMAL); uint16_t size; GetFontProperties(aPattern, &weight, &stretch, &style, &size); diff --git a/gfx/thebes/gfxFont.cpp b/gfx/thebes/gfxFont.cpp index 1a5e94fd4a12..24d4fcd5dfa4 100644 --- a/gfx/thebes/gfxFont.cpp +++ b/gfx/thebes/gfxFont.cpp @@ -811,7 +811,7 @@ void gfxShapedText::AdjustAdvancesForSyntheticBold(float aSynBoldOffset, float gfxFont::AngleForSyntheticOblique() const { // If the style doesn't call for italic/oblique, or if the face already // provides it, no synthetic style should be added. - if (mStyle.style == FontSlantStyle::Normal() || !mStyle.allowSyntheticStyle || + if (mStyle.style == FontSlantStyle::NORMAL || !mStyle.allowSyntheticStyle || !mFontEntry->IsUpright()) { return 0.0f; } @@ -819,7 +819,9 @@ float gfxFont::AngleForSyntheticOblique() const { // If style calls for italic, and face doesn't support it, use default // oblique angle as a simulation. if (mStyle.style.IsItalic()) { - return mFontEntry->SupportsItalic() ? 0.0f : FontSlantStyle::kDefaultAngle; + return mFontEntry->SupportsItalic() + ? 0.0f + : FontSlantStyle::DEFAULT_OBLIQUE_DEGREES; } // Default or custom oblique angle @@ -830,12 +832,12 @@ float gfxFont::SkewForSyntheticOblique() const { // Precomputed value of tan(kDefaultAngle), the default italic/oblique slant; // avoids calling tan() at runtime except for custom oblique values. static const float kTanDefaultAngle = - tan(FontSlantStyle::kDefaultAngle * (M_PI / 180.0)); + tan(FontSlantStyle::DEFAULT_OBLIQUE_DEGREES * (M_PI / 180.0)); float angle = AngleForSyntheticOblique(); if (angle == 0.0f) { return 0.0f; - } else if (angle == FontSlantStyle::kDefaultAngle) { + } else if (angle == FontSlantStyle::DEFAULT_OBLIQUE_DEGREES) { return kTanDefaultAngle; } else { return tan(angle * (M_PI / 180.0)); @@ -4159,9 +4161,9 @@ gfxFontStyle::gfxFontStyle() baselineOffset(0.0f), languageOverride(NO_FONT_LANGUAGE_OVERRIDE), fontSmoothingBackgroundColor(NS_RGBA(0, 0, 0, 0)), - weight(FontWeight::Normal()), - stretch(FontStretch::Normal()), - style(FontSlantStyle::Normal()), + weight(FontWeight::NORMAL), + stretch(FontStretch::NORMAL), + style(FontSlantStyle::NORMAL), variantCaps(NS_FONT_VARIANT_CAPS_NORMAL), variantSubSuper(NS_FONT_VARIANT_POSITION_NORMAL), sizeAdjustBasis(uint8_t(FontSizeAdjust::Tag::None)), @@ -4226,11 +4228,11 @@ gfxFontStyle::gfxFontStyle(FontSlantStyle aStyle, FontWeight aWeight, MOZ_ASSERT(FontSizeAdjust::Tag(sizeAdjustBasis) == aSizeAdjust.tag, "gfxFontStyle.sizeAdjustBasis too small?"); - if (weight > FontWeight(1000)) { - weight = FontWeight(1000); + if (weight > FontWeight::FromInt(1000)) { + weight = FontWeight::FromInt(1000); } - if (weight < FontWeight(1)) { - weight = FontWeight(1); + if (weight < FontWeight::FromInt(1)) { + weight = FontWeight::FromInt(1); } if (size >= FONT_MAX_SIZE) { @@ -4249,9 +4251,8 @@ PLDHashNumber gfxFontStyle::Hash() const { : mozilla::HashBytes(variationSettings.Elements(), variationSettings.Length() * sizeof(gfxFontVariation)); - return mozilla::AddToHash(hash, systemFont, style.ForHash(), - stretch.ForHash(), weight.ForHash(), size, - int32_t(sizeAdjust * 1000.0f)); + return mozilla::AddToHash(hash, systemFont, style.Raw(), stretch.Raw(), + weight.Raw(), size, int32_t(sizeAdjust * 1000.0f)); } void gfxFontStyle::AdjustForSubSuperscript(int32_t aAppUnitsPerDevPixel) { diff --git a/gfx/thebes/gfxFontEntry.cpp b/gfx/thebes/gfxFontEntry.cpp index bbd48c2a3696..a6dc7ee1166f 100644 --- a/gfx/thebes/gfxFontEntry.cpp +++ b/gfx/thebes/gfxFontEntry.cpp @@ -53,7 +53,6 @@ using namespace mozilla; using namespace mozilla::gfx; using namespace mozilla::unicode; -using mozilla::services::GetObserverService; void gfxCharacterMap::NotifyReleased() { if (mShared) { @@ -1230,12 +1229,13 @@ void gfxFontEntry::SetupVariationRanges() { // If axis.mMaxValue is less than the default weight we already // set up, assume the axis has a non-standard range (like Skia) // and don't try to map it. - Weight().Min() <= FontWeight(axis.mMaxValue)) { - if (FontWeight(axis.mDefaultValue) != Weight().Min()) { + Weight().Min() <= FontWeight::FromFloat(axis.mMaxValue)) { + if (FontWeight::FromFloat(axis.mDefaultValue) != Weight().Min()) { mStandardFace = false; } - mWeightRange = WeightRange(FontWeight(std::max(1.0f, axis.mMinValue)), - FontWeight(axis.mMaxValue)); + mWeightRange = + WeightRange(FontWeight::FromFloat(std::max(1.0f, axis.mMinValue)), + FontWeight::FromFloat(axis.mMaxValue)); } else { mRangeFlags |= RangeFlags::eNonCSSWeight; } @@ -1243,12 +1243,12 @@ void gfxFontEntry::SetupVariationRanges() { case HB_TAG('w', 'd', 't', 'h'): if (axis.mMinValue >= 0.0f && axis.mMaxValue <= 1000.0f && - Stretch().Min() <= FontStretch(axis.mMaxValue)) { - if (FontStretch(axis.mDefaultValue) != Stretch().Min()) { + Stretch().Min() <= FontStretch::FromFloat(axis.mMaxValue)) { + if (FontStretch::FromFloat(axis.mDefaultValue) != Stretch().Min()) { mStandardFace = false; } - mStretchRange = StretchRange(FontStretch(axis.mMinValue), - FontStretch(axis.mMaxValue)); + mStretchRange = StretchRange(FontStretch::FromFloat(axis.mMinValue), + FontStretch::FromFloat(axis.mMaxValue)); } else { mRangeFlags |= RangeFlags::eNonCSSStretch; } @@ -1256,7 +1256,7 @@ void gfxFontEntry::SetupVariationRanges() { case HB_TAG('s', 'l', 'n', 't'): if (axis.mMinValue >= -90.0f && axis.mMaxValue <= 90.0f) { - if (FontSlantStyle::Oblique(axis.mDefaultValue) != + if (FontSlantStyle::FromFloat(axis.mDefaultValue) != SlantStyle().Min()) { mStandardFace = false; } @@ -1264,8 +1264,8 @@ void gfxFontEntry::SetupVariationRanges() { // have to flip signs and swap min/max when setting up the CSS // font-style range here. mStyleRange = - SlantStyleRange(FontSlantStyle::Oblique(-axis.mMaxValue), - FontSlantStyle::Oblique(-axis.mMinValue)); + SlantStyleRange(FontSlantStyle::FromFloat(-axis.mMaxValue), + FontSlantStyle::FromFloat(-axis.mMinValue)); } break; @@ -1274,8 +1274,8 @@ void gfxFontEntry::SetupVariationRanges() { if (axis.mDefaultValue != 0.0f) { mStandardFace = false; } - mStyleRange = SlantStyleRange(FontSlantStyle::Normal(), - FontSlantStyle::Italic()); + mStyleRange = + SlantStyleRange(FontSlantStyle::NORMAL, FontSlantStyle::ITALIC); } break; @@ -1358,8 +1358,8 @@ void gfxFontEntry::GetVariationsForStyle(nsTArray& aResult, if (!(mRangeFlags & RangeFlags::eNonCSSStretch)) { float stretch = (IsUserFont() && (mRangeFlags & RangeFlags::eAutoStretch)) - ? aStyle.stretch.Percentage() - : Stretch().Clamp(aStyle.stretch).Percentage(); + ? aStyle.stretch.ToFloat() + : Stretch().Clamp(aStyle.stretch).ToFloat(); aResult.AppendElement( gfxFontVariation{HB_TAG('w', 'd', 't', 'h'), stretch}); } @@ -1373,12 +1373,13 @@ void gfxFontEntry::GetVariationsForStyle(nsTArray& aResult, // requested style. float angle = aStyle.style.IsNormal() ? 0.0f : aStyle.style.IsItalic() - ? FontSlantStyle::Oblique().ObliqueAngle() + ? FontSlantStyle::DEFAULT_OBLIQUE_DEGREES : aStyle.style.ObliqueAngle(); // Clamp to the available range, unless the face is a user font // with no explicit descriptor. if (!(IsUserFont() && (mRangeFlags & RangeFlags::eAutoSlantStyle))) { - angle = SlantStyle().Clamp(FontSlantStyle::Oblique(angle)).ObliqueAngle(); + angle = + SlantStyle().Clamp(FontSlantStyle::FromFloat(angle)).ObliqueAngle(); } // OpenType and CSS measure angles in opposite directions, so we have to // invert the sign of the CSS oblique value when setting OpenType 'slnt'. @@ -1626,7 +1627,7 @@ void gfxFontFamily::FindAllFontsForStyle( // calculate which one we want. // Note that we cannot simply return it as not all 4 faces are necessarily // present. - bool wantBold = aFontStyle.weight >= FontWeight(600); + bool wantBold = aFontStyle.weight >= FontWeight::FromInt(600); bool wantItalic = !aFontStyle.style.IsNormal(); uint8_t faceIndex = (wantItalic ? kItalicMask : 0) | (wantBold ? kBoldMask : 0); diff --git a/gfx/thebes/gfxFontEntry.h b/gfx/thebes/gfxFontEntry.h index ef592f00b213..7354ad591e82 100644 --- a/gfx/thebes/gfxFontEntry.h +++ b/gfx/thebes/gfxFontEntry.h @@ -193,10 +193,10 @@ class gfxFontEntry { // If this is false, we might want to fall back to a different face and // possibly apply synthetic styling. bool IsNormalStyle() const { - return IsUpright() && Weight().Min() <= FontWeight::Normal() && - Weight().Max() >= FontWeight::Normal() && - Stretch().Min() <= FontStretch::Normal() && - Stretch().Max() >= FontStretch::Normal(); + return IsUpright() && Weight().Min() <= FontWeight::NORMAL && + Weight().Max() >= FontWeight::NORMAL && + Stretch().Min() <= FontStretch::NORMAL && + Stretch().Max() >= FontStretch::NORMAL; } // whether a feature is supported by the font (limited to a small set @@ -518,9 +518,9 @@ class gfxFontEntry { uint32_t mLanguageOverride = NO_FONT_LANGUAGE_OVERRIDE; - WeightRange mWeightRange = WeightRange(FontWeight(500)); - StretchRange mStretchRange = StretchRange(FontStretch::Normal()); - SlantStyleRange mStyleRange = SlantStyleRange(FontSlantStyle::Normal()); + WeightRange mWeightRange = WeightRange(FontWeight::FromInt(500)); + StretchRange mStretchRange = StretchRange(FontStretch::NORMAL); + SlantStyleRange mStyleRange = SlantStyleRange(FontSlantStyle::NORMAL); // Font metrics overrides (as multiples of used font size); negative values // indicate no override to be applied. diff --git a/gfx/thebes/gfxFontUtils.h b/gfx/thebes/gfxFontUtils.h index 2b678b5e8582..86da7fce85cd 100644 --- a/gfx/thebes/gfxFontUtils.h +++ b/gfx/thebes/gfxFontUtils.h @@ -15,7 +15,7 @@ #include "mozilla/Attributes.h" #include "mozilla/Casting.h" #include "mozilla/EndianUtils.h" -#include "mozilla/FontPropertyTypes.h" +#include "mozilla/ServoStyleConstsInlines.h" #include "mozilla/MemoryReporting.h" #include "mozilla/UniquePtr.h" #include "nsStringFwd.h" @@ -1251,8 +1251,7 @@ static inline double StyleDistance(const mozilla::SlantStyleRange& aRange, return kReverse; } - const double kDefaultAngle = - mozilla::FontSlantStyle::Oblique().ObliqueAngle(); + const double kDefaultAngle = mozilla::FontSlantStyle::OBLIQUE.ObliqueAngle(); if (aTargetStyle.IsItalic()) { if (minStyle.IsOblique()) { @@ -1383,16 +1382,16 @@ static inline double StretchDistance(const mozilla::StretchRange& aRange, // If aTargetStretch is >100, we prefer larger values if available; // if <=100, we prefer smaller values if available. if (aTargetStretch < minStretch) { - if (aTargetStretch > mozilla::FontStretch::Normal()) { - return minStretch - aTargetStretch; + if (aTargetStretch > mozilla::FontStretch::NORMAL) { + return minStretch.ToFloat() - aTargetStretch.ToFloat(); } - return (minStretch - aTargetStretch) + kReverseDistance; + return (minStretch.ToFloat() - aTargetStretch.ToFloat()) + kReverseDistance; } if (aTargetStretch > maxStretch) { - if (aTargetStretch <= mozilla::FontStretch::Normal()) { - return aTargetStretch - maxStretch; + if (aTargetStretch <= mozilla::FontStretch::NORMAL) { + return aTargetStretch.ToFloat() - maxStretch.ToFloat(); } - return (aTargetStretch - maxStretch) + kReverseDistance; + return (aTargetStretch.ToFloat() - maxStretch.ToFloat()) + kReverseDistance; } return 0.0; } @@ -1422,35 +1421,36 @@ static inline double WeightDistance(const mozilla::WeightRange& aRange, return 0.0; } - if (aTargetWeight < mozilla::FontWeight(400)) { + if (aTargetWeight < mozilla::FontWeight::NORMAL) { // Requested a lighter-than-400 weight if (maxWeight < aTargetWeight) { - return aTargetWeight - maxWeight; + return aTargetWeight.ToFloat() - maxWeight.ToFloat(); } // Add reverse-search penalty for bolder faces - return (minWeight - aTargetWeight) + kReverseDistance; + return (minWeight.ToFloat() - aTargetWeight.ToFloat()) + kReverseDistance; } - if (aTargetWeight > mozilla::FontWeight(500)) { + if (aTargetWeight > mozilla::FontWeight::FromInt(500)) { // Requested a bolder-than-500 weight if (minWeight > aTargetWeight) { - return minWeight - aTargetWeight; + return minWeight.ToFloat() - aTargetWeight.ToFloat(); } // Add reverse-search penalty for lighter faces - return (aTargetWeight - maxWeight) + kReverseDistance; + return (aTargetWeight.ToFloat() - maxWeight.ToFloat()) + kReverseDistance; } // Special case for requested weight in the [400..500] range if (minWeight > aTargetWeight) { - if (minWeight <= mozilla::FontWeight(500)) { + if (minWeight <= mozilla::FontWeight::FromInt(500)) { // Bolder weight up to 500 is first choice - return minWeight - aTargetWeight; + return minWeight.ToFloat() - aTargetWeight.ToFloat(); } // Other bolder weights get a reverse-search penalty - return (minWeight - aTargetWeight) + kReverseDistance; + return (minWeight.ToFloat() - aTargetWeight.ToFloat()) + kReverseDistance; } // Lighter weights are not as good as bolder ones within [400..500] - return (aTargetWeight - maxWeight) + kNotWithinCentralRange; + return (aTargetWeight.ToFloat() - maxWeight.ToFloat()) + + kNotWithinCentralRange; } #endif /* GFX_FONT_UTILS_H */ diff --git a/gfx/thebes/gfxGDIFontList.cpp b/gfx/thebes/gfxGDIFontList.cpp index a38dd1626b41..99e2a7ae56f3 100644 --- a/gfx/thebes/gfxGDIFontList.cpp +++ b/gfx/thebes/gfxGDIFontList.cpp @@ -280,7 +280,7 @@ bool GDIFontEntry::TestCharacterMap(uint32_t aCh) { // previous code was using the group style gfxFontStyle fakeStyle; if (!IsUpright()) { - fakeStyle.style = FontSlantStyle::Italic(); + fakeStyle.style = FontSlantStyle::ITALIC; } fakeStyle.weight = Weight().Min(); @@ -432,7 +432,7 @@ int CALLBACK GDIFontFamily::FamilyAddStylesProc( for (uint32_t i = 0; i < ff->mAvailableFonts.Length(); ++i) { fe = static_cast(ff->mAvailableFonts[i].get()); // check if we already know about this face - if (fe->Weight().Min() == FontWeight(int32_t(logFont.lfWeight)) && + if (fe->Weight().Min() == FontWeight::FromInt(int32_t(logFont.lfWeight)) && fe->IsItalic() == (logFont.lfItalic == 0xFF)) { // update the charset bit here since this could be different // XXX Can we still do this now that we store mCharset @@ -445,13 +445,13 @@ int CALLBACK GDIFontFamily::FamilyAddStylesProc( // We can't set the hasItalicFace flag correctly here, // because we might not have seen the family's italic face(s) yet. // So we'll set that flag for all members after loading all the faces. - auto italicStyle = (logFont.lfItalic == 0xFF ? FontSlantStyle::Italic() - : FontSlantStyle::Normal()); + auto italicStyle = (logFont.lfItalic == 0xFF ? FontSlantStyle::ITALIC + : FontSlantStyle::NORMAL); fe = GDIFontEntry::CreateFontEntry( NS_ConvertUTF16toUTF8(lpelfe->elfFullName), feType, SlantStyleRange(italicStyle), - WeightRange(FontWeight(int32_t(logFont.lfWeight))), - StretchRange(FontStretch::Normal()), nullptr); + WeightRange(FontWeight::FromInt(int32_t(logFont.lfWeight))), + StretchRange(FontStretch::NORMAL), nullptr); if (!fe) { return 1; } diff --git a/gfx/thebes/gfxMacPlatformFontList.mm b/gfx/thebes/gfxMacPlatformFontList.mm index 300f0cbfdb98..51619e9def0e 100644 --- a/gfx/thebes/gfxMacPlatformFontList.mm +++ b/gfx/thebes/gfxMacPlatformFontList.mm @@ -865,22 +865,22 @@ void gfxMacFontFamily::FindStyleVariationsLocked(FontInfoData* aFontInfoData) { // create a font entry MacOSFontEntry* fontEntry = new MacOSFontEntry(NS_ConvertUTF16toUTF8(postscriptFontName), - WeightRange(FontWeight(cssWeight)), isStandardFace, mSizeHint); + WeightRange(FontWeight::FromInt(cssWeight)), isStandardFace, mSizeHint); if (!fontEntry) { break; } // set additional properties based on the traits reported by Cocoa if (macTraits & (NSCondensedFontMask | NSNarrowFontMask | NSCompressedFontMask)) { - fontEntry->mStretchRange = StretchRange(FontStretch::Condensed()); + fontEntry->mStretchRange = StretchRange(FontStretch::CONDENSED); } else if (macTraits & NSExpandedFontMask) { - fontEntry->mStretchRange = StretchRange(FontStretch::Expanded()); + fontEntry->mStretchRange = StretchRange(FontStretch::EXPANDED); } // Cocoa fails to set the Italic traits bit for HelveticaLightItalic, // at least (see bug 611855), so check for style name endings as well if ((macTraits & NSItalicFontMask) || [facename hasSuffix:@"Italic"] || [facename hasSuffix:@"Oblique"]) { - fontEntry->mStyleRange = SlantStyleRange(FontSlantStyle::Italic()); + fontEntry->mStyleRange = SlantStyleRange(FontSlantStyle::ITALIC); } if (macTraits & NSFixedPitchFontMask) { fontEntry->mFixedPitch = true; @@ -1419,7 +1419,7 @@ static gfxFontFamily* CreateFamilyForSystemFont(NSFont* aFont, const nsACString& nsCocoaUtils::GetStringForNSString(psNameNS, nameUTF16); CopyUTF16toUTF8(nameUTF16, psName); - MacOSFontEntry* fe = new MacOSFontEntry(psName, WeightRange(FontWeight::Normal()), true, 0.0); + MacOSFontEntry* fe = new MacOSFontEntry(psName, WeightRange(FontWeight::NORMAL), true, 0.0); MOZ_ASSERT(gfxPlatform::GetPlatform()->HasVariationFontSupport()); fe->SetupVariationRanges(); @@ -1816,12 +1816,11 @@ void gfxMacPlatformFontList::LookupSystemFont(LookAndFeel::FontID aSystemFontID, } NSFontSymbolicTraits traits = [[font fontDescriptor] symbolicTraits]; - aFontStyle.style = - (traits & NSFontItalicTrait) ? FontSlantStyle::Italic() : FontSlantStyle::Normal(); - aFontStyle.weight = (traits & NSFontBoldTrait) ? FontWeight::Bold() : FontWeight::Normal(); - aFontStyle.stretch = (traits & NSFontExpandedTrait) ? FontStretch::Expanded() - : (traits & NSFontCondensedTrait) ? FontStretch::Condensed() - : FontStretch::Normal(); + aFontStyle.style = (traits & NSFontItalicTrait) ? FontSlantStyle::ITALIC : FontSlantStyle::NORMAL; + aFontStyle.weight = (traits & NSFontBoldTrait) ? FontWeight::BOLD : FontWeight::NORMAL; + aFontStyle.stretch = (traits & NSFontExpandedTrait) ? FontStretch::EXPANDED + : (traits & NSFontCondensedTrait) ? FontStretch::CONDENSED + : FontStretch::NORMAL; aFontStyle.size = [font pointSize]; aFontStyle.systemFont = true; } @@ -1998,18 +1997,18 @@ void gfxMacPlatformFontList::GetFacesInitDataForFamily(const fontlist::Family* a } cssWeight *= 100; // scale up to CSS values - StretchRange stretch(FontStretch::Normal()); + StretchRange stretch(FontStretch::NORMAL); if (macTraits & (NSCondensedFontMask | NSNarrowFontMask | NSCompressedFontMask)) { - stretch = StretchRange(FontStretch::Condensed()); + stretch = StretchRange(FontStretch::CONDENSED); } else if (macTraits & NSExpandedFontMask) { - stretch = StretchRange(FontStretch::Expanded()); + stretch = StretchRange(FontStretch::EXPANDED); } // Cocoa fails to set the Italic traits bit for HelveticaLightItalic, // at least (see bug 611855), so check for style name endings as well - SlantStyleRange slantStyle(FontSlantStyle::Normal()); + SlantStyleRange slantStyle(FontSlantStyle::NORMAL); if ((macTraits & NSItalicFontMask) || [facename hasSuffix:@"Italic"] || [facename hasSuffix:@"Oblique"]) { - slantStyle = SlantStyleRange(FontSlantStyle::Italic()); + slantStyle = SlantStyleRange(FontSlantStyle::ITALIC); } bool fixedPitch = (macTraits & NSFixedPitchFontMask) ? true : false; @@ -2035,7 +2034,7 @@ void gfxMacPlatformFontList::GetFacesInitDataForFamily(const fontlist::Family* a NS_ConvertUTF16toUTF8(postscriptFontName), 0, fixedPitch, - WeightRange(FontWeight(cssWeight)), + WeightRange(FontWeight::FromInt(cssWeight)), stretch, slantStyle, charmap, @@ -2072,7 +2071,7 @@ void gfxMacPlatformFontList::ReadFaceNamesForFamily(fontlist::Family* aFamily, // of the macOS UI font; see MacOSFontEntry::GetFontRef(). We pass 16.0 in // order to get a standard text-size face in this case, although it's // unlikely to matter for the purpose of just reading family names. - auto fe = MakeUnique(name, WeightRange(FontWeight::Normal()), false, 16.0); + auto fe = MakeUnique(name, WeightRange(FontWeight::NORMAL), false, 16.0); if (!fe) { continue; } diff --git a/gfx/thebes/gfxTextRun.cpp b/gfx/thebes/gfxTextRun.cpp index f9c645b6b33a..313f77b3a9a6 100644 --- a/gfx/thebes/gfxTextRun.cpp +++ b/gfx/thebes/gfxTextRun.cpp @@ -1789,11 +1789,11 @@ void gfxTextRun::Dump(FILE* out) { for (uint32_t i = 0; i < numGlyphRuns; ++i) { gfxFont* font = glyphRuns[i].mFont; const gfxFontStyle* style = font->GetStyle(); - nsAutoString styleString; - nsStyleUtil::AppendFontSlantStyle(style->style, styleString); + nsAutoCString styleString; + style->style.ToString(styleString); fprintf(out, " [%d] offset=%d %s %f/%g/%s\n", i, glyphRuns[i].mCharacterOffset, font->GetName().get(), style->size, - style->weight.ToFloat(), NS_ConvertUTF16toUTF8(styleString).get()); + style->weight.ToFloat(), styleString.get()); } fprintf(out, " Glyphs:\n"); @@ -2580,8 +2580,8 @@ void gfxFontGroup::InitTextRun(DrawTarget* aDrawTarget, gfxTextRun* aTextRun, nsAutoCString lang; mLanguage->ToUTF8String(lang); nsAutoCString str((const char*)aString, aLength); - nsAutoString styleString; - nsStyleUtil::AppendFontSlantStyle(mStyle.style, styleString); + nsAutoCString styleString; + mStyle.style.ToString(styleString); auto defaultLanguageGeneric = GetDefaultGeneric(mLanguage); MOZ_LOG( log, LogLevel::Warning, @@ -2596,9 +2596,8 @@ void gfxFontGroup::InitTextRun(DrawTarget* aDrawTarget, gfxTextRun* aTextRun, ? "sans-serif" : "none")), lang.get(), static_cast(Script::LATIN), aLength, - mStyle.weight.ToFloat(), mStyle.stretch.Percentage(), - NS_ConvertUTF16toUTF8(styleString).get(), mStyle.size, sizeof(T), - str.get())); + mStyle.weight.ToFloat(), mStyle.stretch.ToFloat(), + styleString.get(), mStyle.size, sizeof(T), str.get())); } // the text is still purely 8-bit; bypass the script-run itemizer @@ -2625,27 +2624,26 @@ void gfxFontGroup::InitTextRun(DrawTarget* aDrawTarget, gfxTextRun* aTextRun, if (MOZ_UNLIKELY(MOZ_LOG_TEST(log, LogLevel::Warning))) { nsAutoCString lang; mLanguage->ToUTF8String(lang); - nsAutoString styleString; - nsStyleUtil::AppendFontSlantStyle(mStyle.style, styleString); + nsAutoCString styleString; + mStyle.style.ToString(styleString); auto defaultLanguageGeneric = GetDefaultGeneric(mLanguage); uint32_t runLen = runLimit - runStart; - MOZ_LOG( - log, LogLevel::Warning, - ("(%s) fontgroup: [%s] default: %s lang: %s script: %d " - "len %d weight: %g stretch: %g%% style: %s size: %6.2f " - "%zu-byte TEXTRUN [%s] ENDTEXTRUN\n", - (mStyle.systemFont ? "textrunui" : "textrun"), - FamilyListToString(mFamilyList).get(), - (defaultLanguageGeneric == StyleGenericFontFamily::Serif - ? "serif" - : (defaultLanguageGeneric == - StyleGenericFontFamily::SansSerif - ? "sans-serif" - : "none")), - lang.get(), static_cast(runScript), runLen, - mStyle.weight.ToFloat(), mStyle.stretch.Percentage(), - NS_ConvertUTF16toUTF8(styleString).get(), mStyle.size, sizeof(T), - NS_ConvertUTF16toUTF8(textPtr + runStart, runLen).get())); + MOZ_LOG(log, LogLevel::Warning, + ("(%s) fontgroup: [%s] default: %s lang: %s script: %d " + "len %d weight: %g stretch: %g%% style: %s size: %6.2f " + "%zu-byte TEXTRUN [%s] ENDTEXTRUN\n", + (mStyle.systemFont ? "textrunui" : "textrun"), + FamilyListToString(mFamilyList).get(), + (defaultLanguageGeneric == StyleGenericFontFamily::Serif + ? "serif" + : (defaultLanguageGeneric == + StyleGenericFontFamily::SansSerif + ? "sans-serif" + : "none")), + lang.get(), static_cast(runScript), runLen, + mStyle.weight.ToFloat(), mStyle.stretch.ToFloat(), + styleString.get(), mStyle.size, sizeof(T), + NS_ConvertUTF16toUTF8(textPtr + runStart, runLen).get())); } InitScriptRun(aDrawTarget, aTextRun, textPtr + runStart, runStart, diff --git a/gfx/thebes/moz.build b/gfx/thebes/moz.build index fe24f2439a70..be85c44845fe 100644 --- a/gfx/thebes/moz.build +++ b/gfx/thebes/moz.build @@ -142,6 +142,7 @@ elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "gtk": elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "windows": REQUIRES_UNIFIED_BUILD = True EXPORTS += [ + "gfxDWriteCommon.h", "gfxDWriteFonts.h", "gfxGDIFont.h", "gfxGDIFontList.h", diff --git a/layout/generic/MathMLTextRunFactory.cpp b/layout/generic/MathMLTextRunFactory.cpp index 22d712f595c7..d699fc7d1ab9 100644 --- a/layout/generic/MathMLTextRunFactory.cpp +++ b/layout/generic/MathMLTextRunFactory.cpp @@ -529,15 +529,15 @@ void MathMLTextRunFactory::RebuildTextRun( // This overrides the initial values specified in fontStyle, to avoid // inconsistencies in which attributes allow CSS changes and which do not. if (mFlags & MATH_FONT_WEIGHT_BOLD) { - font.weight = FontWeight::Bold(); + font.weight = FontWeight::BOLD; if (mFlags & MATH_FONT_STYLING_NORMAL) { - font.style = FontSlantStyle::Normal(); + font.style = FontSlantStyle::NORMAL; } else { - font.style = FontSlantStyle::Italic(); + font.style = FontSlantStyle::ITALIC; } } else if (mFlags & MATH_FONT_STYLING_NORMAL) { - font.style = FontSlantStyle::Normal(); - font.weight = FontWeight::Normal(); + font.style = FontSlantStyle::NORMAL; + font.weight = FontWeight::NORMAL; } else { mathVar = StyleMathVariant::Italic; } @@ -615,20 +615,20 @@ void MathMLTextRunFactory::RebuildTextRun( gfxTextRun* child; if (mathVar == StyleMathVariant::Bold && doMathvariantStyling) { - font.style = FontSlantStyle::Normal(); - font.weight = FontWeight::Bold(); + font.style = FontSlantStyle::NORMAL; + font.weight = FontWeight::BOLD; } else if (mathVar == StyleMathVariant::Italic && doMathvariantStyling) { - font.style = FontSlantStyle::Italic(); - font.weight = FontWeight::Normal(); + font.style = FontSlantStyle::ITALIC; + font.weight = FontWeight::NORMAL; } else if (mathVar == StyleMathVariant::BoldItalic && doMathvariantStyling) { - font.style = FontSlantStyle::Italic(); - font.weight = FontWeight::Bold(); + font.style = FontSlantStyle::ITALIC; + font.weight = FontWeight::BOLD; } else if (mathVar != StyleMathVariant::None) { // Mathvariant overrides fontstyle and fontweight // Need to check to see if mathvariant is actually applied as this function // is used for other purposes. - font.style = FontSlantStyle::Normal(); - font.weight = FontWeight::Normal(); + font.style = FontSlantStyle::NORMAL; + font.weight = FontWeight::NORMAL; } gfxFontGroup* newFontGroup = nullptr; diff --git a/layout/mathml/nsMathMLTokenFrame.cpp b/layout/mathml/nsMathMLTokenFrame.cpp index a815cdd18528..ff328b3d1344 100644 --- a/layout/mathml/nsMathMLTokenFrame.cpp +++ b/layout/mathml/nsMathMLTokenFrame.cpp @@ -41,7 +41,7 @@ eMathMLFrameType nsMathMLTokenFrame::GetMathMLFrameType() { StyleMathVariant mathVariant = StyleFont()->mMathVariant; if ((mathVariant == StyleMathVariant::None && - (StyleFont()->mFont.style == FontSlantStyle::Italic() || + (StyleFont()->mFont.style.IsItalic() || HasAnyStateBits(NS_FRAME_IS_IN_SINGLE_CHAR_MI))) || mathVariant == StyleMathVariant::Italic || mathVariant == StyleMathVariant::BoldItalic || diff --git a/layout/style/FontFaceSet.cpp b/layout/style/FontFaceSet.cpp index b4e7f61bae33..bb12f01de309 100644 --- a/layout/style/FontFaceSet.cpp +++ b/layout/style/FontFaceSet.cpp @@ -201,34 +201,12 @@ void FontFaceSet::ParseFontShorthandForMatching( const nsACString& aFont, StyleFontFamilyList& aFamilyList, FontWeight& aWeight, FontStretch& aStretch, FontSlantStyle& aStyle, ErrorResult& aRv) { - auto style = StyleComputedFontStyleDescriptor::Normal(); - float stretch; - float weight; - RefPtr url = ServoCSSParser::GetURLExtraData(mDocument); - if (!ServoCSSParser::ParseFontShorthandForMatching(aFont, url, aFamilyList, - style, stretch, weight)) { + if (!ServoCSSParser::ParseFontShorthandForMatching( + aFont, url, aFamilyList, aStyle, aStretch, aWeight)) { aRv.ThrowSyntaxError("Invalid font shorthand"); return; } - - switch (style.tag) { - case StyleComputedFontStyleDescriptor::Tag::Normal: - aStyle = FontSlantStyle::Normal(); - break; - case StyleComputedFontStyleDescriptor::Tag::Italic: - aStyle = FontSlantStyle::Italic(); - break; - case StyleComputedFontStyleDescriptor::Tag::Oblique: - MOZ_ASSERT(style.AsOblique()._0 == style.AsOblique()._1, - "We use ComputedFontStyleDescriptor just for convenience, " - "the two values should always match"); - aStyle = FontSlantStyle::Oblique(style.AsOblique()._0); - break; - } - - aWeight = FontWeight(weight); - aStretch = FontStretch::FromStyle(stretch); } static bool HasAnyCharacterInUnicodeRange(gfxUserFontEntry* aEntry, @@ -937,9 +915,10 @@ static WeightRange GetWeightRangeForDescriptor( gfxFontEntry::RangeFlags& aRangeFlags) { if (!aVal) { aRangeFlags |= gfxFontEntry::RangeFlags::eAutoWeight; - return WeightRange(FontWeight::Normal()); + return WeightRange(FontWeight::NORMAL); } - return WeightRange(FontWeight(aVal->_0), FontWeight(aVal->_1)); + return WeightRange(FontWeight::FromFloat(aVal->_0), + FontWeight::FromFloat(aVal->_1)); } static SlantStyleRange GetStyleRangeForDescriptor( @@ -947,20 +926,20 @@ static SlantStyleRange GetStyleRangeForDescriptor( gfxFontEntry::RangeFlags& aRangeFlags) { if (!aVal) { aRangeFlags |= gfxFontEntry::RangeFlags::eAutoSlantStyle; - return SlantStyleRange(FontSlantStyle::Normal()); + return SlantStyleRange(FontSlantStyle::NORMAL); } auto& val = *aVal; switch (val.tag) { case StyleComputedFontStyleDescriptor::Tag::Normal: - return SlantStyleRange(FontSlantStyle::Normal()); + return SlantStyleRange(FontSlantStyle::NORMAL); case StyleComputedFontStyleDescriptor::Tag::Italic: - return SlantStyleRange(FontSlantStyle::Italic()); + return SlantStyleRange(FontSlantStyle::ITALIC); case StyleComputedFontStyleDescriptor::Tag::Oblique: - return SlantStyleRange(FontSlantStyle::Oblique(val.AsOblique()._0), - FontSlantStyle::Oblique(val.AsOblique()._1)); + return SlantStyleRange(FontSlantStyle::FromFloat(val.AsOblique()._0), + FontSlantStyle::FromFloat(val.AsOblique()._1)); } MOZ_ASSERT_UNREACHABLE("How?"); - return SlantStyleRange(FontSlantStyle::Normal()); + return SlantStyleRange(FontSlantStyle::NORMAL); } static StretchRange GetStretchRangeForDescriptor( @@ -968,10 +947,9 @@ static StretchRange GetStretchRangeForDescriptor( gfxFontEntry::RangeFlags& aRangeFlags) { if (!aVal) { aRangeFlags |= gfxFontEntry::RangeFlags::eAutoStretch; - return StretchRange(FontStretch::Normal()); + return StretchRange(FontStretch::NORMAL); } - return StretchRange(FontStretch::FromStyle(aVal->_0), - FontStretch::FromStyle(aVal->_1)); + return StretchRange(aVal->_0, aVal->_1); } // TODO(emilio): Should this take an nsAtom* aFamilyName instead? diff --git a/layout/style/FontFaceSet.h b/layout/style/FontFaceSet.h index 24fcd5dc725f..10bc80a18add 100644 --- a/layout/style/FontFaceSet.h +++ b/layout/style/FontFaceSet.h @@ -10,7 +10,6 @@ #include "mozilla/dom/FontFace.h" #include "mozilla/dom/FontFaceSetBinding.h" #include "mozilla/DOMEventTargetHelper.h" -#include "mozilla/FontPropertyTypes.h" #include "gfxUserFontSet.h" #include "nsICSSLoaderObserver.h" #include "nsIDOMEventListener.h" diff --git a/layout/style/GeckoBindings.cpp b/layout/style/GeckoBindings.cpp index 293895e011cf..873c0422a598 100644 --- a/layout/style/GeckoBindings.cpp +++ b/layout/style/GeckoBindings.cpp @@ -996,47 +996,6 @@ nsTArray* Gecko_AppendFeatureValueHashEntry( aName, aAlternate); } -float Gecko_FontStretch_ToFloat(FontStretch aStretch) { - // Servo represents percentages with 1. being 100%. - return aStretch.Percentage() / 100.0f; -} - -void Gecko_FontStretch_SetFloat(FontStretch* aStretch, float aFloat) { - // Servo represents percentages with 1. being 100%. - // - // Also, the font code assumes a given maximum that style doesn't really need - // to know about. So clamp here at the boundary. - *aStretch = FontStretch(std::min(aFloat * 100.0f, float(FontStretch::kMax))); -} - -void Gecko_FontSlantStyle_SetNormal(FontSlantStyle* aStyle) { - *aStyle = FontSlantStyle::Normal(); -} - -void Gecko_FontSlantStyle_SetItalic(FontSlantStyle* aStyle) { - *aStyle = FontSlantStyle::Italic(); -} - -void Gecko_FontSlantStyle_SetOblique(FontSlantStyle* aStyle, - float aAngleInDegrees) { - *aStyle = FontSlantStyle::Oblique(aAngleInDegrees); -} - -void Gecko_FontSlantStyle_Get(FontSlantStyle aStyle, bool* aNormal, - bool* aItalic, float* aObliqueAngle) { - *aNormal = aStyle.IsNormal(); - *aItalic = aStyle.IsItalic(); - if (aStyle.IsOblique()) { - *aObliqueAngle = aStyle.ObliqueAngle(); - } -} - -float Gecko_FontWeight_ToFloat(FontWeight aWeight) { return aWeight.ToFloat(); } - -void Gecko_FontWeight_SetFloat(FontWeight* aWeight, float aFloat) { - *aWeight = FontWeight(aFloat); -} - void Gecko_CounterStyle_ToPtr(const StyleCounterStyle* aStyle, CounterStylePtr* aPtr) { *aPtr = CounterStylePtr::FromStyle(*aStyle); diff --git a/layout/style/GeckoBindings.h b/layout/style/GeckoBindings.h index a384a0d00ce9..8b434ea8977e 100644 --- a/layout/style/GeckoBindings.h +++ b/layout/style/GeckoBindings.h @@ -443,27 +443,8 @@ NS_DECL_THREADSAFE_FFI_REFCOUNTING(nsIReferrerInfo, nsIReferrerInfo); void Gecko_FillAllImageLayers(nsStyleImageLayers* layers, uint32_t max_len); -float Gecko_FontStretch_ToFloat(mozilla::FontStretch aStretch); - -void Gecko_FontStretch_SetFloat(mozilla::FontStretch* aStretch, - float aFloatValue); - void Gecko_LoadData_Drop(mozilla::StyleLoadData*); -float Gecko_FontSlantStyle_ToFloat(mozilla::FontSlantStyle aStyle); -void Gecko_FontSlantStyle_SetNormal(mozilla::FontSlantStyle*); -void Gecko_FontSlantStyle_SetItalic(mozilla::FontSlantStyle*); - -void Gecko_FontSlantStyle_SetOblique(mozilla::FontSlantStyle*, - float angle_degrees); - -void Gecko_FontSlantStyle_Get(mozilla::FontSlantStyle, bool* normal, - bool* italic, float* oblique_angle); - -float Gecko_FontWeight_ToFloat(mozilla::FontWeight aWeight); - -void Gecko_FontWeight_SetFloat(mozilla::FontWeight* aWeight, float aFloatValue); - void Gecko_nsStyleFont_SetLang(nsStyleFont* font, nsAtom* atom); void Gecko_nsStyleFont_CopyLangFrom(nsStyleFont* aFont, diff --git a/layout/style/ServoBindings.toml b/layout/style/ServoBindings.toml index 6ed22d360996..d7cf6d69fb6b 100644 --- a/layout/style/ServoBindings.toml +++ b/layout/style/ServoBindings.toml @@ -598,6 +598,9 @@ cbindgen-types = [ { gecko = "StyleScrollbarGutter", servo = "crate::values::computed::ScrollbarGutter" }, { gecko = "StyleHyphenateCharacter", servo = "crate::values::computed::HyphenateCharacter" }, { gecko = "StyleContentVisibility", servo = "crate::values::computed::ContentVisibility" }, + { gecko = "StyleFontStyle", servo = "crate::values::computed::font::FontStyle" }, + { gecko = "StyleFontWeight", servo = "crate::values::computed::font::FontWeight" }, + { gecko = "StyleFontStretch", servo = "crate::values::computed::font::FontStretch" }, ] mapped-generic-types = [ diff --git a/layout/style/ServoCSSParser.cpp b/layout/style/ServoCSSParser.cpp index 5dfd179437e7..0ae4c8252fd7 100644 --- a/layout/style/ServoCSSParser.cpp +++ b/layout/style/ServoCSSParser.cpp @@ -59,8 +59,8 @@ bool ServoCSSParser::ParseTransformIntoMatrix(const nsACString& aValue, /* static */ bool ServoCSSParser::ParseFontShorthandForMatching( const nsACString& aValue, URLExtraData* aUrl, StyleFontFamilyList& aList, - StyleComputedFontStyleDescriptor& aStyle, float& aStretch, float& aWeight, - float* aSize) { + StyleFontStyle& aStyle, StyleFontStretch& aStretch, + StyleFontWeight& aWeight, float* aSize) { return Servo_ParseFontShorthandForMatching(&aValue, aUrl, &aList, &aStyle, &aStretch, &aWeight, aSize); } diff --git a/layout/style/ServoCSSParser.h b/layout/style/ServoCSSParser.h index a785e96474f8..eb29bbf3e648 100644 --- a/layout/style/ServoCSSParser.h +++ b/layout/style/ServoCSSParser.h @@ -28,6 +28,9 @@ namespace mozilla { class ServoStyleSet; struct URLExtraData; struct StyleFontFamilyList; +struct StyleFontStretch; +struct StyleFontWeight; +struct StyleFontStyle; union StyleComputedFontStyleDescriptor; namespace css { @@ -124,8 +127,8 @@ class ServoCSSParser { */ static bool ParseFontShorthandForMatching( const nsACString& aValue, URLExtraData* aUrl, StyleFontFamilyList& aList, - StyleComputedFontStyleDescriptor& aStyle, float& aStretch, float& aWeight, - float* aSize = nullptr); + StyleFontStyle& aStyle, StyleFontStretch& aStretch, + StyleFontWeight& aWeight, float* aSize = nullptr); /** * Get a URLExtraData from a document. diff --git a/layout/style/ServoStyleConstsForwards.h b/layout/style/ServoStyleConstsForwards.h index b830dfe7b666..33a821fa80c9 100644 --- a/layout/style/ServoStyleConstsForwards.h +++ b/layout/style/ServoStyleConstsForwards.h @@ -210,6 +210,22 @@ using StyleMatrixTransformOperator = using StyleAtomicUsize = std::atomic; +# define SERVO_FIXED_POINT_HELPERS(T, RawT, FractionBits) \ + static constexpr RawT kPointFive = 1 << (FractionBits - 1); \ + static constexpr uint16_t kScale = 1 << FractionBits; \ + static constexpr float kInverseScale = 1.0f / kScale; \ + static T FromRaw(RawT aRaw) { return {{aRaw}}; } \ + static T FromFloat(float aFloat) { \ + return FromRaw(RawT(aFloat * kScale)); \ + } \ + static T FromInt(RawT aInt) { return FromRaw(RawT(aInt * kScale)); } \ + RawT Raw() const { return _0.value; } \ + uint16_t UnsignedRaw() const { return uint16_t(Raw()); } \ + float ToFloat() const { return Raw() * kInverseScale; } \ + RawT ToIntRounded() const { return (Raw() + kPointFive) >> FractionBits; } \ + bool IsNormal() const { return *this == NORMAL; } \ + inline void ToString(nsACString&) const; + } // namespace mozilla # ifndef HAVE_64BIT_BUILD diff --git a/layout/style/ServoStyleConstsInlines.h b/layout/style/ServoStyleConstsInlines.h index 8bc4b93d143f..47b3f0111fe5 100644 --- a/layout/style/ServoStyleConstsInlines.h +++ b/layout/style/ServoStyleConstsInlines.h @@ -1054,6 +1054,32 @@ inline AspectRatio StyleAspectRatio::ToLayoutRatio() const { : AspectRatio(); } +inline void StyleFontWeight::ToString(nsACString& aString) const { + Servo_FontWeight_ToCss(this, &aString); +} + +inline void StyleFontStretch::ToString(nsACString& aString) const { + Servo_FontStretch_ToCss(this, &aString); +} + +inline void StyleFontStyle::ToString(nsACString& aString) const { + Servo_FontStyle_ToCss(this, &aString); +} + +inline bool StyleFontWeight::IsBold() const { return *this >= BOLD_THRESHOLD; } + +inline bool StyleFontStyle::IsItalic() const { return *this == ITALIC; } + +inline bool StyleFontStyle::IsOblique() const { + return !IsItalic() && !IsNormal(); +} + +inline float StyleFontStyle::ObliqueAngle() const { return ToFloat(); } + +using FontStretch = StyleFontStretch; +using FontSlantStyle = StyleFontStyle; +using FontWeight = StyleFontWeight; + } // namespace mozilla #endif diff --git a/layout/style/nsCSSValue.h b/layout/style/nsCSSValue.h index 352eb00823f2..db54f0a0134d 100644 --- a/layout/style/nsCSSValue.h +++ b/layout/style/nsCSSValue.h @@ -12,7 +12,6 @@ #include "mozilla/Attributes.h" #include "mozilla/CORSMode.h" #include "mozilla/EnumTypeTraits.h" -#include "mozilla/FontPropertyTypes.h" #include "mozilla/MemoryReporting.h" #include "mozilla/ServoBindingTypes.h" #include "mozilla/URLExtraData.h" diff --git a/layout/style/nsStyleUtil.cpp b/layout/style/nsStyleUtil.cpp index e51d73e2512f..149cc1d4b69e 100644 --- a/layout/style/nsStyleUtil.cpp +++ b/layout/style/nsStyleUtil.cpp @@ -9,7 +9,6 @@ #include "mozilla/dom/Document.h" #include "mozilla/ExpandedPrincipal.h" -#include "mozilla/FontPropertyTypes.h" #include "nsIContent.h" #include "nsCSSProps.h" #include "nsContentUtils.h" @@ -327,20 +326,3 @@ bool nsStyleUtil::CSPAllowsInlineStyle( return allowInlineStyle; } - -void nsStyleUtil::AppendFontSlantStyle(const FontSlantStyle& aStyle, - nsAString& aOut) { - if (aStyle.IsNormal()) { - aOut.AppendLiteral("normal"); - } else if (aStyle.IsItalic()) { - aOut.AppendLiteral("italic"); - } else { - aOut.AppendLiteral("oblique"); - auto angle = aStyle.ObliqueAngle(); - if (angle != FontSlantStyle::kDefaultAngle) { - aOut.AppendLiteral(" "); - AppendCSSNumber(angle, aOut); - aOut.AppendLiteral("deg"); - } - } -} diff --git a/layout/style/nsStyleUtil.h b/layout/style/nsStyleUtil.h index 20d5deb61ba5..2983239bd70e 100644 --- a/layout/style/nsStyleUtil.h +++ b/layout/style/nsStyleUtil.h @@ -24,7 +24,6 @@ struct nsCSSValueList; struct nsStylePosition; namespace mozilla { -class FontSlantStyle; namespace dom { class Document; class Element; @@ -55,9 +54,6 @@ class nsStyleUtil { static void AppendEscapedCSSIdent(const nsAString& aIdent, nsAString& aResult); - static void AppendFontSlantStyle(const mozilla::FontSlantStyle&, - nsAString& aResult); - public: static void AppendCSSNumber(float aNumber, nsAString& aResult) { aResult.AppendFloat(aNumber); diff --git a/servo/components/derive_common/cg.rs b/servo/components/derive_common/cg.rs index 2c5268839ffd..ee5543e79748 100644 --- a/servo/components/derive_common/cg.rs +++ b/servo/components/derive_common/cg.rs @@ -143,7 +143,10 @@ pub fn fmap_trait_output(input: &DeriveInput, trait_path: &Path, trait_output: & let ident = &data.ident; GenericArgument::Type(parse_quote!(<#ident as #trait_path>::#trait_output)) }, - ref arg => panic!("arguments {:?} cannot be mapped yet", arg), + &GenericParam::Const(ref inner) => { + let ident = &inner.ident; + GenericArgument::Const(parse_quote!(#ident)) + }, }) .collect(), colon2_token: Default::default(), diff --git a/servo/components/style/font_face.rs b/servo/components/style/font_face.rs index 53e406d4b2fb..757e30bbd698 100644 --- a/servo/components/style/font_face.rs +++ b/servo/components/style/font_face.rs @@ -12,14 +12,14 @@ use crate::parser::{Parse, ParserContext}; use crate::properties::longhands::font_language_override; use crate::shared_lock::{SharedRwLockReadGuard, ToCssWithGuard}; use crate::str::CssStringWriter; -use crate::values::computed::font::FamilyName; +use crate::values::computed::font::{FamilyName, FontStretch}; use crate::values::generics::font::FontStyle as GenericFontStyle; #[cfg(feature = "gecko")] use crate::values::specified::font::SpecifiedFontFeatureSettings; use crate::values::specified::font::SpecifiedFontStyle; #[cfg(feature = "gecko")] use crate::values::specified::font::SpecifiedFontVariationSettings; -use crate::values::specified::font::{AbsoluteFontWeight, FontStretch, MetricsOverride}; +use crate::values::specified::font::{AbsoluteFontWeight, FontStretch as SpecifiedFontStretch, MetricsOverride}; use crate::values::specified::url::SpecifiedUrl; use crate::values::specified::{Angle, NonNegativePercentage}; #[cfg(feature = "gecko")] @@ -170,7 +170,7 @@ fn sort_range(a: T, b: T) -> (T, T) { impl FontWeightRange { /// Returns a computed font-stretch range. pub fn compute(&self) -> ComputedFontWeightRange { - let (min, max) = sort_range(self.0.compute().0, self.1.compute().0); + let (min, max) = sort_range(self.0.compute().value(), self.1.compute().value()); ComputedFontWeightRange(min, max) } } @@ -179,23 +179,23 @@ impl FontWeightRange { /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-stretch #[derive(Clone, Debug, PartialEq, ToShmem)] -pub struct FontStretchRange(pub FontStretch, pub FontStretch); -impl_range!(FontStretchRange, FontStretch); +pub struct FontStretchRange(pub SpecifiedFontStretch, pub SpecifiedFontStretch); +impl_range!(FontStretchRange, SpecifiedFontStretch); -/// The computed representation of the above, so that -/// Gecko can read them easily. +/// The computed representation of the above, so that Gecko can read them +/// easily. #[repr(C)] #[allow(missing_docs)] -pub struct ComputedFontStretchRange(f32, f32); +pub struct ComputedFontStretchRange(FontStretch, FontStretch); impl FontStretchRange { /// Returns a computed font-stretch range. pub fn compute(&self) -> ComputedFontStretchRange { - fn compute_stretch(s: &FontStretch) -> f32 { + fn compute_stretch(s: &SpecifiedFontStretch) -> FontStretch { match *s { - FontStretch::Keyword(ref kw) => kw.compute().0, - FontStretch::Stretch(ref p) => p.0.get(), - FontStretch::System(..) => unreachable!(), + SpecifiedFontStretch::Keyword(ref kw) => kw.compute(), + SpecifiedFontStretch::Stretch(ref p) => FontStretch::from_percentage(p.0.get()), + SpecifiedFontStretch::System(..) => unreachable!(), } } diff --git a/servo/components/style/properties/gecko.mako.rs b/servo/components/style/properties/gecko.mako.rs index 9588d0e6147e..c3c7e4523da6 100644 --- a/servo/components/style/properties/gecko.mako.rs +++ b/servo/components/style/properties/gecko.mako.rs @@ -895,57 +895,9 @@ fn static_assert() { } } - pub fn set_font_weight(&mut self, v: longhands::font_weight::computed_value::T) { - unsafe { bindings::Gecko_FontWeight_SetFloat(&mut self.gecko.mFont.weight, v.0) }; - } - ${impl_simple_copy('font_weight', 'mFont.weight')} - - pub fn clone_font_weight(&self) -> longhands::font_weight::computed_value::T { - let weight: f32 = unsafe { - bindings::Gecko_FontWeight_ToFloat(self.gecko.mFont.weight) - }; - longhands::font_weight::computed_value::T(weight) - } - - pub fn set_font_stretch(&mut self, v: longhands::font_stretch::computed_value::T) { - unsafe { - bindings::Gecko_FontStretch_SetFloat( - &mut self.gecko.mFont.stretch, - v.value(), - ) - }; - } - ${impl_simple_copy('font_stretch', 'mFont.stretch')} - pub fn clone_font_stretch(&self) -> longhands::font_stretch::computed_value::T { - use crate::values::computed::font::FontStretch; - use crate::values::computed::Percentage; - use crate::values::generics::NonNegative; - - let stretch = - unsafe { bindings::Gecko_FontStretch_ToFloat(self.gecko.mFont.stretch) }; - debug_assert!(stretch >= 0.); - - FontStretch(NonNegative(Percentage(stretch))) - } - - pub fn set_font_style(&mut self, v: longhands::font_style::computed_value::T) { - use crate::values::generics::font::FontStyle; - let s = &mut self.gecko.mFont.style; - unsafe { - match v { - FontStyle::Normal => bindings::Gecko_FontSlantStyle_SetNormal(s), - FontStyle::Italic => bindings::Gecko_FontSlantStyle_SetItalic(s), - FontStyle::Oblique(ref angle) => { - bindings::Gecko_FontSlantStyle_SetOblique(s, angle.0.degrees()) - } - } - } - } - ${impl_simple_copy('font_style', 'mFont.style')} - pub fn clone_font_style(&self) -> longhands::font_style::computed_value::T { - use crate::values::computed::font::FontStyle; - FontStyle::from_gecko(self.gecko.mFont.style) - } + ${impl_simple('font_weight', 'mFont.weight')} + ${impl_simple('font_stretch', 'mFont.stretch')} + ${impl_simple('font_style', 'mFont.style')} ${impl_simple_type_with_conversion("font_synthesis", "mFont.synthesis")} diff --git a/servo/components/style/properties/longhands/font.mako.rs b/servo/components/style/properties/longhands/font.mako.rs index 65ee3cbb6cef..6be921159714 100644 --- a/servo/components/style/properties/longhands/font.mako.rs +++ b/servo/components/style/properties/longhands/font.mako.rs @@ -352,11 +352,10 @@ pub mod system_font { fn to_computed_value(&self, cx: &Context) -> Self::ComputedValue { use crate::gecko_bindings::bindings; use crate::gecko_bindings::structs::nsFont; - use std::mem; - use crate::values::computed::Percentage; + use crate::values::computed::font::FontSize; use crate::values::specified::font::KeywordInfo; - use crate::values::computed::font::{FontSize, FontStretch, FontStyle}; use crate::values::generics::NonNegative; + use std::mem; let mut system = mem::MaybeUninit::::uninit(); let system = unsafe { @@ -368,20 +367,15 @@ pub mod system_font { ); &mut *system.as_mut_ptr() }; - let font_weight = longhands::font_weight::computed_value::T::from_gecko_weight(system.weight); - let font_stretch = FontStretch(NonNegative(Percentage(unsafe { - bindings::Gecko_FontStretch_ToFloat(system.stretch) - }))); - let font_style = FontStyle::from_gecko(system.style); let ret = ComputedSystemFont { font_family: system.family.clone(), font_size: FontSize { size: NonNegative(cx.maybe_zoom_text(system.size.0)), keyword_info: KeywordInfo::none() }, - font_weight, - font_stretch, - font_style, + font_weight: system.weight, + font_stretch: system.stretch, + font_style: system.style, font_size_adjust: system.sizeAdjust, % for kwprop in kw_font_props: ${kwprop}: longhands::${kwprop}::computed_value::T::from_gecko_keyword( diff --git a/servo/components/style/style_adjuster.rs b/servo/components/style/style_adjuster.rs index 98890ce09d59..8bc75970bd99 100644 --- a/servo/components/style/style_adjuster.rs +++ b/servo/components/style/style_adjuster.rs @@ -357,12 +357,11 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> { #[cfg(feature = "gecko")] fn adjust_for_mathvariant(&mut self) { use crate::properties::longhands::_moz_math_variant::computed_value::T as MozMathVariant; - use crate::properties::longhands::font_weight::computed_value::T as FontWeight; - use crate::values::generics::font::FontStyle; + use crate::values::computed::font::{FontWeight, FontStyle}; if self.style.get_font().clone__moz_math_variant() != MozMathVariant::None { let font_style = self.style.mutate_font(); - font_style.set_font_weight(FontWeight::normal()); - font_style.set_font_style(FontStyle::Normal); + font_style.set_font_weight(FontWeight::NORMAL); + font_style.set_font_style(FontStyle::NORMAL); } } diff --git a/servo/components/style/values/animated/font.rs b/servo/components/style/values/animated/font.rs index 1f0eb749fc71..f890a3b2bd3d 100644 --- a/servo/components/style/values/animated/font.rs +++ b/servo/components/style/values/animated/font.rs @@ -5,18 +5,11 @@ //! Animation implementation for various font-related types. use super::{Animate, Procedure, ToAnimatedZero}; -use crate::values::computed::font::{FontVariationSettings, FontWeight}; +use crate::values::computed::font::FontVariationSettings; use crate::values::computed::Number; use crate::values::distance::{ComputeSquaredDistance, SquaredDistance}; use crate::values::generics::font::{FontSettings as GenericFontSettings, FontTag, VariationValue}; -impl ToAnimatedZero for FontWeight { - #[inline] - fn to_animated_zero(&self) -> Result { - Ok(FontWeight::normal()) - } -} - /// impl Animate for FontVariationSettings { #[inline] diff --git a/servo/components/style/values/computed/font.rs b/servo/components/style/values/computed/font.rs index b639f7843f22..466af6aef13b 100644 --- a/servo/components/style/values/computed/font.rs +++ b/servo/components/style/values/computed/font.rs @@ -4,27 +4,23 @@ //! Computed values for font properties -#[cfg(feature = "gecko")] -use crate::gecko_bindings::{bindings, structs}; use crate::parser::{Parse, ParserContext}; use crate::values::animated::ToAnimatedValue; use crate::values::computed::{ - Angle, Context, Integer, Length, NonNegativeLength, NonNegativeNumber, NonNegativePercentage, + Angle, Context, Integer, Length, NonNegativeLength, NonNegativeNumber, + Number, Percentage, ToComputedValue }; -use crate::values::computed::{Number, Percentage, ToComputedValue}; use crate::values::generics::font::{FeatureTagValue, FontSettings, VariationValue}; use crate::values::generics::{font as generics, NonNegative}; use crate::values::specified::font::{ self as specified, KeywordInfo, MAX_FONT_WEIGHT, MIN_FONT_WEIGHT, }; use crate::values::specified::length::{FontBaseSize, NoCalcLength}; -use crate::values::CSSFloat; use crate::Atom; use cssparser::{serialize_identifier, CssStringWriter, Parser}; #[cfg(feature = "gecko")] use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use std::fmt::{self, Write}; -use std::hash::{Hash, Hasher}; use style_traits::{CssWriter, ParseError, ToCss}; pub use crate::values::computed::Length as MozScriptMinSize; @@ -32,34 +28,159 @@ pub use crate::values::specified::font::{FontSynthesis, MozScriptSizeMultiplier} pub use crate::values::specified::font::{XLang, XTextZoom}; pub use crate::values::specified::Integer as SpecifiedInteger; +/// Generic template for font property type classes that use a fixed-point +/// internal representation with `FRACTION_BITS` for the fractional part. +/// +/// Values are constructed from and exposed as floating-point, but stored +/// internally as fixed point, so there will be a quantization effect on +/// fractional values, depending on the number of fractional bits used. +/// +/// Using (16-bit) fixed-point types rather than floats for these style +/// attributes reduces the memory footprint of gfxFontEntry and gfxFontStyle; it +/// will also tend to reduce the number of distinct font instances that get +/// created, particularly when styles are animated or set to arbitrary values +/// (e.g. by sliders in the UI), which should reduce pressure on graphics +/// resources and improve cache hit rates. +/// +/// cbindgen:derive-lt +/// cbindgen:derive-lte +/// cbindgen:derive-gt +/// cbindgen:derive-gte +#[repr(C)] +#[derive( + Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue, +)] +pub struct FixedPoint { + value: T, +} + +impl FixedPoint +where + T: num_traits::cast::AsPrimitive, + f32: num_traits::cast::AsPrimitive, +{ + const SCALE: u16 = 1 << FRACTION_BITS; + const INVERSE_SCALE: f32 = 1.0 / Self::SCALE as f32; + + /// Returns a fixed-point bit from a floating-point context. + fn from_float(v: f32) -> Self { + use num_traits::cast::AsPrimitive; + Self { + value: (v * Self::SCALE as f32).round().as_(), + } + } + + /// Returns the floating-point representation. + fn to_float(&self) -> f32 { + self.value.as_() * Self::INVERSE_SCALE + } +} + +/// font-weight: range 1..1000, fractional values permitted; keywords +/// 'normal', 'bold' aliased to 400, 700 respectively. +/// +/// We use an unsigned 10.6 fixed-point value (range 0.0 - 1023.984375) +pub const FONT_WEIGHT_FRACTION_BITS: u16 = 6; + +/// This is an alias which is useful mostly as a cbindgen / C++ inference +/// workaround. +pub type FontWeightFixedPoint = FixedPoint; + /// A value for the font-weight property per: /// /// https://drafts.csswg.org/css-fonts-4/#propdef-font-weight /// -/// This is effectively just a `Number`. +/// cbindgen:derive-lt +/// cbindgen:derive-lte +/// cbindgen:derive-gt +/// cbindgen:derive-gte #[derive( - Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss, ToResolvedValue, + Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue, )] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -pub struct FontWeight(pub Number); - -impl Hash for FontWeight { - fn hash(&self, hasher: &mut H) { - hasher.write_u64((self.0 * 10000.).trunc() as u64); - } -} - +#[repr(C)] +pub struct FontWeight(FontWeightFixedPoint); impl ToAnimatedValue for FontWeight { type AnimatedValue = Number; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { - self.0 + self.value() } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { - FontWeight(animated.max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT)) + FontWeight::from_float(animated) + } +} + +impl ToCss for FontWeight { + fn to_css(&self, dest: &mut CssWriter) -> fmt::Result + where + W: fmt::Write, + { + self.value().to_css(dest) + } +} + +impl FontWeight { + /// The `normal` keyword. + pub const NORMAL: FontWeight = FontWeight(FontWeightFixedPoint { value: 400 << FONT_WEIGHT_FRACTION_BITS }); + + /// The `bold` value. + pub const BOLD: FontWeight = FontWeight(FontWeightFixedPoint { value: 700 << FONT_WEIGHT_FRACTION_BITS }); + + /// The threshold from which we consider a font bold. + pub const BOLD_THRESHOLD: FontWeight = FontWeight(FontWeightFixedPoint { value: 600 << FONT_WEIGHT_FRACTION_BITS }); + + /// Returns the `normal` keyword value. + pub fn normal() -> Self { + Self::NORMAL + } + + /// Weither this weight is bold + pub fn is_bold(&self) -> bool { + *self >= Self::BOLD_THRESHOLD + } + + /// Returns the value as a float. + pub fn value(&self) -> f32 { + self.0.to_float() + } + + /// Construct a valid weight from a float value. + pub fn from_float(v: f32) -> Self { + Self(FixedPoint::from_float(v.max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT))) + } + + /// Return the bolder weight. + /// + /// See the table in: + /// https://drafts.csswg.org/css-fonts-4/#font-weight-numeric-values + pub fn bolder(self) -> Self { + let value = self.value(); + if value < 350. { + return Self::NORMAL; + } + if value < 550. { + return Self::BOLD; + } + Self::from_float(value.max(900.)) + } + + /// Return the lighter weight. + /// + /// See the table in: + /// https://drafts.csswg.org/css-fonts-4/#font-weight-numeric-values + pub fn lighter(self) -> Self { + let value = self.value(); + if value < 550. { + return Self::from_float(value.min(100.)) + } + if value < 750. { + return Self::NORMAL; + } + Self::BOLD } } @@ -85,60 +206,6 @@ pub struct FontSize { pub keyword_info: KeywordInfo, } -impl FontWeight { - /// Value for normal - pub fn normal() -> Self { - FontWeight(400.) - } - - /// Value for bold - pub fn bold() -> Self { - FontWeight(700.) - } - - /// Convert from an Gecko weight - #[cfg(feature = "gecko")] - pub fn from_gecko_weight(weight: structs::FontWeight) -> Self { - // we allow a wider range of weights than is parseable - // because system fonts may provide custom values - let weight = unsafe { bindings::Gecko_FontWeight_ToFloat(weight) }; - FontWeight(weight) - } - - /// Weither this weight is bold - pub fn is_bold(&self) -> bool { - self.0 > 500. - } - - /// Return the bolder weight. - /// - /// See the table in: - /// https://drafts.csswg.org/css-fonts-4/#font-weight-numeric-values - pub fn bolder(self) -> Self { - if self.0 < 350. { - FontWeight(400.) - } else if self.0 < 550. { - FontWeight(700.) - } else { - FontWeight(self.0.max(900.)) - } - } - - /// Return the lighter weight. - /// - /// See the table in: - /// https://drafts.csswg.org/css-fonts-4/#font-weight-numeric-values - pub fn lighter(self) -> Self { - if self.0 < 550. { - FontWeight(self.0.min(100.)) - } else if self.0 < 750. { - FontWeight(400.) - } else { - FontWeight(700.) - } - } -} - impl FontSize { /// The actual computed font size. #[inline] @@ -771,76 +838,66 @@ impl ToComputedValue for specified::MathDepth { } } -/// A wrapper over an `Angle`, that handles clamping to the appropriate range -/// for `font-style` animation. -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss, ToResolvedValue)] -#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -pub struct FontStyleAngle(pub Angle); +/// - Use a signed 8.8 fixed-point value (representable range -128.0..128) +/// +/// Values of below -90 or above 90 not permitted, so we use out of +/// range values to represent normal | oblique +pub const FONT_STYLE_FRACTION_BITS: u16 = 8; -impl ToAnimatedValue for FontStyleAngle { - type AnimatedValue = Angle; - - #[inline] - fn to_animated_value(self) -> Self::AnimatedValue { - self.0 - } - - #[inline] - fn from_animated_value(animated: Self::AnimatedValue) -> Self { - FontStyleAngle(Angle::from_degrees( - animated - .degrees() - .min(specified::FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES) - .max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES), - )) - } -} - -impl Hash for FontStyleAngle { - fn hash(&self, hasher: &mut H) { - hasher.write_u64((self.0.degrees() * 10000.).trunc() as u64); - } -} +/// This is an alias which is useful mostly as a cbindgen / C++ inference +/// workaround. +pub type FontStyleFixedPoint = FixedPoint; /// The computed value of `font-style`. /// -/// FIXME(emilio): Angle should be a custom type to handle clamping during -/// animation. -pub type FontStyle = generics::FontStyle; +/// - Define out of range values min value (-128.0) as meaning 'normal' +/// - Define max value (127.99609375) as 'italic' +/// - Other values represent 'oblique ' +/// - Note that 'oblique 0deg' is distinct from 'normal' (should it be?) +/// +/// cbindgen:derive-lt +/// cbindgen:derive-lte +/// cbindgen:derive-gt +/// cbindgen:derive-gte +#[derive( + Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue, +)] +#[repr(C)] +pub struct FontStyle(FontStyleFixedPoint); impl FontStyle { + /// The normal keyword. + pub const NORMAL: FontStyle = FontStyle(FontStyleFixedPoint { value: 100 << FONT_STYLE_FRACTION_BITS }); + /// The italic keyword. + pub const ITALIC: FontStyle = FontStyle(FontStyleFixedPoint { value: 101 << FONT_STYLE_FRACTION_BITS }); + + /// The default angle for `font-style: oblique`. + /// See also https://github.com/w3c/csswg-drafts/issues/2295 + pub const DEFAULT_OBLIQUE_DEGREES: i16 = 14; + + /// The `oblique` keyword with the default degrees. + pub const OBLIQUE: FontStyle = FontStyle(FontStyleFixedPoint { value: Self::DEFAULT_OBLIQUE_DEGREES << FONT_STYLE_FRACTION_BITS }); + /// The `normal` value. #[inline] pub fn normal() -> Self { - generics::FontStyle::Normal + Self::NORMAL } - /// The default angle for font-style: oblique. This is 20deg per spec: - /// - /// https://drafts.csswg.org/css-fonts-4/#valdef-font-style-oblique-angle - #[inline] - pub fn default_angle() -> FontStyleAngle { - FontStyleAngle(Angle::from_degrees( - specified::DEFAULT_FONT_STYLE_OBLIQUE_ANGLE_DEGREES, + /// Returns the oblique angle for this style. + pub fn oblique(degrees: f32) -> Self { + Self(FixedPoint::from_float( + degrees + .max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES) + .min(specified::FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES) )) } - /// Get the font style from Gecko's nsFont struct. - #[cfg(feature = "gecko")] - pub fn from_gecko(style: structs::FontSlantStyle) -> Self { - let mut angle = 0.; - let mut italic = false; - let mut normal = false; - unsafe { - bindings::Gecko_FontSlantStyle_Get(style, &mut normal, &mut italic, &mut angle); - } - if normal { - return generics::FontStyle::Normal; - } - if italic { - return generics::FontStyle::Italic; - } - generics::FontStyle::Oblique(FontStyleAngle(Angle::from_degrees(angle))) + /// Returns the oblique angle for this style. + pub fn oblique_degrees(&self) -> f32 { + debug_assert_ne!(*self, Self::NORMAL); + debug_assert_ne!(*self, Self::ITALIC); + self.0.to_float() } } @@ -849,43 +906,173 @@ impl ToCss for FontStyle { where W: fmt::Write, { - match *self { - generics::FontStyle::Normal => dest.write_str("normal"), - generics::FontStyle::Italic => dest.write_str("italic"), - generics::FontStyle::Oblique(ref angle) => { - dest.write_str("oblique")?; - // Use `degrees` instead of just comparing Angle because - // `degrees` can return slightly different values due to - // floating point conversions. - if angle.0.degrees() != Self::default_angle().0.degrees() { - dest.write_char(' ')?; - angle.to_css(dest)?; - } - Ok(()) - }, + if *self == Self::NORMAL { + return dest.write_str("normal") + } + if *self == Self::ITALIC { + return dest.write_str("italic") + } + if *self == Self::OBLIQUE { + return dest.write_str("oblique"); + } + dest.write_str("oblique ")?; + let angle = Angle::from_degrees(self.oblique_degrees()); + angle.to_css(dest)?; + Ok(()) + } +} + +impl ToAnimatedValue for FontStyle { + type AnimatedValue = generics::FontStyle; + + #[inline] + fn to_animated_value(self) -> Self::AnimatedValue { + if self == Self::NORMAL { + return generics::FontStyle::Normal + } + if self == Self::ITALIC { + return generics::FontStyle::Italic + } + generics::FontStyle::Oblique(Angle::from_degrees(self.oblique_degrees())) + } + + #[inline] + fn from_animated_value(animated: Self::AnimatedValue) -> Self { + match animated { + generics::FontStyle::Normal => Self::NORMAL, + generics::FontStyle::Italic => Self::ITALIC, + generics::FontStyle::Oblique(ref angle) => Self::oblique(angle.degrees()), } } } + +/// font-stretch is a percentage relative to normal. +/// +/// We use an unsigned 10.6 fixed-point value (range 0.0 - 1023.984375) +/// +/// We arbitrarily limit here to 1000%. (If that becomes a problem, we could +/// reduce the number of fractional bits and increase the limit.) +pub const FONT_STRETCH_FRACTION_BITS: u16 = 6; + +/// This is an alias which is useful mostly as a cbindgen / C++ inference +/// workaround. +pub type FontStretchFixedPoint = FixedPoint; + + /// A value for the font-stretch property per: /// /// https://drafts.csswg.org/css-fonts-4/#propdef-font-stretch +/// +/// cbindgen:derive-lt +/// cbindgen:derive-lte +/// cbindgen:derive-gt +/// cbindgen:derive-gte #[derive( - Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss, ToResolvedValue, + Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue, )] -#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -pub struct FontStretch(pub NonNegativePercentage); +#[repr(C)] +pub struct FontStretch(pub FontStretchFixedPoint); impl FontStretch { + /// The fraction bits, as an easy-to-access-constant. + pub const FRACTION_BITS: u16 = FONT_STRETCH_FRACTION_BITS; + /// 0.5 in our floating point representation. + pub const HALF: u16 = 1 << (Self::FRACTION_BITS - 1); + + /// The `ultra-condensed` keyword. + pub const ULTRA_CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint { value: 50 << Self::FRACTION_BITS }); + /// The `extra-condensed` keyword. + pub const EXTRA_CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint { value: (62 << Self::FRACTION_BITS) + Self::HALF }); + /// The `condensed` keyword. + pub const CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint { value: 75 << Self::FRACTION_BITS }); + /// The `semi-condensed` keyword. + pub const SEMI_CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint { value: (87 << Self::FRACTION_BITS) + Self::HALF }); + /// The `normal` keyword. + pub const NORMAL: FontStretch = FontStretch(FontStretchFixedPoint { value: 100 << Self::FRACTION_BITS }); + /// The `semi-expanded` keyword. + pub const SEMI_EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint { value: (112 << Self::FRACTION_BITS) + Self::HALF }); + /// The `expanded` keyword. + pub const EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint { value: 125 << Self::FRACTION_BITS }); + /// The `extra-expanded` keyword. + pub const EXTRA_EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint { value: 150 << Self::FRACTION_BITS }); + /// The `ultra-expanded` keyword. + pub const ULTRA_EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint { value: 200 << Self::FRACTION_BITS }); + /// 100% pub fn hundred() -> Self { - FontStretch(NonNegativePercentage::hundred()) + Self::NORMAL } - /// The float value of the percentage + /// Converts to a computed percentage. #[inline] - pub fn value(&self) -> CSSFloat { - ((self.0).0).0 + pub fn to_percentage(&self) -> Percentage { + Percentage(self.0.to_float() / 100.0) + } + + /// Converts from a computed percentage value. + pub fn from_percentage(p: f32) -> Self { + Self(FixedPoint::from_float((p * 100.).max(0.0).min(1000.0))) + } + + /// Returns a relevant stretch value from a keyword. + /// https://drafts.csswg.org/css-fonts-4/#font-stretch-prop + pub fn from_keyword(kw: specified::FontStretchKeyword) -> Self { + use specified::FontStretchKeyword::*; + match kw { + UltraCondensed => Self::ULTRA_CONDENSED, + ExtraCondensed => Self::EXTRA_CONDENSED, + Condensed => Self::CONDENSED, + SemiCondensed => Self::SEMI_CONDENSED, + Normal => Self::NORMAL, + SemiExpanded => Self::SEMI_EXPANDED, + Expanded => Self::EXPANDED, + ExtraExpanded => Self::EXTRA_EXPANDED, + UltraExpanded => Self::ULTRA_EXPANDED, + } + } + + /// Returns the stretch keyword if we map to one of the relevant values. + pub fn as_keyword(&self) -> Option { + use specified::FontStretchKeyword::*; + // TODO: Can we use match here? + if *self == Self::ULTRA_CONDENSED { + return Some(UltraCondensed); + } + if *self == Self::EXTRA_CONDENSED { + return Some(ExtraCondensed); + } + if *self == Self::CONDENSED { + return Some(Condensed); + } + if *self == Self::SEMI_CONDENSED { + return Some(SemiCondensed); + } + if *self == Self::NORMAL { + return Some(Normal); + } + if *self == Self::SEMI_EXPANDED { + return Some(SemiExpanded); + } + if *self == Self::EXPANDED { + return Some(Expanded); + } + if *self == Self::EXTRA_EXPANDED { + return Some(ExtraExpanded); + } + if *self == Self::ULTRA_EXPANDED { + return Some(UltraExpanded); + } + None + } +} + +impl ToCss for FontStretch { + fn to_css(&self, dest: &mut CssWriter) -> fmt::Result + where + W: fmt::Write, + { + self.to_percentage().to_css(dest) } } @@ -894,17 +1081,11 @@ impl ToAnimatedValue for FontStretch { #[inline] fn to_animated_value(self) -> Self::AnimatedValue { - self.0.to_animated_value() + self.to_percentage() } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { - FontStretch(NonNegativePercentage::from_animated_value(animated)) - } -} - -impl Hash for FontStretch { - fn hash(&self, hasher: &mut H) { - hasher.write_u64((self.value() * 10000.).trunc() as u64); + Self::from_percentage(animated.0) } } diff --git a/servo/components/style/values/distance.rs b/servo/components/style/values/distance.rs index a4259ce8c6be..fef376cf5f73 100644 --- a/servo/components/style/values/distance.rs +++ b/servo/components/style/values/distance.rs @@ -50,6 +50,13 @@ impl ComputeSquaredDistance for u16 { } } +impl ComputeSquaredDistance for i16 { + #[inline] + fn compute_squared_distance(&self, other: &Self) -> Result { + Ok(SquaredDistance::from_sqrt((*self - *other).abs() as f64)) + } +} + impl ComputeSquaredDistance for i32 { #[inline] fn compute_squared_distance(&self, other: &Self) -> Result { diff --git a/servo/components/style/values/resolved/mod.rs b/servo/components/style/values/resolved/mod.rs index 4ec84c2ae147..817585002bbb 100644 --- a/servo/components/style/values/resolved/mod.rs +++ b/servo/components/style/values/resolved/mod.rs @@ -63,11 +63,12 @@ macro_rules! trivial_to_resolved_value { trivial_to_resolved_value!(()); trivial_to_resolved_value!(bool); trivial_to_resolved_value!(f32); -trivial_to_resolved_value!(i32); trivial_to_resolved_value!(u8); trivial_to_resolved_value!(i8); trivial_to_resolved_value!(u16); +trivial_to_resolved_value!(i16); trivial_to_resolved_value!(u32); +trivial_to_resolved_value!(i32); trivial_to_resolved_value!(usize); trivial_to_resolved_value!(String); trivial_to_resolved_value!(Box); diff --git a/servo/components/style/values/specified/font.rs b/servo/components/style/values/specified/font.rs index bbf3c871c2e2..e3a7067d657b 100644 --- a/servo/components/style/values/specified/font.rs +++ b/servo/components/style/values/specified/font.rs @@ -7,10 +7,10 @@ use crate::context::QuirksMode; use crate::font_metrics::FontMetricsProvider; use crate::parser::{Parse, ParserContext}; -use crate::values::computed::font::{FamilyName, FontFamilyList, FontStyleAngle, SingleFontFamily}; +use crate::values::computed::font::{FamilyName, FontFamilyList, SingleFontFamily}; use crate::values::computed::FontSizeAdjust as ComputedFontSizeAdjust; use crate::values::computed::{font as computed, Length, NonNegativeLength}; -use crate::values::computed::{Angle as ComputedAngle, Percentage as ComputedPercentage}; +use crate::values::computed::{Percentage as ComputedPercentage}; use crate::values::computed::{CSSPixelLength, Context, ToComputedValue}; use crate::values::generics::font::VariationValue; use crate::values::generics::font::{ @@ -164,7 +164,7 @@ impl ToComputedValue for FontWeight { #[inline] fn from_computed_value(computed: &computed::FontWeight) -> Self { FontWeight::Absolute(AbsoluteFontWeight::Weight(Number::from_computed_value( - &computed.0, + &computed.value(), ))) } } @@ -189,10 +189,10 @@ impl AbsoluteFontWeight { pub fn compute(&self) -> computed::FontWeight { match *self { AbsoluteFontWeight::Weight(weight) => { - computed::FontWeight(weight.get().max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT)) + computed::FontWeight::from_float(weight.get()) }, - AbsoluteFontWeight::Normal => computed::FontWeight::normal(), - AbsoluteFontWeight::Bold => computed::FontWeight::bold(), + AbsoluteFontWeight::Normal => computed::FontWeight::NORMAL, + AbsoluteFontWeight::Bold => computed::FontWeight::BOLD, } } } @@ -268,33 +268,24 @@ impl ToComputedValue for SpecifiedFontStyle { fn to_computed_value(&self, _: &Context) -> Self::ComputedValue { match *self { - generics::FontStyle::Normal => generics::FontStyle::Normal, - generics::FontStyle::Italic => generics::FontStyle::Italic, - generics::FontStyle::Oblique(ref angle) => { - generics::FontStyle::Oblique(FontStyleAngle(Self::compute_angle(angle))) - }, + Self::Normal => computed::FontStyle::NORMAL, + Self::Italic => computed::FontStyle::ITALIC, + Self::Oblique(ref angle) => computed::FontStyle::oblique(angle.degrees()), } } fn from_computed_value(computed: &Self::ComputedValue) -> Self { - match *computed { - generics::FontStyle::Normal => generics::FontStyle::Normal, - generics::FontStyle::Italic => generics::FontStyle::Italic, - generics::FontStyle::Oblique(ref angle) => { - generics::FontStyle::Oblique(Angle::from_computed_value(&angle.0)) - }, + if *computed == computed::FontStyle::NORMAL { + return Self::Normal; } + if *computed == computed::FontStyle::ITALIC { + return Self::Italic; + } + let degrees = computed.oblique_degrees(); + generics::FontStyle::Oblique(Angle::from_degrees(degrees, /* was_calc = */ false)) } } -/// The default angle for `font-style: oblique`. -/// -/// NOTE(emilio): As of right now this diverges from the spec, which specifies -/// 20, because it's not updated yet to account for the resolution in: -/// -/// https://github.com/w3c/csswg-drafts/issues/2295 -pub const DEFAULT_FONT_STYLE_OBLIQUE_ANGLE_DEGREES: f32 = 14.; - /// From https://drafts.csswg.org/css-fonts-4/#valdef-font-style-oblique-angle: /// /// Values less than -90deg or values greater than 90deg are @@ -315,10 +306,6 @@ impl SpecifiedFontStyle { .min(FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES) } - fn compute_angle(angle: &Angle) -> ComputedAngle { - ComputedAngle::from_degrees(Self::compute_angle_degrees(angle)) - } - /// Parse a suitable angle for font-style: oblique. pub fn parse_angle<'i, 't>( context: &ParserContext, @@ -341,7 +328,7 @@ impl SpecifiedFontStyle { /// The default angle for `font-style: oblique`. pub fn default_angle() -> Angle { Angle::from_degrees( - DEFAULT_FONT_STYLE_OBLIQUE_ANGLE_DEGREES, + computed::FontStyle::DEFAULT_OBLIQUE_DEGREES as f32, /* was_calc = */ false, ) } @@ -390,7 +377,6 @@ impl ToComputedValue for FontStyle { #[derive( Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, )] -#[repr(u8)] pub enum FontStretch { Stretch(NonNegativePercentage), Keyword(FontStretchKeyword), @@ -416,57 +402,15 @@ pub enum FontStretchKeyword { } impl FontStretchKeyword { - /// Resolves the value of the keyword as specified in: - /// - /// https://drafts.csswg.org/css-fonts-4/#font-stretch-prop - pub fn compute(&self) -> ComputedPercentage { - use self::FontStretchKeyword::*; - ComputedPercentage(match *self { - UltraCondensed => 0.5, - ExtraCondensed => 0.625, - Condensed => 0.75, - SemiCondensed => 0.875, - Normal => 1., - SemiExpanded => 1.125, - Expanded => 1.25, - ExtraExpanded => 1.5, - UltraExpanded => 2., - }) + /// Turns the keyword into a computed value. + pub fn compute(&self) -> computed::FontStretch { + computed::FontStretch::from_keyword(*self) } /// Does the opposite operation to `compute`, in order to serialize keywords /// if possible. - pub fn from_percentage(percentage: f32) -> Option { - use self::FontStretchKeyword::*; - // NOTE(emilio): Can't use `match` because of rust-lang/rust#41620. - if percentage == 0.5 { - return Some(UltraCondensed); - } - if percentage == 0.625 { - return Some(ExtraCondensed); - } - if percentage == 0.75 { - return Some(Condensed); - } - if percentage == 0.875 { - return Some(SemiCondensed); - } - if percentage == 1. { - return Some(Normal); - } - if percentage == 1.125 { - return Some(SemiExpanded); - } - if percentage == 1.25 { - return Some(Expanded); - } - if percentage == 1.5 { - return Some(ExtraExpanded); - } - if percentage == 2. { - return Some(UltraExpanded); - } - None + pub fn from_percentage(p: f32) -> Option { + computed::FontStretch::from_percentage(p).as_keyword() } } @@ -485,16 +429,17 @@ impl ToComputedValue for FontStretch { fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { match *self { FontStretch::Stretch(ref percentage) => { - computed::FontStretch(percentage.to_computed_value(context)) + let percentage = percentage.to_computed_value(context).0; + computed::FontStretch::from_percentage(percentage.0) }, - FontStretch::Keyword(ref kw) => computed::FontStretch(NonNegative(kw.compute())), + FontStretch::Keyword(ref kw) => kw.compute(), FontStretch::System(_) => self.compute_system(context), } } fn from_computed_value(computed: &Self::ComputedValue) -> Self { FontStretch::Stretch(NonNegativePercentage::from_computed_value(&NonNegative( - (computed.0).0, + computed.to_percentage() ))) } } diff --git a/servo/ports/geckolib/cbindgen.toml b/servo/ports/geckolib/cbindgen.toml index 6d940d798f33..c89058742cde 100644 --- a/servo/ports/geckolib/cbindgen.toml +++ b/servo/ports/geckolib/cbindgen.toml @@ -898,3 +898,21 @@ renaming_overrides_prefixing = true public: inline nsAtom* AsAtom() const; """ + +"FontWeight" = """ + SERVO_FIXED_POINT_HELPERS(StyleFontWeight, uint16_t, StyleFONT_WEIGHT_FRACTION_BITS); + + inline bool IsBold() const; +""" + +"FontStyle" = """ + SERVO_FIXED_POINT_HELPERS(StyleFontStyle, int16_t, StyleFONT_STYLE_FRACTION_BITS); + + inline bool IsItalic() const; + inline bool IsOblique() const; + inline float ObliqueAngle() const; +""" + +"FontStretch" = """ + SERVO_FIXED_POINT_HELPERS(StyleFontStretch, uint16_t, StyleFONT_STRETCH_FRACTION_BITS); +""" diff --git a/servo/ports/geckolib/glue.rs b/servo/ports/geckolib/glue.rs index 7b14d12916cd..c797519b66e2 100644 --- a/servo/ports/geckolib/glue.rs +++ b/servo/ports/geckolib/glue.rs @@ -28,7 +28,7 @@ use style::data::{self, ElementStyles}; use style::dom::{ShowSubtreeData, TDocument, TElement, TNode}; use style::driver; use style::error_reporting::{ContextualParseError, ParseErrorReporter}; -use style::font_face::{self, ComputedFontStyleDescriptor, FontFaceSourceListComponent, Source}; +use style::font_face::{self, FontFaceSourceListComponent, Source}; use style::font_metrics::{get_metrics_provider_for_product, FontMetricsProvider}; use style::gecko::data::{GeckoStyleSheet, PerDocumentStyleData, PerDocumentStyleDataImpl}; use style::gecko::restyle_damage::GeckoRestyleDamage; @@ -137,7 +137,7 @@ use style::traversal_flags::{self, TraversalFlags}; use style::use_counters::UseCounters; use style::values::animated::{Animate, Procedure, ToAnimatedZero}; use style::values::computed::easing::ComputedLinearStop; -use style::values::computed::font::{FontFamily, FontFamilyList, GenericFontFamily}; +use style::values::computed::font::{FontFamily, FontFamilyList, GenericFontFamily, FontWeight, FontStyle, FontStretch}; use style::values::computed::{self, Context, ToComputedValue}; use style::values::distance::ComputeSquaredDistance; use style::values::specified::gecko::IntersectionObserverRootMargin; @@ -5139,14 +5139,12 @@ pub extern "C" fn Servo_DeclarationBlock_SetKeywordValue( longhands::font_size::SpecifiedValue::from_html_size(value as u8) }, FontStyle => { - let val = if value == structs::NS_FONT_STYLE_ITALIC { + style::values::specified::FontStyle::Specified(if value == structs::NS_FONT_STYLE_ITALIC { FontStyle::Italic } else { debug_assert_eq!(value, structs::NS_FONT_STYLE_NORMAL); FontStyle::Normal - }; - - ToComputedValue::from_computed_value(&val) + }) }, FontWeight => longhands::font_weight::SpecifiedValue::from_gecko_keyword(value), ListStyleType => Box::new(longhands::list_style_type::SpecifiedValue::from_gecko_keyword(value)), @@ -7017,17 +7015,14 @@ pub unsafe extern "C" fn Servo_ParseFontShorthandForMatching( value: &nsACString, data: *mut URLExtraData, family: &mut FontFamilyList, - style: &mut ComputedFontStyleDescriptor, - stretch: &mut f32, - weight: &mut f32, + style: &mut FontStyle, + stretch: &mut FontStretch, + weight: &mut FontWeight, size: Option<&mut f32>, ) -> bool { use style::properties::shorthands::font; - use style::values::computed::font::FontWeight as ComputedFontWeight; + use style::values::specified::font as specified; use style::values::generics::font::FontStyle as GenericFontStyle; - use style::values::specified::font::{ - FontFamily, FontSize, FontStretch, FontStyle, FontWeight, SpecifiedFontStyle, - }; let string = value.as_str_unchecked(); let mut input = ParserInput::new(&string); @@ -7050,44 +7045,41 @@ pub unsafe extern "C" fn Servo_ParseFontShorthandForMatching( // The system font is not acceptable, so we return false. match font.font_family { - FontFamily::Values(list) => *family = list, - FontFamily::System(_) => return false, + specified::FontFamily::Values(list) => *family = list, + specified::FontFamily::System(_) => return false, } let specified_font_style = match font.font_style { - FontStyle::Specified(ref s) => s, - FontStyle::System(_) => return false, + specified::FontStyle::Specified(ref s) => s, + specified::FontStyle::System(_) => return false, }; *style = match *specified_font_style { - GenericFontStyle::Normal => ComputedFontStyleDescriptor::Normal, - GenericFontStyle::Italic => ComputedFontStyleDescriptor::Italic, - GenericFontStyle::Oblique(ref angle) => { - let angle = SpecifiedFontStyle::compute_angle_degrees(angle); - ComputedFontStyleDescriptor::Oblique(angle, angle) - }, + GenericFontStyle::Normal => FontStyle::NORMAL, + GenericFontStyle::Italic => FontStyle::ITALIC, + GenericFontStyle::Oblique(ref angle) => FontStyle::oblique(angle.degrees()), }; *stretch = match font.font_stretch { - FontStretch::Keyword(ref k) => k.compute().0, - FontStretch::Stretch(ref p) => p.0.get(), - FontStretch::System(_) => return false, + specified::FontStretch::Keyword(ref k) => k.compute(), + specified::FontStretch::Stretch(ref p) => FontStretch::from_percentage(p.0.get()), + specified::FontStretch::System(_) => return false, }; *weight = match font.font_weight { - FontWeight::Absolute(w) => w.compute().0, + specified::FontWeight::Absolute(w) => w.compute(), // Resolve relative font weights against the initial of font-weight // (normal, which is equivalent to 400). - FontWeight::Bolder => ComputedFontWeight::normal().bolder().0, - FontWeight::Lighter => ComputedFontWeight::normal().lighter().0, - FontWeight::System(_) => return false, + specified::FontWeight::Bolder => FontWeight::normal().bolder(), + specified::FontWeight::Lighter => FontWeight::normal().lighter(), + specified::FontWeight::System(_) => return false, }; // XXX This is unfinished; see values::specified::FontSize::ToComputedValue // for a more complete implementation (but we can't use it as-is). if let Some(size) = size { *size = match font.font_size { - FontSize::Length(lp) => { + specified::FontSize::Length(lp) => { use style::values::generics::transform::ToAbsoluteLength; match lp.to_pixel_length(None) { Ok(len) => len, @@ -7095,7 +7087,7 @@ pub unsafe extern "C" fn Servo_ParseFontShorthandForMatching( } }, // Map absolute-size keywords to sizes. - FontSize::Keyword(info) => { + specified::FontSize::Keyword(info) => { let metrics = get_metrics_provider_for_product(); // TODO: Maybe get a meaningful language / quirks-mode from the // caller? @@ -7104,7 +7096,7 @@ pub unsafe extern "C" fn Servo_ParseFontShorthandForMatching( info.kw.to_length_without_context(quirks_mode, &metrics, &language, family).0.px() } // smaller, larger not currently supported - FontSize::Smaller | FontSize::Larger | FontSize::System(_) => { + specified::FontSize::Smaller | specified::FontSize::Larger | specified::FontSize::System(_) => { return false; } }; @@ -7348,6 +7340,31 @@ pub extern "C" fn Servo_LengthPercentage_ToCss( lp.to_css(&mut CssWriter::new(result)).unwrap(); } +#[no_mangle] +pub extern "C" fn Servo_FontStyle_ToCss(s: &FontStyle, result: &mut nsACString) { + s.to_css(&mut CssWriter::new(result)).unwrap() +} + +#[no_mangle] +pub extern "C" fn Servo_FontWeight_ToCss(w: &FontWeight, result: &mut nsACString) { + w.to_css(&mut CssWriter::new(result)).unwrap() +} + +#[no_mangle] +pub extern "C" fn Servo_FontStretch_ToCss(s: &FontStretch, result: &mut nsACString) { + s.to_css(&mut CssWriter::new(result)).unwrap() +} + +#[no_mangle] +pub extern "C" fn Servo_FontStretch_SerializeKeyword(s: &FontStretch, result: &mut nsACString) -> bool { + let kw = match s.as_keyword() { + Some(kw) => kw, + None => return false, + }; + kw.to_css(&mut CssWriter::new(result)).unwrap(); + true +} + #[no_mangle] pub unsafe extern "C" fn Servo_CursorKind_Parse( cursor: &nsACString, diff --git a/taskcluster/ci/fetch/toolchains.yml b/taskcluster/ci/fetch/toolchains.yml index a009ede17adf..cf09a0715211 100644 --- a/taskcluster/ci/fetch/toolchains.yml +++ b/taskcluster/ci/fetch/toolchains.yml @@ -245,12 +245,12 @@ wine: strip-components: 1 add-prefix: wine-source/ -cbindgen-0.24.2: +cbindgen-0.24.3: description: cbindgen source code fetch: type: git repo: https://github.com/eqrion/cbindgen - revision: 3d06ae1fc4984b82ada2d84ce74c7af06ffd499d + revision: f43ccfc047a1a160267f32355c5e5e7154a2665a cctools-port: description: cctools-port source code diff --git a/taskcluster/ci/toolchain/cbindgen.yml b/taskcluster/ci/toolchain/cbindgen.yml index 4d0425ea0533..0de95ac5c146 100644 --- a/taskcluster/ci/toolchain/cbindgen.yml +++ b/taskcluster/ci/toolchain/cbindgen.yml @@ -16,7 +16,7 @@ job-defaults: fetch: # If you update this, make sure to update the minimum version in # build/moz.configure/bindgen.configure as well. - - cbindgen-0.24.2 + - cbindgen-0.24.3 linux64-cbindgen: treeherder: diff --git a/widget/android/nsLookAndFeel.cpp b/widget/android/nsLookAndFeel.cpp index 79251847f552..f7c62ff3bf7c 100644 --- a/widget/android/nsLookAndFeel.cpp +++ b/widget/android/nsLookAndFeel.cpp @@ -418,9 +418,9 @@ nsresult nsLookAndFeel::NativeGetFloat(FloatID aID, float& aResult) { bool nsLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, gfxFontStyle& aFontStyle) { aFontName.AssignLiteral("Roboto"); - aFontStyle.style = FontSlantStyle::Normal(); - aFontStyle.weight = FontWeight::Normal(); - aFontStyle.stretch = FontStretch::Normal(); + aFontStyle.style = FontSlantStyle::NORMAL; + aFontStyle.weight = FontWeight::NORMAL; + aFontStyle.stretch = FontStretch::NORMAL; aFontStyle.size = 9.0 * 96.0f / 72.0f; aFontStyle.systemFont = true; return true; diff --git a/widget/cocoa/nsLookAndFeel.mm b/widget/cocoa/nsLookAndFeel.mm index 30a4e0885bb2..347a3264fa04 100644 --- a/widget/cocoa/nsLookAndFeel.mm +++ b/widget/cocoa/nsLookAndFeel.mm @@ -548,9 +548,9 @@ bool nsLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, gfxFontStyle& // hack for now if (aID == FontID::MozWindow || aID == FontID::MozDocument) { - aFontStyle.style = mozilla::FontSlantStyle::Normal(); - aFontStyle.weight = mozilla::FontWeight::Normal(); - aFontStyle.stretch = mozilla::FontStretch::Normal(); + aFontStyle.style = mozilla::FontSlantStyle::NORMAL; + aFontStyle.weight = mozilla::FontWeight::NORMAL; + aFontStyle.stretch = mozilla::FontStretch::NORMAL; aFontStyle.size = 14; aFontStyle.systemFont = true; diff --git a/widget/gtk/nsLookAndFeel.cpp b/widget/gtk/nsLookAndFeel.cpp index 3728c818d180..0a5f9a5acecc 100644 --- a/widget/gtk/nsLookAndFeel.cpp +++ b/widget/gtk/nsLookAndFeel.cpp @@ -1017,7 +1017,7 @@ nsresult nsLookAndFeel::NativeGetFloat(FloatID aID, float& aResult) { static void GetSystemFontInfo(GtkStyleContext* aStyle, nsString* aFontName, gfxFontStyle* aFontStyle) { - aFontStyle->style = FontSlantStyle::Normal(); + aFontStyle->style = FontSlantStyle::NORMAL; // As in // https://git.gnome.org/browse/gtk+/tree/gtk/gtkwidget.c?h=3.22.19#n10333 @@ -1031,10 +1031,11 @@ static void GetSystemFontInfo(GtkStyleContext* aStyle, nsString* aFontName, NS_ConvertUTF8toUTF16 family(pango_font_description_get_family(desc)); *aFontName = quote + family + quote; - aFontStyle->weight = FontWeight(pango_font_description_get_weight(desc)); + aFontStyle->weight = + FontWeight::FromInt(pango_font_description_get_weight(desc)); // FIXME: Set aFontStyle->stretch correctly! - aFontStyle->stretch = FontStretch::Normal(); + aFontStyle->stretch = FontStretch::NORMAL; float size = float(pango_font_description_get_size(desc)) / PANGO_SCALE; diff --git a/widget/headless/HeadlessLookAndFeelGTK.cpp b/widget/headless/HeadlessLookAndFeelGTK.cpp index f79d3e7efd37..11ad5008afcc 100644 --- a/widget/headless/HeadlessLookAndFeelGTK.cpp +++ b/widget/headless/HeadlessLookAndFeelGTK.cpp @@ -209,9 +209,9 @@ nsresult HeadlessLookAndFeel::NativeGetFloat(FloatID aID, float& aResult) { bool HeadlessLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, gfxFontStyle& aFontStyle) { // Default to san-serif for everything. - aFontStyle.style = FontSlantStyle::Normal(); - aFontStyle.weight = FontWeight::Normal(); - aFontStyle.stretch = FontStretch::Normal(); + aFontStyle.style = FontSlantStyle::NORMAL; + aFontStyle.weight = FontWeight::NORMAL; + aFontStyle.stretch = FontStretch::NORMAL; aFontStyle.size = 14; aFontStyle.systemFont = true; diff --git a/widget/nsXPLookAndFeel.cpp b/widget/nsXPLookAndFeel.cpp index b2cb80525623..d9552530c59f 100644 --- a/widget/nsXPLookAndFeel.cpp +++ b/widget/nsXPLookAndFeel.cpp @@ -982,9 +982,9 @@ bool nsXPLookAndFeel::LookAndFeelFontToStyle(const LookAndFeelFont& aFont, aName = aFont.name(); aStyle = gfxFontStyle(); aStyle.size = aFont.size(); - aStyle.weight = FontWeight(aFont.weight()); + aStyle.weight = FontWeight::FromInt(aFont.weight()); aStyle.style = - aFont.italic() ? FontSlantStyle::Italic() : FontSlantStyle::Normal(); + aFont.italic() ? FontSlantStyle::ITALIC : FontSlantStyle::NORMAL; aStyle.systemFont = true; return true; } diff --git a/widget/windows/nsLookAndFeel.cpp b/widget/windows/nsLookAndFeel.cpp index 7c3e19a12de7..b96e63a1b5d0 100644 --- a/widget/windows/nsLookAndFeel.cpp +++ b/widget/windows/nsLookAndFeel.cpp @@ -626,9 +626,9 @@ LookAndFeelFont nsLookAndFeel::GetLookAndFeelFontInternal( result.size() = pixelHeight; result.italic() = !!aLogFont.lfItalic; // FIXME: Other weights? - result.weight() = ((aLogFont.lfWeight == FW_BOLD) ? FontWeight::Bold() - : FontWeight::Normal()) - .ToFloat(); + result.weight() = + ((aLogFont.lfWeight == FW_BOLD) ? FontWeight::BOLD : FontWeight::NORMAL) + .ToFloat(); return result; }