Bug 1773558 - Move fixed-point font types to Rust. r=layout-reviewers,jfkthame

Now that cbindgen and rust support const generics, it seems more simple.

This centralizes all the relevant font constants etc in rust and avoids
conversions when going from rust to C++ and vice versa.

Differential Revision: https://phabricator.services.mozilla.com/D148847
This commit is contained in:
Emilio Cobos Álvarez
2022-06-13 00:59:23 +00:00
parent 87a0fd94ac
commit 42a711655b
56 changed files with 820 additions and 1164 deletions

View File

@@ -501,14 +501,11 @@ void TextAttrsMgr::FontStyleTextAttr::ExposeValue(
RefPtr<nsAtom> atom = NS_Atomize("italic"); RefPtr<nsAtom> atom = NS_Atomize("italic");
aAttributes->SetAttribute(nsGkAtoms::font_style, atom); aAttributes->SetAttribute(nsGkAtoms::font_style, atom);
} else { } else {
auto angle = aValue.ObliqueAngle(); nsAutoCString s;
nsString string(u"oblique"_ns); aValue.ToString(s);
if (angle != FontSlantStyle::kDefaultAngle) { nsString wide;
string.AppendLiteral(" "); CopyUTF8toUTF16(s, wide);
nsStyleUtil::AppendCSSNumber(angle, string); aAttributes->SetAttribute(nsGkAtoms::font_style, std::move(wide));
string.AppendLiteral("deg");
}
aAttributes->SetAttribute(nsGkAtoms::font_style, std::move(string));
} }
} }
@@ -543,7 +540,8 @@ bool TextAttrsMgr::FontWeightTextAttr::GetValueFor(LocalAccessible* aAccessible,
void TextAttrsMgr::FontWeightTextAttr::ExposeValue(AccAttributes* aAttributes, void TextAttrsMgr::FontWeightTextAttr::ExposeValue(AccAttributes* aAttributes,
const FontWeight& aValue) { const FontWeight& aValue) {
aAttributes->SetAttribute(nsGkAtoms::fontWeight, aValue.ToIntRounded()); int value = aValue.ToIntRounded();
aAttributes->SetAttribute(nsGkAtoms::fontWeight, value);
} }
FontWeight TextAttrsMgr::FontWeightTextAttr::GetFontWeight(nsIFrame* aFrame) { 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 // bold font, i.e. synthetic bolding is used. (Simply returns false on any
// platforms that don't use the multi-strike synthetic bolding.) // platforms that don't use the multi-strike synthetic bolding.)
if (font->ApplySyntheticBold()) { if (font->ApplySyntheticBold()) {
return FontWeight::Bold(); return FontWeight::BOLD;
} }
// On Windows, font->GetStyle()->weight will give the same weight as // On Windows, font->GetStyle()->weight will give the same weight as

View File

@@ -22,7 +22,7 @@ option(env="CBINDGEN", nargs=1, when=cbindgen_is_needed, help="Path to cbindgen"
def check_cbindgen_version(cbindgen, fatal=False): def check_cbindgen_version(cbindgen, fatal=False):
log.debug("trying cbindgen: %s" % cbindgen) log.debug("trying cbindgen: %s" % cbindgen)
cbindgen_min_version = Version("0.24.2") cbindgen_min_version = Version("0.24.3")
# cbindgen x.y.z # cbindgen x.y.z
version = Version(check_cmd_output(cbindgen, "--version").strip().split(" ")[1]) version = Version(check_cmd_output(cbindgen, "--version").strip().split(" ")[1])

View File

@@ -101,15 +101,9 @@ static void SerializeFontForCanvas(const StyleFontFamilyList& aList,
// Re-serialize the font shorthand as required by the canvas spec. // Re-serialize the font shorthand as required by the canvas spec.
aUsedFont.Truncate(); aUsedFont.Truncate();
if (aStyle.style.IsItalic()) { if (!aStyle.style.IsNormal()) {
aUsedFont.Append("italic "); aStyle.style.ToString(aUsedFont);
} else if (aStyle.style.IsOblique()) { aUsedFont.Append(" ");
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 ");
}
} }
// font-weight is serialized as a number // 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. // font-stretch is serialized using CSS Fonts 3 keywords, not percentages.
if (!aStyle.stretch.IsNormal()) { if (!aStyle.stretch.IsNormal() &&
if (aStyle.stretch == FontStretch::UltraCondensed()) { Servo_FontStretch_SerializeKeyword(&aStyle.stretch, &aUsedFont)) {
aUsedFont.Append("ultra-condensed "); aUsedFont.Append(" ");
} 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 ");
}
} }
// Serialize the computed (not specified) size, and the family name(s). // 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 // In the OffscreenCanvas case we don't have the context necessary to call
// GetFontStyleForServo(), as we do in the main-thread canvas context, so // GetFontStyleForServo(), as we do in the main-thread canvas context, so
// instead we borrow ParseFontShorthandForMatching to parse the attribute. // instead we borrow ParseFontShorthandForMatching to parse the attribute.
float stretch = FontStretch::Normal().Percentage(),
weight = FontWeight::Normal().ToFloat(), size = 10.0;
StyleComputedFontStyleDescriptor style( StyleComputedFontStyleDescriptor style(
StyleComputedFontStyleDescriptor::Normal()); StyleComputedFontStyleDescriptor::Normal());
StyleFontFamilyList list; StyleFontFamilyList list;
gfxFontStyle fontStyle;
float size = 0.0f;
if (!ServoCSSParser::ParseFontShorthandForMatching( if (!ServoCSSParser::ParseFontShorthandForMatching(
aFont, nullptr, list, style, stretch, weight, &size)) { aFont, nullptr, list, fontStyle.style, fontStyle.stretch,
fontStyle.weight, &size)) {
return false; return false;
} }
gfxFontStyle fontStyle;
fontStyle.size = size; 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: Get a userFontSet from the Worker and pass to the fontGroup
// TODO: Should we be passing a language? Where from? // TODO: Should we be passing a language? Where from?
@@ -189,9 +155,8 @@ bool OffscreenCanvasRenderingContext2D::SetFontInternal(const nsACString& aFont,
1.0); // aDevToCssSize 1.0); // aDevToCssSize
CurrentState().fontGroup = fontGroup; CurrentState().fontGroup = fontGroup;
SerializeFontForCanvas(list, fontStyle, CurrentState().font); SerializeFontForCanvas(list, fontStyle, CurrentState().font);
CurrentState().fontFont = CurrentState().fontFont = nsFont(StyleFontFamily{list, false, false},
nsFont(StyleFontFamily{list, false, false}, StyleCSSPixelLength::FromPixels(size));
StyleCSSPixelLength::FromPixels(float(fontStyle.size)));
CurrentState().fontLanguage = nullptr; CurrentState().fontLanguage = nullptr;
CurrentState().fontExplicitLanguage = false; CurrentState().fontExplicitLanguage = false;
return true; return true;

View File

@@ -591,10 +591,10 @@ void MathMLElement::MapMathMLAttributesInto(
str.CompressWhitespace(); str.CompressWhitespace();
if (str.EqualsASCII("normal")) { if (str.EqualsASCII("normal")) {
aDecls.SetKeywordValue(eCSSProperty_font_weight, aDecls.SetKeywordValue(eCSSProperty_font_weight,
FontWeight::Normal().ToFloat()); FontWeight::NORMAL.ToFloat());
} else if (str.EqualsASCII("bold")) { } else if (str.EqualsASCII("bold")) {
aDecls.SetKeywordValue(eCSSProperty_font_weight, aDecls.SetKeywordValue(eCSSProperty_font_weight,
FontWeight::Bold().ToFloat()); FontWeight::BOLD.ToFloat());
} }
} }
} }

View File

@@ -5,6 +5,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "ScaledFontDWrite.h" #include "ScaledFontDWrite.h"
#include "gfxDWriteCommon.h"
#include "UnscaledFontDWrite.h" #include "UnscaledFontDWrite.h"
#include "PathD2D.h" #include "PathD2D.h"
#include "gfxFont.h" #include "gfxFont.h"
@@ -86,38 +87,6 @@ static bool DoGrayscale(IDWriteFontFace* aDWFace, Float ppem) {
return true; 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, ScaledFontDWrite::ScaledFontDWrite(IDWriteFontFace* aFontFace,
const RefPtr<UnscaledFont>& aUnscaledFont, const RefPtr<UnscaledFont>& aUnscaledFont,
Float aSize, bool aUseEmbeddedBitmap, Float aSize, bool aUseEmbeddedBitmap,
@@ -132,7 +101,7 @@ ScaledFontDWrite::ScaledFontDWrite(IDWriteFontFace* aFontFace,
mStyle = SkFontStyle(aStyle->weight.ToIntRounded(), mStyle = SkFontStyle(aStyle->weight.ToIntRounded(),
DWriteFontStretchFromStretch(aStyle->stretch), DWriteFontStretchFromStretch(aStyle->stretch),
// FIXME(jwatt): also use kOblique_Slant // FIXME(jwatt): also use kOblique_Slant
aStyle->style == FontSlantStyle::Normal() aStyle->style == FontSlantStyle::NORMAL
? SkFontStyle::kUpright_Slant ? SkFontStyle::kUpright_Slant
: SkFontStyle::kItalic_Slant); : SkFontStyle::kItalic_Slant);
} }

View File

@@ -18,7 +18,7 @@
#include <string.h> #include <string.h>
#include "mozilla/Assertions.h" #include "mozilla/Assertions.h"
#include "mozilla/TextUtils.h" #include "mozilla/ServoStyleConsts.h"
#include "nsString.h" #include "nsString.h"
/* /*
@@ -28,309 +28,9 @@
namespace mozilla { namespace mozilla {
/** using FontSlantStyle = StyleFontStyle;
* Generic template for font property type classes that use a fixed-point using FontWeight = StyleFontWeight;
* internal representation. using FontStretch = StyleFontStretch;
* 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 InternalType, unsigned FractionBits, int Min, int Max>
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<InternalType>(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<uint16_t, 6, 1, 1000> {
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<uint16_t, 6, 0, 1000> {
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 <angle>?
* values of <angle> 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 <angle>'
* - Note that 'oblique 0deg' is distinct from 'normal' (should it be?)
*/
class FontSlantStyle final : public FontPropertyValue<int16_t, 8, -90, 90> {
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;
};
/** /**
* Convenience type to hold a <min, max> pair representing a range of values. * Convenience type to hold a <min, max> pair representing a range of values.
@@ -338,7 +38,7 @@ class FontSlantStyle final : public FontPropertyValue<int16_t, 8, -90, 90> {
* The min and max are both inclusive, so when min == max the range represents * The min and max are both inclusive, so when min == max the range represents
* a single value (not an empty range). * a single value (not an empty range).
*/ */
template <class T> template <class T, class Derived>
class FontPropertyRange { class FontPropertyRange {
// This implementation assumes the underlying property type is a 16-bit value // This implementation assumes the underlying property type is a 16-bit value
// (see FromScalar and AsScalar below). // (see FromScalar and AsScalar below).
@@ -392,29 +92,22 @@ class FontPropertyRange {
* *
* This depends on the underlying property type being a 16-bit value! * This depends on the underlying property type being a 16-bit value!
*/ */
typedef uint32_t ScalarType; using ScalarType = uint32_t;
ScalarType AsScalar() const { ScalarType AsScalar() const {
return (mValues.first.ForHash() << 16) | mValues.second.ForHash(); return (mValues.first.UnsignedRaw() << 16) | mValues.second.UnsignedRaw();
} }
/* static Derived FromScalar(ScalarType aScalar) {
* FIXME: static_assert(std::is_base_of_v<FontPropertyRange, Derived>);
* FromScalar is defined in each individual subclass, because I can't return Derived(T::FromRaw(aScalar >> 16), T::FromRaw(aScalar & 0xffff));
* 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)));
} }
*/
protected: protected:
std::pair<T, T> mValues; std::pair<T, T> mValues;
}; };
class WeightRange : public FontPropertyRange<FontWeight> { class WeightRange : public FontPropertyRange<FontWeight, WeightRange> {
public: public:
WeightRange(FontWeight aMin, FontWeight aMax) WeightRange(FontWeight aMin, FontWeight aMax)
: FontPropertyRange(aMin, aMax) {} : FontPropertyRange(aMin, aMax) {}
@@ -430,14 +123,9 @@ class WeightRange : public FontPropertyRange<FontWeight> {
aOutString.AppendFloat(Max().ToFloat()); 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<FontStretch> { class StretchRange : public FontPropertyRange<FontStretch, StretchRange> {
public: public:
StretchRange(FontStretch aMin, FontStretch aMax) StretchRange(FontStretch aMin, FontStretch aMax)
: FontPropertyRange(aMin, aMax) {} : FontPropertyRange(aMin, aMax) {}
@@ -447,21 +135,16 @@ class StretchRange : public FontPropertyRange<FontStretch> {
StretchRange(const StretchRange& aOther) = default; StretchRange(const StretchRange& aOther) = default;
void ToString(nsACString& aOutString, const char* aDelim = "..") const { void ToString(nsACString& aOutString, const char* aDelim = "..") const {
aOutString.AppendFloat(Min().Percentage()); aOutString.AppendFloat(Min().ToFloat());
if (!IsSingle()) { if (!IsSingle()) {
aOutString.Append(aDelim); 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<FontSlantStyle> { class SlantStyleRange
: public FontPropertyRange<FontSlantStyle, SlantStyleRange> {
public: public:
SlantStyleRange(FontSlantStyle aMin, FontSlantStyle aMax) SlantStyleRange(FontSlantStyle aMin, FontSlantStyle aMax)
: FontPropertyRange(aMin, aMax) {} : FontPropertyRange(aMin, aMax) {}
@@ -477,12 +160,6 @@ class SlantStyleRange : public FontPropertyRange<FontSlantStyle> {
Max().ToString(aOutString); Max().ToString(aOutString);
} }
} }
static SlantStyleRange FromScalar(ScalarType aScalar) {
return SlantStyleRange(
FontSlantStyle(FontSlantStyle::InternalType(aScalar >> 16)),
FontSlantStyle(FontSlantStyle::InternalType(aScalar & 0xffff)));
}
}; };
} // namespace mozilla } // namespace mozilla

View File

@@ -10,7 +10,6 @@
#include <cstdint> #include <cstdint>
#include "gfxFontConstants.h" // for NS_FONT_KERNING_AUTO, etc #include "gfxFontConstants.h" // for NS_FONT_KERNING_AUTO, etc
#include "gfxFontVariations.h" #include "gfxFontVariations.h"
#include "mozilla/FontPropertyTypes.h"
#include "mozilla/ServoStyleConstsInlines.h" #include "mozilla/ServoStyleConstsInlines.h"
#include "mozilla/StyleColorInlines.h" // for StyleRGBA #include "mozilla/StyleColorInlines.h" // for StyleRGBA
#include "nsTArray.h" // for nsTArray #include "nsTArray.h" // for nsTArray
@@ -54,9 +53,9 @@ struct nsFont final {
// Font-selection/rendering properties corresponding to CSS font-style, // Font-selection/rendering properties corresponding to CSS font-style,
// font-weight, font-stretch. These are all 16-bit types. // font-weight, font-stretch. These are all 16-bit types.
FontSlantStyle style = FontSlantStyle::Normal(); FontSlantStyle style = FontSlantStyle::NORMAL;
FontWeight weight = FontWeight::Normal(); FontWeight weight = FontWeight::NORMAL;
FontStretch stretch = FontStretch::Normal(); FontStretch stretch = FontStretch::NORMAL;
// Some font-variant-alternates property values require // Some font-variant-alternates property values require
// font-specific settings defined via @font-feature-values rules. // font-specific settings defined via @font-feature-values rules.

View File

@@ -278,7 +278,7 @@ bool Family::FindAllFacesForStyleInternal(FontList* aList,
// calculate which one we want. // calculate which one we want.
// Note that we cannot simply return it as not all 4 faces are necessarily // Note that we cannot simply return it as not all 4 faces are necessarily
// present. // present.
bool wantBold = aStyle.weight >= FontWeight(600); bool wantBold = aStyle.weight.IsBold();
bool wantItalic = !aStyle.style.IsNormal(); bool wantItalic = !aStyle.style.IsNormal();
uint8_t faceIndex = uint8_t faceIndex =
(wantItalic ? kItalicMask : 0) | (wantBold ? kBoldMask : 0); (wantItalic ? kItalicMask : 0) | (wantBold ? kBoldMask : 0);

View File

@@ -35,33 +35,34 @@
#define ENHANCED_CONTRAST_VALUE_NAME L"EnhancedContrastLevel" #define ENHANCED_CONTRAST_VALUE_NAME L"EnhancedContrastLevel"
// FIXME: This shouldn't look at constants probably.
static inline DWRITE_FONT_STRETCH DWriteFontStretchFromStretch( static inline DWRITE_FONT_STRETCH DWriteFontStretchFromStretch(
mozilla::FontStretch aStretch) { mozilla::FontStretch aStretch) {
if (aStretch == mozilla::FontStretch::UltraCondensed()) { if (aStretch == mozilla::FontStretch::ULTRA_CONDENSED) {
return DWRITE_FONT_STRETCH_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; return DWRITE_FONT_STRETCH_EXTRA_CONDENSED;
} }
if (aStretch == mozilla::FontStretch::Condensed()) { if (aStretch == mozilla::FontStretch::CONDENSED) {
return DWRITE_FONT_STRETCH_CONDENSED; return DWRITE_FONT_STRETCH_CONDENSED;
} }
if (aStretch == mozilla::FontStretch::SemiCondensed()) { if (aStretch == mozilla::FontStretch::SEMI_CONDENSED) {
return DWRITE_FONT_STRETCH_SEMI_CONDENSED; return DWRITE_FONT_STRETCH_SEMI_CONDENSED;
} }
if (aStretch == mozilla::FontStretch::Normal()) { if (aStretch == mozilla::FontStretch::NORMAL) {
return DWRITE_FONT_STRETCH_NORMAL; return DWRITE_FONT_STRETCH_NORMAL;
} }
if (aStretch == mozilla::FontStretch::SemiExpanded()) { if (aStretch == mozilla::FontStretch::SEMI_EXPANDED) {
return DWRITE_FONT_STRETCH_SEMI_EXPANDED; return DWRITE_FONT_STRETCH_SEMI_EXPANDED;
} }
if (aStretch == mozilla::FontStretch::Expanded()) { if (aStretch == mozilla::FontStretch::EXPANDED) {
return DWRITE_FONT_STRETCH_EXPANDED; return DWRITE_FONT_STRETCH_EXPANDED;
} }
if (aStretch == mozilla::FontStretch::ExtraExpanded()) { if (aStretch == mozilla::FontStretch::EXTRA_EXPANDED) {
return DWRITE_FONT_STRETCH_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_ULTRA_EXPANDED;
} }
return DWRITE_FONT_STRETCH_UNDEFINED; return DWRITE_FONT_STRETCH_UNDEFINED;
@@ -71,25 +72,25 @@ static inline mozilla::FontStretch FontStretchFromDWriteStretch(
DWRITE_FONT_STRETCH aStretch) { DWRITE_FONT_STRETCH aStretch) {
switch (aStretch) { switch (aStretch) {
case DWRITE_FONT_STRETCH_ULTRA_CONDENSED: case DWRITE_FONT_STRETCH_ULTRA_CONDENSED:
return mozilla::FontStretch::UltraCondensed(); return mozilla::FontStretch::ULTRA_CONDENSED;
case DWRITE_FONT_STRETCH_EXTRA_CONDENSED: case DWRITE_FONT_STRETCH_EXTRA_CONDENSED:
return mozilla::FontStretch::ExtraCondensed(); return mozilla::FontStretch::EXTRA_CONDENSED;
case DWRITE_FONT_STRETCH_CONDENSED: case DWRITE_FONT_STRETCH_CONDENSED:
return mozilla::FontStretch::Condensed(); return mozilla::FontStretch::CONDENSED;
case DWRITE_FONT_STRETCH_SEMI_CONDENSED: case DWRITE_FONT_STRETCH_SEMI_CONDENSED:
return mozilla::FontStretch::SemiCondensed(); return mozilla::FontStretch::SEMI_CONDENSED;
case DWRITE_FONT_STRETCH_NORMAL: case DWRITE_FONT_STRETCH_NORMAL:
return mozilla::FontStretch::Normal(); return mozilla::FontStretch::NORMAL;
case DWRITE_FONT_STRETCH_SEMI_EXPANDED: case DWRITE_FONT_STRETCH_SEMI_EXPANDED:
return mozilla::FontStretch::SemiExpanded(); return mozilla::FontStretch::SEMI_EXPANDED;
case DWRITE_FONT_STRETCH_EXPANDED: case DWRITE_FONT_STRETCH_EXPANDED:
return mozilla::FontStretch::Expanded(); return mozilla::FontStretch::EXPANDED;
case DWRITE_FONT_STRETCH_EXTRA_EXPANDED: case DWRITE_FONT_STRETCH_EXTRA_EXPANDED:
return mozilla::FontStretch::ExtraExpanded(); return mozilla::FontStretch::EXTRA_EXPANDED;
case DWRITE_FONT_STRETCH_ULTRA_EXPANDED: case DWRITE_FONT_STRETCH_ULTRA_EXPANDED:
return mozilla::FontStretch::UltraExpanded(); return mozilla::FontStretch::ULTRA_EXPANDED;
default: default:
return mozilla::FontStretch::Normal(); return mozilla::FontStretch::NORMAL;
} }
} }

View File

@@ -1284,7 +1284,7 @@ void gfxDWriteFontList::GetFacesInitDataForFamily(
aFamily->Key().AsString(SharedFontList()).EqualsLiteral("meiryo")) { aFamily->Key().AsString(SharedFontList()).EqualsLiteral("meiryo")) {
continue; continue;
} }
WeightRange weight(FontWeight(dwFont->GetWeight())); WeightRange weight(FontWeight::FromInt(dwFont->GetWeight()));
StretchRange stretch(FontStretchFromDWriteStretch(dwFont->GetStretch())); StretchRange stretch(FontStretchFromDWriteStretch(dwFont->GetStretch()));
// Try to read PSName as a unique face identifier; if this fails we'll get // 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 // it directly from the 'name' table, and if that also fails we consider
@@ -1324,9 +1324,9 @@ void gfxDWriteFontList::GetFacesInitDataForFamily(
continue; continue;
} }
SlantStyleRange slant( SlantStyleRange slant(
dwstyle == DWRITE_FONT_STYLE_NORMAL ? FontSlantStyle::Normal() dwstyle == DWRITE_FONT_STYLE_NORMAL ? FontSlantStyle::NORMAL
: dwstyle == DWRITE_FONT_STYLE_ITALIC ? FontSlantStyle::Italic() : dwstyle == DWRITE_FONT_STYLE_ITALIC ? FontSlantStyle::ITALIC
: FontSlantStyle::Oblique()); : FontSlantStyle::OBLIQUE);
aFaces.AppendElement(fontlist::Face::InitData{ aFaces.AppendElement(fontlist::Face::InitData{
name, uint16_t(i), false, weight, stretch, slant, charmap}); name, uint16_t(i), false, weight, stretch, slant, charmap});
} }

View File

@@ -116,10 +116,10 @@ class gfxDWriteFontEntry final : public gfxFontEntry {
mHasVariationsInitialized(false) { mHasVariationsInitialized(false) {
DWRITE_FONT_STYLE dwriteStyle = aFont->GetStyle(); DWRITE_FONT_STYLE dwriteStyle = aFont->GetStyle();
FontSlantStyle style = (dwriteStyle == DWRITE_FONT_STYLE_ITALIC FontSlantStyle style = (dwriteStyle == DWRITE_FONT_STYLE_ITALIC
? FontSlantStyle::Italic() ? FontSlantStyle::ITALIC
: (dwriteStyle == DWRITE_FONT_STYLE_OBLIQUE : (dwriteStyle == DWRITE_FONT_STYLE_OBLIQUE
? FontSlantStyle::Oblique() ? FontSlantStyle::OBLIQUE
: FontSlantStyle::Normal())); : FontSlantStyle::NORMAL));
mStyleRange = SlantStyleRange(style); mStyleRange = SlantStyleRange(style);
mStretchRange = mStretchRange =
@@ -127,7 +127,7 @@ class gfxDWriteFontEntry final : public gfxFontEntry {
int weight = NS_ROUNDUP(aFont->GetWeight() - 50, 100); int weight = NS_ROUNDUP(aFont->GetWeight() - 50, 100);
weight = mozilla::Clamp(weight, 100, 900); weight = mozilla::Clamp(weight, 100, 900);
mWeightRange = WeightRange(FontWeight(weight)); mWeightRange = WeightRange(FontWeight::FromInt(weight));
mIsCJK = UNINITIALIZED_VALUE; mIsCJK = UNINITIALIZED_VALUE;
} }

View File

@@ -289,7 +289,7 @@ gfxFont* gfxDWriteFont::CopyWithAntialiasOption(
bool gfxDWriteFont::GetFakeMetricsForArialBlack( bool gfxDWriteFont::GetFakeMetricsForArialBlack(
DWRITE_FONT_METRICS* aFontMetrics) { DWRITE_FONT_METRICS* aFontMetrics) {
gfxFontStyle style(mStyle); gfxFontStyle style(mStyle);
style.weight = FontWeight(700); style.weight = FontWeight::FromInt(700);
gfxFontEntry* fe = gfxPlatformFontList::PlatformFontList()->FindFontForFamily( gfxFontEntry* fe = gfxPlatformFontList::PlatformFontList()->FindFontForFamily(
nullptr, "Arial"_ns, &style); nullptr, "Arial"_ns, &style);
@@ -306,8 +306,8 @@ bool gfxDWriteFont::GetFakeMetricsForArialBlack(
void gfxDWriteFont::ComputeMetrics(AntialiasOption anAAOption) { void gfxDWriteFont::ComputeMetrics(AntialiasOption anAAOption) {
DWRITE_FONT_METRICS fontMetrics; DWRITE_FONT_METRICS fontMetrics;
if (!(mFontEntry->Weight().Min() == FontWeight(900) && if (!(mFontEntry->Weight().Min() == FontWeight::FromInt(900) &&
mFontEntry->Weight().Max() == FontWeight(900) && mFontEntry->Weight().Max() == FontWeight::FromInt(900) &&
!mFontEntry->IsUserFont() && !mFontEntry->IsUserFont() &&
mFontEntry->Name().EqualsLiteral("Arial Black") && mFontEntry->Name().EqualsLiteral("Arial Black") &&
GetFakeMetricsForArialBlack(&fontMetrics))) { GetFakeMetricsForArialBlack(&fontMetrics))) {

View File

@@ -5,7 +5,6 @@
#include "mozilla/ArrayUtils.h" #include "mozilla/ArrayUtils.h"
#include "mozilla/Base64.h" #include "mozilla/Base64.h"
#include "mozilla/FontPropertyTypes.h"
#include "mozilla/MemoryReporting.h" #include "mozilla/MemoryReporting.h"
#include "mozilla/dom/ContentChild.h" #include "mozilla/dom/ContentChild.h"
@@ -304,9 +303,9 @@ static void SetPropertiesFromFace(gfxFontEntry* aFontEntry,
hb_blob_destroy(blob); hb_blob_destroy(blob);
aFontEntry->mStyleRange = SlantStyleRange( aFontEntry->mStyleRange = SlantStyleRange(
(style & 2) ? FontSlantStyle::Italic() : FontSlantStyle::Normal()); (style & 2) ? FontSlantStyle::ITALIC : FontSlantStyle::NORMAL);
aFontEntry->mWeightRange = WeightRange(FontWeight(int(os2weight))); aFontEntry->mWeightRange = WeightRange(FontWeight::FromInt(int(os2weight)));
aFontEntry->mStretchRange = StretchRange(FontStretch(stretch)); aFontEntry->mStretchRange = StretchRange(FontStretch::FromFloat(stretch));
// For variable fonts, update the style/weight/stretch attributes if the // For variable fonts, update the style/weight/stretch attributes if the
// corresponding variation axes are present. // corresponding variation axes are present.
@@ -331,9 +330,9 @@ FT2FontEntry* FT2FontEntry::CreateFontEntry(const nsACString& aName,
} else { } else {
// If nullptr is passed for aFace, the caller is intending to override // If nullptr is passed for aFace, the caller is intending to override
// these attributes anyway. We just set defaults here to be safe. // these attributes anyway. We just set defaults here to be safe.
fe->mStyleRange = SlantStyleRange(FontSlantStyle::Normal()); fe->mStyleRange = SlantStyleRange(FontSlantStyle::NORMAL);
fe->mWeightRange = WeightRange(FontWeight::Normal()); fe->mWeightRange = WeightRange(FontWeight::NORMAL);
fe->mStretchRange = StretchRange(FontStretch::Normal()); fe->mStretchRange = StretchRange(FontStretch::NORMAL);
} }
return fe; return fe;
@@ -996,36 +995,31 @@ bool gfxFT2FontList::AppendFacesFromCachedFaceList(CollectFunc aCollectFace,
if (!nextField(start, end)) { if (!nextField(start, end)) {
break; break;
} }
nsAutoCString minStyle(start, end - start);
nsAutoCString maxStyle(minStyle); auto readIntPair = [&](int32_t& aStart, int32_t& aEnd) {
int32_t colon = minStyle.FindChar(FontNameCache::kRangeSep); char* limit = nullptr;
if (colon > 0) { aStart = strtol(start, &limit, 10);
maxStyle.Assign(minStyle.BeginReading() + colon + 1); if (*limit == FontNameCache::kRangeSep && limit + 1 < end) {
minStyle.Truncate(colon); aEnd = strtof(limit + 1, nullptr);
} }
};
int32_t minStyle, maxStyle;
readIntPair(minStyle, maxStyle);
if (!nextField(start, end)) { if (!nextField(start, end)) {
break; break;
} }
char* limit;
float minWeight = strtof(start, &limit); int32_t minWeight, maxWeight;
float maxWeight; readIntPair(minWeight, maxWeight);
if (*limit == FontNameCache::kRangeSep && limit + 1 < end) {
maxWeight = strtof(limit + 1, nullptr);
} else {
maxWeight = minWeight;
}
if (!nextField(start, end)) { if (!nextField(start, end)) {
break; break;
} }
float minStretch = strtof(start, &limit);
float maxStretch; int32_t minStretch, maxStretch;
if (*limit == FontNameCache::kRangeSep && limit + 1 < end) { readIntPair(minStretch, maxStretch);
maxStretch = strtof(limit + 1, nullptr);
} else {
maxStretch = minStretch;
}
if (!nextField(start, end)) { if (!nextField(start, end)) {
break; break;
@@ -1042,15 +1036,17 @@ bool gfxFT2FontList::AppendFacesFromCachedFaceList(CollectFunc aCollectFace,
} }
FontVisibility visibility = FontVisibility(strtoul(start, nullptr, 10)); FontVisibility visibility = FontVisibility(strtoul(start, nullptr, 10));
FontListEntry fle( FontListEntry fle(familyName, faceName, aFileName,
familyName, faceName, aFileName, WeightRange(FontWeight::FromRaw(minWeight),
WeightRange(FontWeight(minWeight), FontWeight(maxWeight)).AsScalar(), FontWeight::FromRaw(maxWeight))
StretchRange(FontStretch(minStretch), FontStretch(maxStretch)) .AsScalar(),
.AsScalar(), StretchRange(FontStretch::FromRaw(minStretch),
SlantStyleRange(FontSlantStyle::FromString(minStyle.get()), FontStretch::FromRaw(maxStretch))
FontSlantStyle::FromString(maxStyle.get())) .AsScalar(),
.AsScalar(), SlantStyleRange(FontSlantStyle::FromRaw(minStyle),
index, visibility); FontSlantStyle::FromRaw(maxStyle))
.AsScalar(),
index, visibility);
aCollectFace(fle, psname, fullname, aStdFile); aCollectFace(fle, psname, fullname, aStdFile);
count++; count++;
@@ -1072,19 +1068,17 @@ void FT2FontEntry::AppendToFaceList(nsCString& aFaceList,
aFaceList.Append(FontNameCache::kFieldSep); aFaceList.Append(FontNameCache::kFieldSep);
aFaceList.AppendInt(mFTFontIndex); aFaceList.AppendInt(mFTFontIndex);
aFaceList.Append(FontNameCache::kFieldSep); aFaceList.Append(FontNameCache::kFieldSep);
// Note that ToString() appends to the destination string without aFaceList.AppendInt(SlantStyle().Min().Raw());
// replacing existing contents (see FontPropertyTypes.h)
SlantStyle().Min().ToString(aFaceList);
aFaceList.Append(FontNameCache::kRangeSep); aFaceList.Append(FontNameCache::kRangeSep);
SlantStyle().Max().ToString(aFaceList); aFaceList.AppendInt(SlantStyle().Max().Raw());
aFaceList.Append(FontNameCache::kFieldSep); aFaceList.Append(FontNameCache::kFieldSep);
aFaceList.AppendFloat(Weight().Min().ToFloat()); aFaceList.AppendInt(Weight().Min().Raw());
aFaceList.Append(FontNameCache::kRangeSep); aFaceList.Append(FontNameCache::kRangeSep);
aFaceList.AppendFloat(Weight().Max().ToFloat()); aFaceList.AppendInt(Weight().Max().Raw());
aFaceList.Append(FontNameCache::kFieldSep); aFaceList.Append(FontNameCache::kFieldSep);
aFaceList.AppendFloat(Stretch().Min().Percentage()); aFaceList.AppendInt(Stretch().Min().Raw());
aFaceList.Append(FontNameCache::kRangeSep); aFaceList.Append(FontNameCache::kRangeSep);
aFaceList.AppendFloat(Stretch().Max().Percentage()); aFaceList.AppendInt(Stretch().Max().Raw());
aFaceList.Append(FontNameCache::kFieldSep); aFaceList.Append(FontNameCache::kFieldSep);
aFaceList.Append(aPSName); aFaceList.Append(aPSName);
aFaceList.Append(FontNameCache::kFieldSep); aFaceList.Append(FontNameCache::kFieldSep);

View File

@@ -145,65 +145,65 @@ static void GetFaceNames(FcPattern* aFont, const nsACString& aFamilyName,
static FontWeight MapFcWeight(int aFcWeight) { static FontWeight MapFcWeight(int aFcWeight) {
if (aFcWeight <= (FC_WEIGHT_THIN + FC_WEIGHT_EXTRALIGHT) / 2) { 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) { 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) { 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) { if (aFcWeight <= (FC_WEIGHT_REGULAR + FC_WEIGHT_MEDIUM) / 2) {
// This includes FC_WEIGHT_BOOK // This includes FC_WEIGHT_BOOK
return FontWeight(400); return FontWeight::FromInt(400);
} }
if (aFcWeight <= (FC_WEIGHT_MEDIUM + FC_WEIGHT_DEMIBOLD) / 2) { 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) { 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) { 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) { if (aFcWeight <= (FC_WEIGHT_EXTRABOLD + FC_WEIGHT_BLACK) / 2) {
return FontWeight(800); return FontWeight::FromInt(800);
} }
if (aFcWeight <= FC_WEIGHT_BLACK) { if (aFcWeight <= FC_WEIGHT_BLACK) {
return FontWeight(900); return FontWeight::FromInt(900);
} }
// including FC_WEIGHT_EXTRABLACK // including FC_WEIGHT_EXTRABLACK
return FontWeight(901); return FontWeight::FromInt(901);
} }
// TODO(emilio, jfkthame): I think this can now be more fine-grained. // TODO(emilio, jfkthame): I think this can now be more fine-grained.
static FontStretch MapFcWidth(int aFcWidth) { static FontStretch MapFcWidth(int aFcWidth) {
if (aFcWidth <= (FC_WIDTH_ULTRACONDENSED + FC_WIDTH_EXTRACONDENSED) / 2) { 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) { 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) { if (aFcWidth <= (FC_WIDTH_CONDENSED + FC_WIDTH_SEMICONDENSED) / 2) {
return FontStretch::Condensed(); return FontStretch::CONDENSED;
} }
if (aFcWidth <= (FC_WIDTH_SEMICONDENSED + FC_WIDTH_NORMAL) / 2) { 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) { if (aFcWidth <= (FC_WIDTH_NORMAL + FC_WIDTH_SEMIEXPANDED) / 2) {
return FontStretch::Normal(); return FontStretch::NORMAL;
} }
if (aFcWidth <= (FC_WIDTH_SEMIEXPANDED + FC_WIDTH_EXPANDED) / 2) { 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) { if (aFcWidth <= (FC_WIDTH_EXPANDED + FC_WIDTH_EXTRAEXPANDED) / 2) {
return FontStretch::Expanded(); return FontStretch::EXPANDED;
} }
if (aFcWidth <= (FC_WIDTH_EXTRAEXPANDED + FC_WIDTH_ULTRAEXPANDED) / 2) { 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, static void GetFontProperties(FcPattern* aFontPattern, WeightRange* aWeight,
@@ -231,9 +231,9 @@ static void GetFontProperties(FcPattern* aFontPattern, WeightRange* aWeight,
slant = FC_SLANT_ROMAN; slant = FC_SLANT_ROMAN;
} }
if (slant == FC_SLANT_OBLIQUE) { if (slant == FC_SLANT_OBLIQUE) {
*aSlantStyle = SlantStyleRange(FontSlantStyle::Oblique()); *aSlantStyle = SlantStyleRange(FontSlantStyle::OBLIQUE);
} else if (slant > 0) { } else if (slant > 0) {
*aSlantStyle = SlantStyleRange(FontSlantStyle::Italic()); *aSlantStyle = SlantStyleRange(FontSlantStyle::ITALIC);
} }
if (aSize) { if (aSize) {
@@ -888,7 +888,7 @@ gfxFont* gfxFontconfigFontEntry::CreateFontInstance(
} }
// will synthetic oblique be applied using a transform? // will synthetic oblique be applied using a transform?
if (IsUpright() && aFontStyle->style != FontSlantStyle::Normal() && if (IsUpright() && !aFontStyle->style.IsNormal() &&
aFontStyle->allowSyntheticStyle) { aFontStyle->allowSyntheticStyle) {
// disable embedded bitmaps (mimics behavior in 90-synthetic.conf) // disable embedded bitmaps (mimics behavior in 90-synthetic.conf)
FcPatternDel(renderPattern, FC_EMBEDDED_BITMAP); FcPatternDel(renderPattern, FC_EMBEDDED_BITMAP);
@@ -1752,9 +1752,9 @@ void gfxFcPlatformFontList::InitSharedFontListForPlatform() {
} }
} }
WeightRange weight(FontWeight::Normal()); WeightRange weight(FontWeight::NORMAL);
StretchRange stretch(FontStretch::Normal()); StretchRange stretch(FontStretch::NORMAL);
SlantStyleRange style(FontSlantStyle::Normal()); SlantStyleRange style(FontSlantStyle::NORMAL);
uint16_t size; uint16_t size;
GetFontProperties(aPattern, &weight, &stretch, &style, &size); GetFontProperties(aPattern, &weight, &stretch, &style, &size);

View File

@@ -811,7 +811,7 @@ void gfxShapedText::AdjustAdvancesForSyntheticBold(float aSynBoldOffset,
float gfxFont::AngleForSyntheticOblique() const { float gfxFont::AngleForSyntheticOblique() const {
// If the style doesn't call for italic/oblique, or if the face already // If the style doesn't call for italic/oblique, or if the face already
// provides it, no synthetic style should be added. // provides it, no synthetic style should be added.
if (mStyle.style == FontSlantStyle::Normal() || !mStyle.allowSyntheticStyle || if (mStyle.style == FontSlantStyle::NORMAL || !mStyle.allowSyntheticStyle ||
!mFontEntry->IsUpright()) { !mFontEntry->IsUpright()) {
return 0.0f; return 0.0f;
} }
@@ -819,7 +819,9 @@ float gfxFont::AngleForSyntheticOblique() const {
// If style calls for italic, and face doesn't support it, use default // If style calls for italic, and face doesn't support it, use default
// oblique angle as a simulation. // oblique angle as a simulation.
if (mStyle.style.IsItalic()) { 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 // Default or custom oblique angle
@@ -830,12 +832,12 @@ float gfxFont::SkewForSyntheticOblique() const {
// Precomputed value of tan(kDefaultAngle), the default italic/oblique slant; // Precomputed value of tan(kDefaultAngle), the default italic/oblique slant;
// avoids calling tan() at runtime except for custom oblique values. // avoids calling tan() at runtime except for custom oblique values.
static const float kTanDefaultAngle = static const float kTanDefaultAngle =
tan(FontSlantStyle::kDefaultAngle * (M_PI / 180.0)); tan(FontSlantStyle::DEFAULT_OBLIQUE_DEGREES * (M_PI / 180.0));
float angle = AngleForSyntheticOblique(); float angle = AngleForSyntheticOblique();
if (angle == 0.0f) { if (angle == 0.0f) {
return 0.0f; return 0.0f;
} else if (angle == FontSlantStyle::kDefaultAngle) { } else if (angle == FontSlantStyle::DEFAULT_OBLIQUE_DEGREES) {
return kTanDefaultAngle; return kTanDefaultAngle;
} else { } else {
return tan(angle * (M_PI / 180.0)); return tan(angle * (M_PI / 180.0));
@@ -4159,9 +4161,9 @@ gfxFontStyle::gfxFontStyle()
baselineOffset(0.0f), baselineOffset(0.0f),
languageOverride(NO_FONT_LANGUAGE_OVERRIDE), languageOverride(NO_FONT_LANGUAGE_OVERRIDE),
fontSmoothingBackgroundColor(NS_RGBA(0, 0, 0, 0)), fontSmoothingBackgroundColor(NS_RGBA(0, 0, 0, 0)),
weight(FontWeight::Normal()), weight(FontWeight::NORMAL),
stretch(FontStretch::Normal()), stretch(FontStretch::NORMAL),
style(FontSlantStyle::Normal()), style(FontSlantStyle::NORMAL),
variantCaps(NS_FONT_VARIANT_CAPS_NORMAL), variantCaps(NS_FONT_VARIANT_CAPS_NORMAL),
variantSubSuper(NS_FONT_VARIANT_POSITION_NORMAL), variantSubSuper(NS_FONT_VARIANT_POSITION_NORMAL),
sizeAdjustBasis(uint8_t(FontSizeAdjust::Tag::None)), sizeAdjustBasis(uint8_t(FontSizeAdjust::Tag::None)),
@@ -4226,11 +4228,11 @@ gfxFontStyle::gfxFontStyle(FontSlantStyle aStyle, FontWeight aWeight,
MOZ_ASSERT(FontSizeAdjust::Tag(sizeAdjustBasis) == aSizeAdjust.tag, MOZ_ASSERT(FontSizeAdjust::Tag(sizeAdjustBasis) == aSizeAdjust.tag,
"gfxFontStyle.sizeAdjustBasis too small?"); "gfxFontStyle.sizeAdjustBasis too small?");
if (weight > FontWeight(1000)) { if (weight > FontWeight::FromInt(1000)) {
weight = FontWeight(1000); weight = FontWeight::FromInt(1000);
} }
if (weight < FontWeight(1)) { if (weight < FontWeight::FromInt(1)) {
weight = FontWeight(1); weight = FontWeight::FromInt(1);
} }
if (size >= FONT_MAX_SIZE) { if (size >= FONT_MAX_SIZE) {
@@ -4249,9 +4251,8 @@ PLDHashNumber gfxFontStyle::Hash() const {
: mozilla::HashBytes(variationSettings.Elements(), : mozilla::HashBytes(variationSettings.Elements(),
variationSettings.Length() * variationSettings.Length() *
sizeof(gfxFontVariation)); sizeof(gfxFontVariation));
return mozilla::AddToHash(hash, systemFont, style.ForHash(), return mozilla::AddToHash(hash, systemFont, style.Raw(), stretch.Raw(),
stretch.ForHash(), weight.ForHash(), size, weight.Raw(), size, int32_t(sizeAdjust * 1000.0f));
int32_t(sizeAdjust * 1000.0f));
} }
void gfxFontStyle::AdjustForSubSuperscript(int32_t aAppUnitsPerDevPixel) { void gfxFontStyle::AdjustForSubSuperscript(int32_t aAppUnitsPerDevPixel) {

View File

@@ -53,7 +53,6 @@
using namespace mozilla; using namespace mozilla;
using namespace mozilla::gfx; using namespace mozilla::gfx;
using namespace mozilla::unicode; using namespace mozilla::unicode;
using mozilla::services::GetObserverService;
void gfxCharacterMap::NotifyReleased() { void gfxCharacterMap::NotifyReleased() {
if (mShared) { if (mShared) {
@@ -1230,12 +1229,13 @@ void gfxFontEntry::SetupVariationRanges() {
// If axis.mMaxValue is less than the default weight we already // If axis.mMaxValue is less than the default weight we already
// set up, assume the axis has a non-standard range (like Skia) // set up, assume the axis has a non-standard range (like Skia)
// and don't try to map it. // and don't try to map it.
Weight().Min() <= FontWeight(axis.mMaxValue)) { Weight().Min() <= FontWeight::FromFloat(axis.mMaxValue)) {
if (FontWeight(axis.mDefaultValue) != Weight().Min()) { if (FontWeight::FromFloat(axis.mDefaultValue) != Weight().Min()) {
mStandardFace = false; mStandardFace = false;
} }
mWeightRange = WeightRange(FontWeight(std::max(1.0f, axis.mMinValue)), mWeightRange =
FontWeight(axis.mMaxValue)); WeightRange(FontWeight::FromFloat(std::max(1.0f, axis.mMinValue)),
FontWeight::FromFloat(axis.mMaxValue));
} else { } else {
mRangeFlags |= RangeFlags::eNonCSSWeight; mRangeFlags |= RangeFlags::eNonCSSWeight;
} }
@@ -1243,12 +1243,12 @@ void gfxFontEntry::SetupVariationRanges() {
case HB_TAG('w', 'd', 't', 'h'): case HB_TAG('w', 'd', 't', 'h'):
if (axis.mMinValue >= 0.0f && axis.mMaxValue <= 1000.0f && if (axis.mMinValue >= 0.0f && axis.mMaxValue <= 1000.0f &&
Stretch().Min() <= FontStretch(axis.mMaxValue)) { Stretch().Min() <= FontStretch::FromFloat(axis.mMaxValue)) {
if (FontStretch(axis.mDefaultValue) != Stretch().Min()) { if (FontStretch::FromFloat(axis.mDefaultValue) != Stretch().Min()) {
mStandardFace = false; mStandardFace = false;
} }
mStretchRange = StretchRange(FontStretch(axis.mMinValue), mStretchRange = StretchRange(FontStretch::FromFloat(axis.mMinValue),
FontStretch(axis.mMaxValue)); FontStretch::FromFloat(axis.mMaxValue));
} else { } else {
mRangeFlags |= RangeFlags::eNonCSSStretch; mRangeFlags |= RangeFlags::eNonCSSStretch;
} }
@@ -1256,7 +1256,7 @@ void gfxFontEntry::SetupVariationRanges() {
case HB_TAG('s', 'l', 'n', 't'): case HB_TAG('s', 'l', 'n', 't'):
if (axis.mMinValue >= -90.0f && axis.mMaxValue <= 90.0f) { if (axis.mMinValue >= -90.0f && axis.mMaxValue <= 90.0f) {
if (FontSlantStyle::Oblique(axis.mDefaultValue) != if (FontSlantStyle::FromFloat(axis.mDefaultValue) !=
SlantStyle().Min()) { SlantStyle().Min()) {
mStandardFace = false; mStandardFace = false;
} }
@@ -1264,8 +1264,8 @@ void gfxFontEntry::SetupVariationRanges() {
// have to flip signs and swap min/max when setting up the CSS // have to flip signs and swap min/max when setting up the CSS
// font-style range here. // font-style range here.
mStyleRange = mStyleRange =
SlantStyleRange(FontSlantStyle::Oblique(-axis.mMaxValue), SlantStyleRange(FontSlantStyle::FromFloat(-axis.mMaxValue),
FontSlantStyle::Oblique(-axis.mMinValue)); FontSlantStyle::FromFloat(-axis.mMinValue));
} }
break; break;
@@ -1274,8 +1274,8 @@ void gfxFontEntry::SetupVariationRanges() {
if (axis.mDefaultValue != 0.0f) { if (axis.mDefaultValue != 0.0f) {
mStandardFace = false; mStandardFace = false;
} }
mStyleRange = SlantStyleRange(FontSlantStyle::Normal(), mStyleRange =
FontSlantStyle::Italic()); SlantStyleRange(FontSlantStyle::NORMAL, FontSlantStyle::ITALIC);
} }
break; break;
@@ -1358,8 +1358,8 @@ void gfxFontEntry::GetVariationsForStyle(nsTArray<gfxFontVariation>& aResult,
if (!(mRangeFlags & RangeFlags::eNonCSSStretch)) { if (!(mRangeFlags & RangeFlags::eNonCSSStretch)) {
float stretch = (IsUserFont() && (mRangeFlags & RangeFlags::eAutoStretch)) float stretch = (IsUserFont() && (mRangeFlags & RangeFlags::eAutoStretch))
? aStyle.stretch.Percentage() ? aStyle.stretch.ToFloat()
: Stretch().Clamp(aStyle.stretch).Percentage(); : Stretch().Clamp(aStyle.stretch).ToFloat();
aResult.AppendElement( aResult.AppendElement(
gfxFontVariation{HB_TAG('w', 'd', 't', 'h'), stretch}); gfxFontVariation{HB_TAG('w', 'd', 't', 'h'), stretch});
} }
@@ -1373,12 +1373,13 @@ void gfxFontEntry::GetVariationsForStyle(nsTArray<gfxFontVariation>& aResult,
// requested style. // requested style.
float angle = aStyle.style.IsNormal() ? 0.0f float angle = aStyle.style.IsNormal() ? 0.0f
: aStyle.style.IsItalic() : aStyle.style.IsItalic()
? FontSlantStyle::Oblique().ObliqueAngle() ? FontSlantStyle::DEFAULT_OBLIQUE_DEGREES
: aStyle.style.ObliqueAngle(); : aStyle.style.ObliqueAngle();
// Clamp to the available range, unless the face is a user font // Clamp to the available range, unless the face is a user font
// with no explicit descriptor. // with no explicit descriptor.
if (!(IsUserFont() && (mRangeFlags & RangeFlags::eAutoSlantStyle))) { 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 // OpenType and CSS measure angles in opposite directions, so we have to
// invert the sign of the CSS oblique value when setting OpenType 'slnt'. // invert the sign of the CSS oblique value when setting OpenType 'slnt'.
@@ -1626,7 +1627,7 @@ void gfxFontFamily::FindAllFontsForStyle(
// calculate which one we want. // calculate which one we want.
// Note that we cannot simply return it as not all 4 faces are necessarily // Note that we cannot simply return it as not all 4 faces are necessarily
// present. // present.
bool wantBold = aFontStyle.weight >= FontWeight(600); bool wantBold = aFontStyle.weight >= FontWeight::FromInt(600);
bool wantItalic = !aFontStyle.style.IsNormal(); bool wantItalic = !aFontStyle.style.IsNormal();
uint8_t faceIndex = uint8_t faceIndex =
(wantItalic ? kItalicMask : 0) | (wantBold ? kBoldMask : 0); (wantItalic ? kItalicMask : 0) | (wantBold ? kBoldMask : 0);

View File

@@ -193,10 +193,10 @@ class gfxFontEntry {
// If this is false, we might want to fall back to a different face and // If this is false, we might want to fall back to a different face and
// possibly apply synthetic styling. // possibly apply synthetic styling.
bool IsNormalStyle() const { bool IsNormalStyle() const {
return IsUpright() && Weight().Min() <= FontWeight::Normal() && return IsUpright() && Weight().Min() <= FontWeight::NORMAL &&
Weight().Max() >= FontWeight::Normal() && Weight().Max() >= FontWeight::NORMAL &&
Stretch().Min() <= FontStretch::Normal() && Stretch().Min() <= FontStretch::NORMAL &&
Stretch().Max() >= FontStretch::Normal(); Stretch().Max() >= FontStretch::NORMAL;
} }
// whether a feature is supported by the font (limited to a small set // 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; uint32_t mLanguageOverride = NO_FONT_LANGUAGE_OVERRIDE;
WeightRange mWeightRange = WeightRange(FontWeight(500)); WeightRange mWeightRange = WeightRange(FontWeight::FromInt(500));
StretchRange mStretchRange = StretchRange(FontStretch::Normal()); StretchRange mStretchRange = StretchRange(FontStretch::NORMAL);
SlantStyleRange mStyleRange = SlantStyleRange(FontSlantStyle::Normal()); SlantStyleRange mStyleRange = SlantStyleRange(FontSlantStyle::NORMAL);
// Font metrics overrides (as multiples of used font size); negative values // Font metrics overrides (as multiples of used font size); negative values
// indicate no override to be applied. // indicate no override to be applied.

View File

@@ -15,7 +15,7 @@
#include "mozilla/Attributes.h" #include "mozilla/Attributes.h"
#include "mozilla/Casting.h" #include "mozilla/Casting.h"
#include "mozilla/EndianUtils.h" #include "mozilla/EndianUtils.h"
#include "mozilla/FontPropertyTypes.h" #include "mozilla/ServoStyleConstsInlines.h"
#include "mozilla/MemoryReporting.h" #include "mozilla/MemoryReporting.h"
#include "mozilla/UniquePtr.h" #include "mozilla/UniquePtr.h"
#include "nsStringFwd.h" #include "nsStringFwd.h"
@@ -1251,8 +1251,7 @@ static inline double StyleDistance(const mozilla::SlantStyleRange& aRange,
return kReverse; return kReverse;
} }
const double kDefaultAngle = const double kDefaultAngle = mozilla::FontSlantStyle::OBLIQUE.ObliqueAngle();
mozilla::FontSlantStyle::Oblique().ObliqueAngle();
if (aTargetStyle.IsItalic()) { if (aTargetStyle.IsItalic()) {
if (minStyle.IsOblique()) { 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 aTargetStretch is >100, we prefer larger values if available;
// if <=100, we prefer smaller values if available. // if <=100, we prefer smaller values if available.
if (aTargetStretch < minStretch) { if (aTargetStretch < minStretch) {
if (aTargetStretch > mozilla::FontStretch::Normal()) { if (aTargetStretch > mozilla::FontStretch::NORMAL) {
return minStretch - aTargetStretch; return minStretch.ToFloat() - aTargetStretch.ToFloat();
} }
return (minStretch - aTargetStretch) + kReverseDistance; return (minStretch.ToFloat() - aTargetStretch.ToFloat()) + kReverseDistance;
} }
if (aTargetStretch > maxStretch) { if (aTargetStretch > maxStretch) {
if (aTargetStretch <= mozilla::FontStretch::Normal()) { if (aTargetStretch <= mozilla::FontStretch::NORMAL) {
return aTargetStretch - maxStretch; return aTargetStretch.ToFloat() - maxStretch.ToFloat();
} }
return (aTargetStretch - maxStretch) + kReverseDistance; return (aTargetStretch.ToFloat() - maxStretch.ToFloat()) + kReverseDistance;
} }
return 0.0; return 0.0;
} }
@@ -1422,35 +1421,36 @@ static inline double WeightDistance(const mozilla::WeightRange& aRange,
return 0.0; return 0.0;
} }
if (aTargetWeight < mozilla::FontWeight(400)) { if (aTargetWeight < mozilla::FontWeight::NORMAL) {
// Requested a lighter-than-400 weight // Requested a lighter-than-400 weight
if (maxWeight < aTargetWeight) { if (maxWeight < aTargetWeight) {
return aTargetWeight - maxWeight; return aTargetWeight.ToFloat() - maxWeight.ToFloat();
} }
// Add reverse-search penalty for bolder faces // 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 // Requested a bolder-than-500 weight
if (minWeight > aTargetWeight) { if (minWeight > aTargetWeight) {
return minWeight - aTargetWeight; return minWeight.ToFloat() - aTargetWeight.ToFloat();
} }
// Add reverse-search penalty for lighter faces // 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 // Special case for requested weight in the [400..500] range
if (minWeight > aTargetWeight) { if (minWeight > aTargetWeight) {
if (minWeight <= mozilla::FontWeight(500)) { if (minWeight <= mozilla::FontWeight::FromInt(500)) {
// Bolder weight up to 500 is first choice // Bolder weight up to 500 is first choice
return minWeight - aTargetWeight; return minWeight.ToFloat() - aTargetWeight.ToFloat();
} }
// Other bolder weights get a reverse-search penalty // 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] // 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 */ #endif /* GFX_FONT_UTILS_H */

View File

@@ -280,7 +280,7 @@ bool GDIFontEntry::TestCharacterMap(uint32_t aCh) {
// previous code was using the group style // previous code was using the group style
gfxFontStyle fakeStyle; gfxFontStyle fakeStyle;
if (!IsUpright()) { if (!IsUpright()) {
fakeStyle.style = FontSlantStyle::Italic(); fakeStyle.style = FontSlantStyle::ITALIC;
} }
fakeStyle.weight = Weight().Min(); fakeStyle.weight = Weight().Min();
@@ -432,7 +432,7 @@ int CALLBACK GDIFontFamily::FamilyAddStylesProc(
for (uint32_t i = 0; i < ff->mAvailableFonts.Length(); ++i) { for (uint32_t i = 0; i < ff->mAvailableFonts.Length(); ++i) {
fe = static_cast<GDIFontEntry*>(ff->mAvailableFonts[i].get()); fe = static_cast<GDIFontEntry*>(ff->mAvailableFonts[i].get());
// check if we already know about this face // 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)) { fe->IsItalic() == (logFont.lfItalic == 0xFF)) {
// update the charset bit here since this could be different // update the charset bit here since this could be different
// XXX Can we still do this now that we store mCharset // 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, // We can't set the hasItalicFace flag correctly here,
// because we might not have seen the family's italic face(s) yet. // 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. // So we'll set that flag for all members after loading all the faces.
auto italicStyle = (logFont.lfItalic == 0xFF ? FontSlantStyle::Italic() auto italicStyle = (logFont.lfItalic == 0xFF ? FontSlantStyle::ITALIC
: FontSlantStyle::Normal()); : FontSlantStyle::NORMAL);
fe = GDIFontEntry::CreateFontEntry( fe = GDIFontEntry::CreateFontEntry(
NS_ConvertUTF16toUTF8(lpelfe->elfFullName), feType, NS_ConvertUTF16toUTF8(lpelfe->elfFullName), feType,
SlantStyleRange(italicStyle), SlantStyleRange(italicStyle),
WeightRange(FontWeight(int32_t(logFont.lfWeight))), WeightRange(FontWeight::FromInt(int32_t(logFont.lfWeight))),
StretchRange(FontStretch::Normal()), nullptr); StretchRange(FontStretch::NORMAL), nullptr);
if (!fe) { if (!fe) {
return 1; return 1;
} }

View File

@@ -865,22 +865,22 @@ void gfxMacFontFamily::FindStyleVariationsLocked(FontInfoData* aFontInfoData) {
// create a font entry // create a font entry
MacOSFontEntry* fontEntry = MacOSFontEntry* fontEntry =
new MacOSFontEntry(NS_ConvertUTF16toUTF8(postscriptFontName), new MacOSFontEntry(NS_ConvertUTF16toUTF8(postscriptFontName),
WeightRange(FontWeight(cssWeight)), isStandardFace, mSizeHint); WeightRange(FontWeight::FromInt(cssWeight)), isStandardFace, mSizeHint);
if (!fontEntry) { if (!fontEntry) {
break; break;
} }
// set additional properties based on the traits reported by Cocoa // set additional properties based on the traits reported by Cocoa
if (macTraits & (NSCondensedFontMask | NSNarrowFontMask | NSCompressedFontMask)) { if (macTraits & (NSCondensedFontMask | NSNarrowFontMask | NSCompressedFontMask)) {
fontEntry->mStretchRange = StretchRange(FontStretch::Condensed()); fontEntry->mStretchRange = StretchRange(FontStretch::CONDENSED);
} else if (macTraits & NSExpandedFontMask) { } else if (macTraits & NSExpandedFontMask) {
fontEntry->mStretchRange = StretchRange(FontStretch::Expanded()); fontEntry->mStretchRange = StretchRange(FontStretch::EXPANDED);
} }
// Cocoa fails to set the Italic traits bit for HelveticaLightItalic, // Cocoa fails to set the Italic traits bit for HelveticaLightItalic,
// at least (see bug 611855), so check for style name endings as well // at least (see bug 611855), so check for style name endings as well
if ((macTraits & NSItalicFontMask) || [facename hasSuffix:@"Italic"] || if ((macTraits & NSItalicFontMask) || [facename hasSuffix:@"Italic"] ||
[facename hasSuffix:@"Oblique"]) { [facename hasSuffix:@"Oblique"]) {
fontEntry->mStyleRange = SlantStyleRange(FontSlantStyle::Italic()); fontEntry->mStyleRange = SlantStyleRange(FontSlantStyle::ITALIC);
} }
if (macTraits & NSFixedPitchFontMask) { if (macTraits & NSFixedPitchFontMask) {
fontEntry->mFixedPitch = true; fontEntry->mFixedPitch = true;
@@ -1419,7 +1419,7 @@ static gfxFontFamily* CreateFamilyForSystemFont(NSFont* aFont, const nsACString&
nsCocoaUtils::GetStringForNSString(psNameNS, nameUTF16); nsCocoaUtils::GetStringForNSString(psNameNS, nameUTF16);
CopyUTF16toUTF8(nameUTF16, psName); 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()); MOZ_ASSERT(gfxPlatform::GetPlatform()->HasVariationFontSupport());
fe->SetupVariationRanges(); fe->SetupVariationRanges();
@@ -1816,12 +1816,11 @@ void gfxMacPlatformFontList::LookupSystemFont(LookAndFeel::FontID aSystemFontID,
} }
NSFontSymbolicTraits traits = [[font fontDescriptor] symbolicTraits]; NSFontSymbolicTraits traits = [[font fontDescriptor] symbolicTraits];
aFontStyle.style = aFontStyle.style = (traits & NSFontItalicTrait) ? FontSlantStyle::ITALIC : FontSlantStyle::NORMAL;
(traits & NSFontItalicTrait) ? FontSlantStyle::Italic() : FontSlantStyle::Normal(); aFontStyle.weight = (traits & NSFontBoldTrait) ? FontWeight::BOLD : FontWeight::NORMAL;
aFontStyle.weight = (traits & NSFontBoldTrait) ? FontWeight::Bold() : FontWeight::Normal(); aFontStyle.stretch = (traits & NSFontExpandedTrait) ? FontStretch::EXPANDED
aFontStyle.stretch = (traits & NSFontExpandedTrait) ? FontStretch::Expanded() : (traits & NSFontCondensedTrait) ? FontStretch::CONDENSED
: (traits & NSFontCondensedTrait) ? FontStretch::Condensed() : FontStretch::NORMAL;
: FontStretch::Normal();
aFontStyle.size = [font pointSize]; aFontStyle.size = [font pointSize];
aFontStyle.systemFont = true; aFontStyle.systemFont = true;
} }
@@ -1998,18 +1997,18 @@ void gfxMacPlatformFontList::GetFacesInitDataForFamily(const fontlist::Family* a
} }
cssWeight *= 100; // scale up to CSS values cssWeight *= 100; // scale up to CSS values
StretchRange stretch(FontStretch::Normal()); StretchRange stretch(FontStretch::NORMAL);
if (macTraits & (NSCondensedFontMask | NSNarrowFontMask | NSCompressedFontMask)) { if (macTraits & (NSCondensedFontMask | NSNarrowFontMask | NSCompressedFontMask)) {
stretch = StretchRange(FontStretch::Condensed()); stretch = StretchRange(FontStretch::CONDENSED);
} else if (macTraits & NSExpandedFontMask) { } else if (macTraits & NSExpandedFontMask) {
stretch = StretchRange(FontStretch::Expanded()); stretch = StretchRange(FontStretch::EXPANDED);
} }
// Cocoa fails to set the Italic traits bit for HelveticaLightItalic, // Cocoa fails to set the Italic traits bit for HelveticaLightItalic,
// at least (see bug 611855), so check for style name endings as well // 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"] || if ((macTraits & NSItalicFontMask) || [facename hasSuffix:@"Italic"] ||
[facename hasSuffix:@"Oblique"]) { [facename hasSuffix:@"Oblique"]) {
slantStyle = SlantStyleRange(FontSlantStyle::Italic()); slantStyle = SlantStyleRange(FontSlantStyle::ITALIC);
} }
bool fixedPitch = (macTraits & NSFixedPitchFontMask) ? true : false; bool fixedPitch = (macTraits & NSFixedPitchFontMask) ? true : false;
@@ -2035,7 +2034,7 @@ void gfxMacPlatformFontList::GetFacesInitDataForFamily(const fontlist::Family* a
NS_ConvertUTF16toUTF8(postscriptFontName), NS_ConvertUTF16toUTF8(postscriptFontName),
0, 0,
fixedPitch, fixedPitch,
WeightRange(FontWeight(cssWeight)), WeightRange(FontWeight::FromInt(cssWeight)),
stretch, stretch,
slantStyle, slantStyle,
charmap, charmap,
@@ -2072,7 +2071,7 @@ void gfxMacPlatformFontList::ReadFaceNamesForFamily(fontlist::Family* aFamily,
// of the macOS UI font; see MacOSFontEntry::GetFontRef(). We pass 16.0 in // 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 // 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. // unlikely to matter for the purpose of just reading family names.
auto fe = MakeUnique<MacOSFontEntry>(name, WeightRange(FontWeight::Normal()), false, 16.0); auto fe = MakeUnique<MacOSFontEntry>(name, WeightRange(FontWeight::NORMAL), false, 16.0);
if (!fe) { if (!fe) {
continue; continue;
} }

View File

@@ -1789,11 +1789,11 @@ void gfxTextRun::Dump(FILE* out) {
for (uint32_t i = 0; i < numGlyphRuns; ++i) { for (uint32_t i = 0; i < numGlyphRuns; ++i) {
gfxFont* font = glyphRuns[i].mFont; gfxFont* font = glyphRuns[i].mFont;
const gfxFontStyle* style = font->GetStyle(); const gfxFontStyle* style = font->GetStyle();
nsAutoString styleString; nsAutoCString styleString;
nsStyleUtil::AppendFontSlantStyle(style->style, styleString); style->style.ToString(styleString);
fprintf(out, " [%d] offset=%d %s %f/%g/%s\n", i, fprintf(out, " [%d] offset=%d %s %f/%g/%s\n", i,
glyphRuns[i].mCharacterOffset, font->GetName().get(), style->size, glyphRuns[i].mCharacterOffset, font->GetName().get(), style->size,
style->weight.ToFloat(), NS_ConvertUTF16toUTF8(styleString).get()); style->weight.ToFloat(), styleString.get());
} }
fprintf(out, " Glyphs:\n"); fprintf(out, " Glyphs:\n");
@@ -2580,8 +2580,8 @@ void gfxFontGroup::InitTextRun(DrawTarget* aDrawTarget, gfxTextRun* aTextRun,
nsAutoCString lang; nsAutoCString lang;
mLanguage->ToUTF8String(lang); mLanguage->ToUTF8String(lang);
nsAutoCString str((const char*)aString, aLength); nsAutoCString str((const char*)aString, aLength);
nsAutoString styleString; nsAutoCString styleString;
nsStyleUtil::AppendFontSlantStyle(mStyle.style, styleString); mStyle.style.ToString(styleString);
auto defaultLanguageGeneric = GetDefaultGeneric(mLanguage); auto defaultLanguageGeneric = GetDefaultGeneric(mLanguage);
MOZ_LOG( MOZ_LOG(
log, LogLevel::Warning, log, LogLevel::Warning,
@@ -2596,9 +2596,8 @@ void gfxFontGroup::InitTextRun(DrawTarget* aDrawTarget, gfxTextRun* aTextRun,
? "sans-serif" ? "sans-serif"
: "none")), : "none")),
lang.get(), static_cast<int>(Script::LATIN), aLength, lang.get(), static_cast<int>(Script::LATIN), aLength,
mStyle.weight.ToFloat(), mStyle.stretch.Percentage(), mStyle.weight.ToFloat(), mStyle.stretch.ToFloat(),
NS_ConvertUTF16toUTF8(styleString).get(), mStyle.size, sizeof(T), styleString.get(), mStyle.size, sizeof(T), str.get()));
str.get()));
} }
// the text is still purely 8-bit; bypass the script-run itemizer // 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))) { if (MOZ_UNLIKELY(MOZ_LOG_TEST(log, LogLevel::Warning))) {
nsAutoCString lang; nsAutoCString lang;
mLanguage->ToUTF8String(lang); mLanguage->ToUTF8String(lang);
nsAutoString styleString; nsAutoCString styleString;
nsStyleUtil::AppendFontSlantStyle(mStyle.style, styleString); mStyle.style.ToString(styleString);
auto defaultLanguageGeneric = GetDefaultGeneric(mLanguage); auto defaultLanguageGeneric = GetDefaultGeneric(mLanguage);
uint32_t runLen = runLimit - runStart; uint32_t runLen = runLimit - runStart;
MOZ_LOG( MOZ_LOG(log, LogLevel::Warning,
log, LogLevel::Warning, ("(%s) fontgroup: [%s] default: %s lang: %s script: %d "
("(%s) fontgroup: [%s] default: %s lang: %s script: %d " "len %d weight: %g stretch: %g%% style: %s size: %6.2f "
"len %d weight: %g stretch: %g%% style: %s size: %6.2f " "%zu-byte TEXTRUN [%s] ENDTEXTRUN\n",
"%zu-byte TEXTRUN [%s] ENDTEXTRUN\n", (mStyle.systemFont ? "textrunui" : "textrun"),
(mStyle.systemFont ? "textrunui" : "textrun"), FamilyListToString(mFamilyList).get(),
FamilyListToString(mFamilyList).get(), (defaultLanguageGeneric == StyleGenericFontFamily::Serif
(defaultLanguageGeneric == StyleGenericFontFamily::Serif ? "serif"
? "serif" : (defaultLanguageGeneric ==
: (defaultLanguageGeneric == StyleGenericFontFamily::SansSerif
StyleGenericFontFamily::SansSerif ? "sans-serif"
? "sans-serif" : "none")),
: "none")), lang.get(), static_cast<int>(runScript), runLen,
lang.get(), static_cast<int>(runScript), runLen, mStyle.weight.ToFloat(), mStyle.stretch.ToFloat(),
mStyle.weight.ToFloat(), mStyle.stretch.Percentage(), styleString.get(), mStyle.size, sizeof(T),
NS_ConvertUTF16toUTF8(styleString).get(), mStyle.size, sizeof(T), NS_ConvertUTF16toUTF8(textPtr + runStart, runLen).get()));
NS_ConvertUTF16toUTF8(textPtr + runStart, runLen).get()));
} }
InitScriptRun(aDrawTarget, aTextRun, textPtr + runStart, runStart, InitScriptRun(aDrawTarget, aTextRun, textPtr + runStart, runStart,

View File

@@ -142,6 +142,7 @@ elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "gtk":
elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "windows": elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "windows":
REQUIRES_UNIFIED_BUILD = True REQUIRES_UNIFIED_BUILD = True
EXPORTS += [ EXPORTS += [
"gfxDWriteCommon.h",
"gfxDWriteFonts.h", "gfxDWriteFonts.h",
"gfxGDIFont.h", "gfxGDIFont.h",
"gfxGDIFontList.h", "gfxGDIFontList.h",

View File

@@ -529,15 +529,15 @@ void MathMLTextRunFactory::RebuildTextRun(
// This overrides the initial values specified in fontStyle, to avoid // This overrides the initial values specified in fontStyle, to avoid
// inconsistencies in which attributes allow CSS changes and which do not. // inconsistencies in which attributes allow CSS changes and which do not.
if (mFlags & MATH_FONT_WEIGHT_BOLD) { if (mFlags & MATH_FONT_WEIGHT_BOLD) {
font.weight = FontWeight::Bold(); font.weight = FontWeight::BOLD;
if (mFlags & MATH_FONT_STYLING_NORMAL) { if (mFlags & MATH_FONT_STYLING_NORMAL) {
font.style = FontSlantStyle::Normal(); font.style = FontSlantStyle::NORMAL;
} else { } else {
font.style = FontSlantStyle::Italic(); font.style = FontSlantStyle::ITALIC;
} }
} else if (mFlags & MATH_FONT_STYLING_NORMAL) { } else if (mFlags & MATH_FONT_STYLING_NORMAL) {
font.style = FontSlantStyle::Normal(); font.style = FontSlantStyle::NORMAL;
font.weight = FontWeight::Normal(); font.weight = FontWeight::NORMAL;
} else { } else {
mathVar = StyleMathVariant::Italic; mathVar = StyleMathVariant::Italic;
} }
@@ -615,20 +615,20 @@ void MathMLTextRunFactory::RebuildTextRun(
gfxTextRun* child; gfxTextRun* child;
if (mathVar == StyleMathVariant::Bold && doMathvariantStyling) { if (mathVar == StyleMathVariant::Bold && doMathvariantStyling) {
font.style = FontSlantStyle::Normal(); font.style = FontSlantStyle::NORMAL;
font.weight = FontWeight::Bold(); font.weight = FontWeight::BOLD;
} else if (mathVar == StyleMathVariant::Italic && doMathvariantStyling) { } else if (mathVar == StyleMathVariant::Italic && doMathvariantStyling) {
font.style = FontSlantStyle::Italic(); font.style = FontSlantStyle::ITALIC;
font.weight = FontWeight::Normal(); font.weight = FontWeight::NORMAL;
} else if (mathVar == StyleMathVariant::BoldItalic && doMathvariantStyling) { } else if (mathVar == StyleMathVariant::BoldItalic && doMathvariantStyling) {
font.style = FontSlantStyle::Italic(); font.style = FontSlantStyle::ITALIC;
font.weight = FontWeight::Bold(); font.weight = FontWeight::BOLD;
} else if (mathVar != StyleMathVariant::None) { } else if (mathVar != StyleMathVariant::None) {
// Mathvariant overrides fontstyle and fontweight // Mathvariant overrides fontstyle and fontweight
// Need to check to see if mathvariant is actually applied as this function // Need to check to see if mathvariant is actually applied as this function
// is used for other purposes. // is used for other purposes.
font.style = FontSlantStyle::Normal(); font.style = FontSlantStyle::NORMAL;
font.weight = FontWeight::Normal(); font.weight = FontWeight::NORMAL;
} }
gfxFontGroup* newFontGroup = nullptr; gfxFontGroup* newFontGroup = nullptr;

View File

@@ -41,7 +41,7 @@ eMathMLFrameType nsMathMLTokenFrame::GetMathMLFrameType() {
StyleMathVariant mathVariant = StyleFont()->mMathVariant; StyleMathVariant mathVariant = StyleFont()->mMathVariant;
if ((mathVariant == StyleMathVariant::None && if ((mathVariant == StyleMathVariant::None &&
(StyleFont()->mFont.style == FontSlantStyle::Italic() || (StyleFont()->mFont.style.IsItalic() ||
HasAnyStateBits(NS_FRAME_IS_IN_SINGLE_CHAR_MI))) || HasAnyStateBits(NS_FRAME_IS_IN_SINGLE_CHAR_MI))) ||
mathVariant == StyleMathVariant::Italic || mathVariant == StyleMathVariant::Italic ||
mathVariant == StyleMathVariant::BoldItalic || mathVariant == StyleMathVariant::BoldItalic ||

View File

@@ -201,34 +201,12 @@ void FontFaceSet::ParseFontShorthandForMatching(
const nsACString& aFont, StyleFontFamilyList& aFamilyList, const nsACString& aFont, StyleFontFamilyList& aFamilyList,
FontWeight& aWeight, FontStretch& aStretch, FontSlantStyle& aStyle, FontWeight& aWeight, FontStretch& aStretch, FontSlantStyle& aStyle,
ErrorResult& aRv) { ErrorResult& aRv) {
auto style = StyleComputedFontStyleDescriptor::Normal();
float stretch;
float weight;
RefPtr<URLExtraData> url = ServoCSSParser::GetURLExtraData(mDocument); RefPtr<URLExtraData> url = ServoCSSParser::GetURLExtraData(mDocument);
if (!ServoCSSParser::ParseFontShorthandForMatching(aFont, url, aFamilyList, if (!ServoCSSParser::ParseFontShorthandForMatching(
style, stretch, weight)) { aFont, url, aFamilyList, aStyle, aStretch, aWeight)) {
aRv.ThrowSyntaxError("Invalid font shorthand"); aRv.ThrowSyntaxError("Invalid font shorthand");
return; 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, static bool HasAnyCharacterInUnicodeRange(gfxUserFontEntry* aEntry,
@@ -937,9 +915,10 @@ static WeightRange GetWeightRangeForDescriptor(
gfxFontEntry::RangeFlags& aRangeFlags) { gfxFontEntry::RangeFlags& aRangeFlags) {
if (!aVal) { if (!aVal) {
aRangeFlags |= gfxFontEntry::RangeFlags::eAutoWeight; 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( static SlantStyleRange GetStyleRangeForDescriptor(
@@ -947,20 +926,20 @@ static SlantStyleRange GetStyleRangeForDescriptor(
gfxFontEntry::RangeFlags& aRangeFlags) { gfxFontEntry::RangeFlags& aRangeFlags) {
if (!aVal) { if (!aVal) {
aRangeFlags |= gfxFontEntry::RangeFlags::eAutoSlantStyle; aRangeFlags |= gfxFontEntry::RangeFlags::eAutoSlantStyle;
return SlantStyleRange(FontSlantStyle::Normal()); return SlantStyleRange(FontSlantStyle::NORMAL);
} }
auto& val = *aVal; auto& val = *aVal;
switch (val.tag) { switch (val.tag) {
case StyleComputedFontStyleDescriptor::Tag::Normal: case StyleComputedFontStyleDescriptor::Tag::Normal:
return SlantStyleRange(FontSlantStyle::Normal()); return SlantStyleRange(FontSlantStyle::NORMAL);
case StyleComputedFontStyleDescriptor::Tag::Italic: case StyleComputedFontStyleDescriptor::Tag::Italic:
return SlantStyleRange(FontSlantStyle::Italic()); return SlantStyleRange(FontSlantStyle::ITALIC);
case StyleComputedFontStyleDescriptor::Tag::Oblique: case StyleComputedFontStyleDescriptor::Tag::Oblique:
return SlantStyleRange(FontSlantStyle::Oblique(val.AsOblique()._0), return SlantStyleRange(FontSlantStyle::FromFloat(val.AsOblique()._0),
FontSlantStyle::Oblique(val.AsOblique()._1)); FontSlantStyle::FromFloat(val.AsOblique()._1));
} }
MOZ_ASSERT_UNREACHABLE("How?"); MOZ_ASSERT_UNREACHABLE("How?");
return SlantStyleRange(FontSlantStyle::Normal()); return SlantStyleRange(FontSlantStyle::NORMAL);
} }
static StretchRange GetStretchRangeForDescriptor( static StretchRange GetStretchRangeForDescriptor(
@@ -968,10 +947,9 @@ static StretchRange GetStretchRangeForDescriptor(
gfxFontEntry::RangeFlags& aRangeFlags) { gfxFontEntry::RangeFlags& aRangeFlags) {
if (!aVal) { if (!aVal) {
aRangeFlags |= gfxFontEntry::RangeFlags::eAutoStretch; aRangeFlags |= gfxFontEntry::RangeFlags::eAutoStretch;
return StretchRange(FontStretch::Normal()); return StretchRange(FontStretch::NORMAL);
} }
return StretchRange(FontStretch::FromStyle(aVal->_0), return StretchRange(aVal->_0, aVal->_1);
FontStretch::FromStyle(aVal->_1));
} }
// TODO(emilio): Should this take an nsAtom* aFamilyName instead? // TODO(emilio): Should this take an nsAtom* aFamilyName instead?

View File

@@ -10,7 +10,6 @@
#include "mozilla/dom/FontFace.h" #include "mozilla/dom/FontFace.h"
#include "mozilla/dom/FontFaceSetBinding.h" #include "mozilla/dom/FontFaceSetBinding.h"
#include "mozilla/DOMEventTargetHelper.h" #include "mozilla/DOMEventTargetHelper.h"
#include "mozilla/FontPropertyTypes.h"
#include "gfxUserFontSet.h" #include "gfxUserFontSet.h"
#include "nsICSSLoaderObserver.h" #include "nsICSSLoaderObserver.h"
#include "nsIDOMEventListener.h" #include "nsIDOMEventListener.h"

View File

@@ -996,47 +996,6 @@ nsTArray<uint32_t>* Gecko_AppendFeatureValueHashEntry(
aName, aAlternate); 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, void Gecko_CounterStyle_ToPtr(const StyleCounterStyle* aStyle,
CounterStylePtr* aPtr) { CounterStylePtr* aPtr) {
*aPtr = CounterStylePtr::FromStyle(*aStyle); *aPtr = CounterStylePtr::FromStyle(*aStyle);

View File

@@ -443,27 +443,8 @@ NS_DECL_THREADSAFE_FFI_REFCOUNTING(nsIReferrerInfo, nsIReferrerInfo);
void Gecko_FillAllImageLayers(nsStyleImageLayers* layers, uint32_t max_len); 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*); 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_SetLang(nsStyleFont* font, nsAtom* atom);
void Gecko_nsStyleFont_CopyLangFrom(nsStyleFont* aFont, void Gecko_nsStyleFont_CopyLangFrom(nsStyleFont* aFont,

View File

@@ -598,6 +598,9 @@ cbindgen-types = [
{ gecko = "StyleScrollbarGutter", servo = "crate::values::computed::ScrollbarGutter" }, { gecko = "StyleScrollbarGutter", servo = "crate::values::computed::ScrollbarGutter" },
{ gecko = "StyleHyphenateCharacter", servo = "crate::values::computed::HyphenateCharacter" }, { gecko = "StyleHyphenateCharacter", servo = "crate::values::computed::HyphenateCharacter" },
{ gecko = "StyleContentVisibility", servo = "crate::values::computed::ContentVisibility" }, { 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 = [ mapped-generic-types = [

View File

@@ -59,8 +59,8 @@ bool ServoCSSParser::ParseTransformIntoMatrix(const nsACString& aValue,
/* static */ /* static */
bool ServoCSSParser::ParseFontShorthandForMatching( bool ServoCSSParser::ParseFontShorthandForMatching(
const nsACString& aValue, URLExtraData* aUrl, StyleFontFamilyList& aList, const nsACString& aValue, URLExtraData* aUrl, StyleFontFamilyList& aList,
StyleComputedFontStyleDescriptor& aStyle, float& aStretch, float& aWeight, StyleFontStyle& aStyle, StyleFontStretch& aStretch,
float* aSize) { StyleFontWeight& aWeight, float* aSize) {
return Servo_ParseFontShorthandForMatching(&aValue, aUrl, &aList, &aStyle, return Servo_ParseFontShorthandForMatching(&aValue, aUrl, &aList, &aStyle,
&aStretch, &aWeight, aSize); &aStretch, &aWeight, aSize);
} }

View File

@@ -28,6 +28,9 @@ namespace mozilla {
class ServoStyleSet; class ServoStyleSet;
struct URLExtraData; struct URLExtraData;
struct StyleFontFamilyList; struct StyleFontFamilyList;
struct StyleFontStretch;
struct StyleFontWeight;
struct StyleFontStyle;
union StyleComputedFontStyleDescriptor; union StyleComputedFontStyleDescriptor;
namespace css { namespace css {
@@ -124,8 +127,8 @@ class ServoCSSParser {
*/ */
static bool ParseFontShorthandForMatching( static bool ParseFontShorthandForMatching(
const nsACString& aValue, URLExtraData* aUrl, StyleFontFamilyList& aList, const nsACString& aValue, URLExtraData* aUrl, StyleFontFamilyList& aList,
StyleComputedFontStyleDescriptor& aStyle, float& aStretch, float& aWeight, StyleFontStyle& aStyle, StyleFontStretch& aStretch,
float* aSize = nullptr); StyleFontWeight& aWeight, float* aSize = nullptr);
/** /**
* Get a URLExtraData from a document. * Get a URLExtraData from a document.

View File

@@ -210,6 +210,22 @@ using StyleMatrixTransformOperator =
using StyleAtomicUsize = std::atomic<size_t>; using StyleAtomicUsize = std::atomic<size_t>;
# 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 } // namespace mozilla
# ifndef HAVE_64BIT_BUILD # ifndef HAVE_64BIT_BUILD

View File

@@ -1054,6 +1054,32 @@ inline AspectRatio StyleAspectRatio::ToLayoutRatio() const {
: AspectRatio(); : 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 } // namespace mozilla
#endif #endif

View File

@@ -12,7 +12,6 @@
#include "mozilla/Attributes.h" #include "mozilla/Attributes.h"
#include "mozilla/CORSMode.h" #include "mozilla/CORSMode.h"
#include "mozilla/EnumTypeTraits.h" #include "mozilla/EnumTypeTraits.h"
#include "mozilla/FontPropertyTypes.h"
#include "mozilla/MemoryReporting.h" #include "mozilla/MemoryReporting.h"
#include "mozilla/ServoBindingTypes.h" #include "mozilla/ServoBindingTypes.h"
#include "mozilla/URLExtraData.h" #include "mozilla/URLExtraData.h"

View File

@@ -9,7 +9,6 @@
#include "mozilla/dom/Document.h" #include "mozilla/dom/Document.h"
#include "mozilla/ExpandedPrincipal.h" #include "mozilla/ExpandedPrincipal.h"
#include "mozilla/FontPropertyTypes.h"
#include "nsIContent.h" #include "nsIContent.h"
#include "nsCSSProps.h" #include "nsCSSProps.h"
#include "nsContentUtils.h" #include "nsContentUtils.h"
@@ -327,20 +326,3 @@ bool nsStyleUtil::CSPAllowsInlineStyle(
return allowInlineStyle; 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");
}
}
}

View File

@@ -24,7 +24,6 @@ struct nsCSSValueList;
struct nsStylePosition; struct nsStylePosition;
namespace mozilla { namespace mozilla {
class FontSlantStyle;
namespace dom { namespace dom {
class Document; class Document;
class Element; class Element;
@@ -55,9 +54,6 @@ class nsStyleUtil {
static void AppendEscapedCSSIdent(const nsAString& aIdent, static void AppendEscapedCSSIdent(const nsAString& aIdent,
nsAString& aResult); nsAString& aResult);
static void AppendFontSlantStyle(const mozilla::FontSlantStyle&,
nsAString& aResult);
public: public:
static void AppendCSSNumber(float aNumber, nsAString& aResult) { static void AppendCSSNumber(float aNumber, nsAString& aResult) {
aResult.AppendFloat(aNumber); aResult.AppendFloat(aNumber);

View File

@@ -143,7 +143,10 @@ pub fn fmap_trait_output(input: &DeriveInput, trait_path: &Path, trait_output: &
let ident = &data.ident; let ident = &data.ident;
GenericArgument::Type(parse_quote!(<#ident as #trait_path>::#trait_output)) 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(), .collect(),
colon2_token: Default::default(), colon2_token: Default::default(),

View File

@@ -12,14 +12,14 @@ use crate::parser::{Parse, ParserContext};
use crate::properties::longhands::font_language_override; use crate::properties::longhands::font_language_override;
use crate::shared_lock::{SharedRwLockReadGuard, ToCssWithGuard}; use crate::shared_lock::{SharedRwLockReadGuard, ToCssWithGuard};
use crate::str::CssStringWriter; 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; use crate::values::generics::font::FontStyle as GenericFontStyle;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use crate::values::specified::font::SpecifiedFontFeatureSettings; use crate::values::specified::font::SpecifiedFontFeatureSettings;
use crate::values::specified::font::SpecifiedFontStyle; use crate::values::specified::font::SpecifiedFontStyle;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use crate::values::specified::font::SpecifiedFontVariationSettings; 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::url::SpecifiedUrl;
use crate::values::specified::{Angle, NonNegativePercentage}; use crate::values::specified::{Angle, NonNegativePercentage};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
@@ -170,7 +170,7 @@ fn sort_range<T: PartialOrd>(a: T, b: T) -> (T, T) {
impl FontWeightRange { impl FontWeightRange {
/// Returns a computed font-stretch range. /// Returns a computed font-stretch range.
pub fn compute(&self) -> ComputedFontWeightRange { 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) ComputedFontWeightRange(min, max)
} }
} }
@@ -179,23 +179,23 @@ impl FontWeightRange {
/// ///
/// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-stretch /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-stretch
#[derive(Clone, Debug, PartialEq, ToShmem)] #[derive(Clone, Debug, PartialEq, ToShmem)]
pub struct FontStretchRange(pub FontStretch, pub FontStretch); pub struct FontStretchRange(pub SpecifiedFontStretch, pub SpecifiedFontStretch);
impl_range!(FontStretchRange, FontStretch); impl_range!(FontStretchRange, SpecifiedFontStretch);
/// The computed representation of the above, so that /// The computed representation of the above, so that Gecko can read them
/// Gecko can read them easily. /// easily.
#[repr(C)] #[repr(C)]
#[allow(missing_docs)] #[allow(missing_docs)]
pub struct ComputedFontStretchRange(f32, f32); pub struct ComputedFontStretchRange(FontStretch, FontStretch);
impl FontStretchRange { impl FontStretchRange {
/// Returns a computed font-stretch range. /// Returns a computed font-stretch range.
pub fn compute(&self) -> ComputedFontStretchRange { pub fn compute(&self) -> ComputedFontStretchRange {
fn compute_stretch(s: &FontStretch) -> f32 { fn compute_stretch(s: &SpecifiedFontStretch) -> FontStretch {
match *s { match *s {
FontStretch::Keyword(ref kw) => kw.compute().0, SpecifiedFontStretch::Keyword(ref kw) => kw.compute(),
FontStretch::Stretch(ref p) => p.0.get(), SpecifiedFontStretch::Stretch(ref p) => FontStretch::from_percentage(p.0.get()),
FontStretch::System(..) => unreachable!(), SpecifiedFontStretch::System(..) => unreachable!(),
} }
} }

View File

@@ -895,57 +895,9 @@ fn static_assert() {
} }
} }
pub fn set_font_weight(&mut self, v: longhands::font_weight::computed_value::T) { ${impl_simple('font_weight', 'mFont.weight')}
unsafe { bindings::Gecko_FontWeight_SetFloat(&mut self.gecko.mFont.weight, v.0) }; ${impl_simple('font_stretch', 'mFont.stretch')}
} ${impl_simple('font_style', 'mFont.style')}
${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_type_with_conversion("font_synthesis", "mFont.synthesis")} ${impl_simple_type_with_conversion("font_synthesis", "mFont.synthesis")}

View File

@@ -352,11 +352,10 @@ pub mod system_font {
fn to_computed_value(&self, cx: &Context) -> Self::ComputedValue { fn to_computed_value(&self, cx: &Context) -> Self::ComputedValue {
use crate::gecko_bindings::bindings; use crate::gecko_bindings::bindings;
use crate::gecko_bindings::structs::nsFont; use crate::gecko_bindings::structs::nsFont;
use std::mem; use crate::values::computed::font::FontSize;
use crate::values::computed::Percentage;
use crate::values::specified::font::KeywordInfo; use crate::values::specified::font::KeywordInfo;
use crate::values::computed::font::{FontSize, FontStretch, FontStyle};
use crate::values::generics::NonNegative; use crate::values::generics::NonNegative;
use std::mem;
let mut system = mem::MaybeUninit::<nsFont>::uninit(); let mut system = mem::MaybeUninit::<nsFont>::uninit();
let system = unsafe { let system = unsafe {
@@ -368,20 +367,15 @@ pub mod system_font {
); );
&mut *system.as_mut_ptr() &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 { let ret = ComputedSystemFont {
font_family: system.family.clone(), font_family: system.family.clone(),
font_size: FontSize { font_size: FontSize {
size: NonNegative(cx.maybe_zoom_text(system.size.0)), size: NonNegative(cx.maybe_zoom_text(system.size.0)),
keyword_info: KeywordInfo::none() keyword_info: KeywordInfo::none()
}, },
font_weight, font_weight: system.weight,
font_stretch, font_stretch: system.stretch,
font_style, font_style: system.style,
font_size_adjust: system.sizeAdjust, font_size_adjust: system.sizeAdjust,
% for kwprop in kw_font_props: % for kwprop in kw_font_props:
${kwprop}: longhands::${kwprop}::computed_value::T::from_gecko_keyword( ${kwprop}: longhands::${kwprop}::computed_value::T::from_gecko_keyword(

View File

@@ -357,12 +357,11 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
fn adjust_for_mathvariant(&mut self) { fn adjust_for_mathvariant(&mut self) {
use crate::properties::longhands::_moz_math_variant::computed_value::T as MozMathVariant; 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::computed::font::{FontWeight, FontStyle};
use crate::values::generics::font::FontStyle;
if self.style.get_font().clone__moz_math_variant() != MozMathVariant::None { if self.style.get_font().clone__moz_math_variant() != MozMathVariant::None {
let font_style = self.style.mutate_font(); let font_style = self.style.mutate_font();
font_style.set_font_weight(FontWeight::normal()); font_style.set_font_weight(FontWeight::NORMAL);
font_style.set_font_style(FontStyle::Normal); font_style.set_font_style(FontStyle::NORMAL);
} }
} }

View File

@@ -5,18 +5,11 @@
//! Animation implementation for various font-related types. //! Animation implementation for various font-related types.
use super::{Animate, Procedure, ToAnimatedZero}; 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::computed::Number;
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance}; use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::generics::font::{FontSettings as GenericFontSettings, FontTag, VariationValue}; use crate::values::generics::font::{FontSettings as GenericFontSettings, FontTag, VariationValue};
impl ToAnimatedZero for FontWeight {
#[inline]
fn to_animated_zero(&self) -> Result<Self, ()> {
Ok(FontWeight::normal())
}
}
/// <https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def> /// <https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def>
impl Animate for FontVariationSettings { impl Animate for FontVariationSettings {
#[inline] #[inline]

View File

@@ -4,27 +4,23 @@
//! Computed values for font properties //! Computed values for font properties
#[cfg(feature = "gecko")]
use crate::gecko_bindings::{bindings, structs};
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::values::animated::ToAnimatedValue; use crate::values::animated::ToAnimatedValue;
use crate::values::computed::{ 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::{FeatureTagValue, FontSettings, VariationValue};
use crate::values::generics::{font as generics, NonNegative}; use crate::values::generics::{font as generics, NonNegative};
use crate::values::specified::font::{ use crate::values::specified::font::{
self as specified, KeywordInfo, MAX_FONT_WEIGHT, MIN_FONT_WEIGHT, self as specified, KeywordInfo, MAX_FONT_WEIGHT, MIN_FONT_WEIGHT,
}; };
use crate::values::specified::length::{FontBaseSize, NoCalcLength}; use crate::values::specified::length::{FontBaseSize, NoCalcLength};
use crate::values::CSSFloat;
use crate::Atom; use crate::Atom;
use cssparser::{serialize_identifier, CssStringWriter, Parser}; use cssparser::{serialize_identifier, CssStringWriter, Parser};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use std::hash::{Hash, Hasher};
use style_traits::{CssWriter, ParseError, ToCss}; use style_traits::{CssWriter, ParseError, ToCss};
pub use crate::values::computed::Length as MozScriptMinSize; 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::font::{XLang, XTextZoom};
pub use crate::values::specified::Integer as SpecifiedInteger; 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<T, const FRACTION_BITS: u16> {
value: T,
}
impl<T, const FRACTION_BITS: u16> FixedPoint<T, FRACTION_BITS>
where
T: num_traits::cast::AsPrimitive<f32>,
f32: num_traits::cast::AsPrimitive<T>,
{
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<u16, FONT_WEIGHT_FRACTION_BITS>;
/// A value for the font-weight property per: /// A value for the font-weight property per:
/// ///
/// https://drafts.csswg.org/css-fonts-4/#propdef-font-weight /// 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( #[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))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct FontWeight(pub Number); #[repr(C)]
pub struct FontWeight(FontWeightFixedPoint);
impl Hash for FontWeight {
fn hash<H: Hasher>(&self, hasher: &mut H) {
hasher.write_u64((self.0 * 10000.).trunc() as u64);
}
}
impl ToAnimatedValue for FontWeight { impl ToAnimatedValue for FontWeight {
type AnimatedValue = Number; type AnimatedValue = Number;
#[inline] #[inline]
fn to_animated_value(self) -> Self::AnimatedValue { fn to_animated_value(self) -> Self::AnimatedValue {
self.0 self.value()
} }
#[inline] #[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self { 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<W>(&self, dest: &mut CssWriter<W>) -> 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, 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 { impl FontSize {
/// The actual computed font size. /// The actual computed font size.
#[inline] #[inline]
@@ -771,76 +838,66 @@ impl ToComputedValue for specified::MathDepth {
} }
} }
/// A wrapper over an `Angle`, that handles clamping to the appropriate range /// - Use a signed 8.8 fixed-point value (representable range -128.0..128)
/// for `font-style` animation. ///
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss, ToResolvedValue)] /// Values of <angle> below -90 or above 90 not permitted, so we use out of
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] /// range values to represent normal | oblique
pub struct FontStyleAngle(pub Angle); pub const FONT_STYLE_FRACTION_BITS: u16 = 8;
impl ToAnimatedValue for FontStyleAngle { /// This is an alias which is useful mostly as a cbindgen / C++ inference
type AnimatedValue = Angle; /// workaround.
pub type FontStyleFixedPoint = FixedPoint<i16, FONT_STYLE_FRACTION_BITS>;
#[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<H: Hasher>(&self, hasher: &mut H) {
hasher.write_u64((self.0.degrees() * 10000.).trunc() as u64);
}
}
/// The computed value of `font-style`. /// The computed value of `font-style`.
/// ///
/// FIXME(emilio): Angle should be a custom type to handle clamping during /// - Define out of range values min value (-128.0) as meaning 'normal'
/// animation. /// - Define max value (127.99609375) as 'italic'
pub type FontStyle = generics::FontStyle<FontStyleAngle>; /// - Other values represent 'oblique <angle>'
/// - 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 { 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. /// The `normal` value.
#[inline] #[inline]
pub fn normal() -> Self { pub fn normal() -> Self {
generics::FontStyle::Normal Self::NORMAL
} }
/// The default angle for font-style: oblique. This is 20deg per spec: /// Returns the oblique angle for this style.
/// pub fn oblique(degrees: f32) -> Self {
/// https://drafts.csswg.org/css-fonts-4/#valdef-font-style-oblique-angle Self(FixedPoint::from_float(
#[inline] degrees
pub fn default_angle() -> FontStyleAngle { .max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES)
FontStyleAngle(Angle::from_degrees( .min(specified::FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES)
specified::DEFAULT_FONT_STYLE_OBLIQUE_ANGLE_DEGREES,
)) ))
} }
/// Get the font style from Gecko's nsFont struct. /// Returns the oblique angle for this style.
#[cfg(feature = "gecko")] pub fn oblique_degrees(&self) -> f32 {
pub fn from_gecko(style: structs::FontSlantStyle) -> Self { debug_assert_ne!(*self, Self::NORMAL);
let mut angle = 0.; debug_assert_ne!(*self, Self::ITALIC);
let mut italic = false; self.0.to_float()
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)))
} }
} }
@@ -849,43 +906,173 @@ impl ToCss for FontStyle {
where where
W: fmt::Write, W: fmt::Write,
{ {
match *self { if *self == Self::NORMAL {
generics::FontStyle::Normal => dest.write_str("normal"), return dest.write_str("normal")
generics::FontStyle::Italic => dest.write_str("italic"), }
generics::FontStyle::Oblique(ref angle) => { if *self == Self::ITALIC {
dest.write_str("oblique")?; return dest.write_str("italic")
// Use `degrees` instead of just comparing Angle because }
// `degrees` can return slightly different values due to if *self == Self::OBLIQUE {
// floating point conversions. return dest.write_str("oblique");
if angle.0.degrees() != Self::default_angle().0.degrees() { }
dest.write_char(' ')?; dest.write_str("oblique ")?;
angle.to_css(dest)?; let angle = Angle::from_degrees(self.oblique_degrees());
} angle.to_css(dest)?;
Ok(()) Ok(())
}, }
}
impl ToAnimatedValue for FontStyle {
type AnimatedValue = generics::FontStyle<Angle>;
#[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<u16, FONT_STRETCH_FRACTION_BITS>;
/// A value for the font-stretch property per: /// A value for the font-stretch property per:
/// ///
/// https://drafts.csswg.org/css-fonts-4/#propdef-font-stretch /// https://drafts.csswg.org/css-fonts-4/#propdef-font-stretch
///
/// cbindgen:derive-lt
/// cbindgen:derive-lte
/// cbindgen:derive-gt
/// cbindgen:derive-gte
#[derive( #[derive(
Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss, ToResolvedValue, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue,
)] )]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[repr(C)]
pub struct FontStretch(pub NonNegativePercentage); pub struct FontStretch(pub FontStretchFixedPoint);
impl FontStretch { 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% /// 100%
pub fn hundred() -> Self { pub fn hundred() -> Self {
FontStretch(NonNegativePercentage::hundred()) Self::NORMAL
} }
/// The float value of the percentage /// Converts to a computed percentage.
#[inline] #[inline]
pub fn value(&self) -> CSSFloat { pub fn to_percentage(&self) -> Percentage {
((self.0).0).0 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<specified::FontStretchKeyword> {
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<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
self.to_percentage().to_css(dest)
} }
} }
@@ -894,17 +1081,11 @@ impl ToAnimatedValue for FontStretch {
#[inline] #[inline]
fn to_animated_value(self) -> Self::AnimatedValue { fn to_animated_value(self) -> Self::AnimatedValue {
self.0.to_animated_value() self.to_percentage()
} }
#[inline] #[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self { fn from_animated_value(animated: Self::AnimatedValue) -> Self {
FontStretch(NonNegativePercentage::from_animated_value(animated)) Self::from_percentage(animated.0)
}
}
impl Hash for FontStretch {
fn hash<H: Hasher>(&self, hasher: &mut H) {
hasher.write_u64((self.value() * 10000.).trunc() as u64);
} }
} }

View File

@@ -50,6 +50,13 @@ impl ComputeSquaredDistance for u16 {
} }
} }
impl ComputeSquaredDistance for i16 {
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
Ok(SquaredDistance::from_sqrt((*self - *other).abs() as f64))
}
}
impl ComputeSquaredDistance for i32 { impl ComputeSquaredDistance for i32 {
#[inline] #[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {

View File

@@ -63,11 +63,12 @@ macro_rules! trivial_to_resolved_value {
trivial_to_resolved_value!(()); trivial_to_resolved_value!(());
trivial_to_resolved_value!(bool); trivial_to_resolved_value!(bool);
trivial_to_resolved_value!(f32); trivial_to_resolved_value!(f32);
trivial_to_resolved_value!(i32);
trivial_to_resolved_value!(u8); trivial_to_resolved_value!(u8);
trivial_to_resolved_value!(i8); trivial_to_resolved_value!(i8);
trivial_to_resolved_value!(u16); trivial_to_resolved_value!(u16);
trivial_to_resolved_value!(i16);
trivial_to_resolved_value!(u32); trivial_to_resolved_value!(u32);
trivial_to_resolved_value!(i32);
trivial_to_resolved_value!(usize); trivial_to_resolved_value!(usize);
trivial_to_resolved_value!(String); trivial_to_resolved_value!(String);
trivial_to_resolved_value!(Box<str>); trivial_to_resolved_value!(Box<str>);

View File

@@ -7,10 +7,10 @@
use crate::context::QuirksMode; use crate::context::QuirksMode;
use crate::font_metrics::FontMetricsProvider; use crate::font_metrics::FontMetricsProvider;
use crate::parser::{Parse, ParserContext}; 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::FontSizeAdjust as ComputedFontSizeAdjust;
use crate::values::computed::{font as computed, Length, NonNegativeLength}; 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::computed::{CSSPixelLength, Context, ToComputedValue};
use crate::values::generics::font::VariationValue; use crate::values::generics::font::VariationValue;
use crate::values::generics::font::{ use crate::values::generics::font::{
@@ -164,7 +164,7 @@ impl ToComputedValue for FontWeight {
#[inline] #[inline]
fn from_computed_value(computed: &computed::FontWeight) -> Self { fn from_computed_value(computed: &computed::FontWeight) -> Self {
FontWeight::Absolute(AbsoluteFontWeight::Weight(Number::from_computed_value( FontWeight::Absolute(AbsoluteFontWeight::Weight(Number::from_computed_value(
&computed.0, &computed.value(),
))) )))
} }
} }
@@ -189,10 +189,10 @@ impl AbsoluteFontWeight {
pub fn compute(&self) -> computed::FontWeight { pub fn compute(&self) -> computed::FontWeight {
match *self { match *self {
AbsoluteFontWeight::Weight(weight) => { 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::Normal => computed::FontWeight::NORMAL,
AbsoluteFontWeight::Bold => computed::FontWeight::bold(), AbsoluteFontWeight::Bold => computed::FontWeight::BOLD,
} }
} }
} }
@@ -268,33 +268,24 @@ impl ToComputedValue for SpecifiedFontStyle {
fn to_computed_value(&self, _: &Context) -> Self::ComputedValue { fn to_computed_value(&self, _: &Context) -> Self::ComputedValue {
match *self { match *self {
generics::FontStyle::Normal => generics::FontStyle::Normal, Self::Normal => computed::FontStyle::NORMAL,
generics::FontStyle::Italic => generics::FontStyle::Italic, Self::Italic => computed::FontStyle::ITALIC,
generics::FontStyle::Oblique(ref angle) => { Self::Oblique(ref angle) => computed::FontStyle::oblique(angle.degrees()),
generics::FontStyle::Oblique(FontStyleAngle(Self::compute_angle(angle)))
},
} }
} }
fn from_computed_value(computed: &Self::ComputedValue) -> Self { fn from_computed_value(computed: &Self::ComputedValue) -> Self {
match *computed { if *computed == computed::FontStyle::NORMAL {
generics::FontStyle::Normal => generics::FontStyle::Normal, return Self::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::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: /// From https://drafts.csswg.org/css-fonts-4/#valdef-font-style-oblique-angle:
/// ///
/// Values less than -90deg or values greater than 90deg are /// Values less than -90deg or values greater than 90deg are
@@ -315,10 +306,6 @@ impl SpecifiedFontStyle {
.min(FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES) .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. /// Parse a suitable angle for font-style: oblique.
pub fn parse_angle<'i, 't>( pub fn parse_angle<'i, 't>(
context: &ParserContext, context: &ParserContext,
@@ -341,7 +328,7 @@ impl SpecifiedFontStyle {
/// The default angle for `font-style: oblique`. /// The default angle for `font-style: oblique`.
pub fn default_angle() -> Angle { pub fn default_angle() -> Angle {
Angle::from_degrees( Angle::from_degrees(
DEFAULT_FONT_STYLE_OBLIQUE_ANGLE_DEGREES, computed::FontStyle::DEFAULT_OBLIQUE_DEGREES as f32,
/* was_calc = */ false, /* was_calc = */ false,
) )
} }
@@ -390,7 +377,6 @@ impl ToComputedValue for FontStyle {
#[derive( #[derive(
Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem,
)] )]
#[repr(u8)]
pub enum FontStretch { pub enum FontStretch {
Stretch(NonNegativePercentage), Stretch(NonNegativePercentage),
Keyword(FontStretchKeyword), Keyword(FontStretchKeyword),
@@ -416,57 +402,15 @@ pub enum FontStretchKeyword {
} }
impl FontStretchKeyword { impl FontStretchKeyword {
/// Resolves the value of the keyword as specified in: /// Turns the keyword into a computed value.
/// pub fn compute(&self) -> computed::FontStretch {
/// https://drafts.csswg.org/css-fonts-4/#font-stretch-prop computed::FontStretch::from_keyword(*self)
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.,
})
} }
/// Does the opposite operation to `compute`, in order to serialize keywords /// Does the opposite operation to `compute`, in order to serialize keywords
/// if possible. /// if possible.
pub fn from_percentage(percentage: f32) -> Option<Self> { pub fn from_percentage(p: f32) -> Option<Self> {
use self::FontStretchKeyword::*; computed::FontStretch::from_percentage(p).as_keyword()
// 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
} }
} }
@@ -485,16 +429,17 @@ impl ToComputedValue for FontStretch {
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self { match *self {
FontStretch::Stretch(ref percentage) => { 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), FontStretch::System(_) => self.compute_system(context),
} }
} }
fn from_computed_value(computed: &Self::ComputedValue) -> Self { fn from_computed_value(computed: &Self::ComputedValue) -> Self {
FontStretch::Stretch(NonNegativePercentage::from_computed_value(&NonNegative( FontStretch::Stretch(NonNegativePercentage::from_computed_value(&NonNegative(
(computed.0).0, computed.to_percentage()
))) )))
} }
} }

View File

@@ -898,3 +898,21 @@ renaming_overrides_prefixing = true
public: public:
inline nsAtom* AsAtom() const; 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);
"""

View File

@@ -28,7 +28,7 @@ use style::data::{self, ElementStyles};
use style::dom::{ShowSubtreeData, TDocument, TElement, TNode}; use style::dom::{ShowSubtreeData, TDocument, TElement, TNode};
use style::driver; use style::driver;
use style::error_reporting::{ContextualParseError, ParseErrorReporter}; 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::font_metrics::{get_metrics_provider_for_product, FontMetricsProvider};
use style::gecko::data::{GeckoStyleSheet, PerDocumentStyleData, PerDocumentStyleDataImpl}; use style::gecko::data::{GeckoStyleSheet, PerDocumentStyleData, PerDocumentStyleDataImpl};
use style::gecko::restyle_damage::GeckoRestyleDamage; use style::gecko::restyle_damage::GeckoRestyleDamage;
@@ -137,7 +137,7 @@ use style::traversal_flags::{self, TraversalFlags};
use style::use_counters::UseCounters; use style::use_counters::UseCounters;
use style::values::animated::{Animate, Procedure, ToAnimatedZero}; use style::values::animated::{Animate, Procedure, ToAnimatedZero};
use style::values::computed::easing::ComputedLinearStop; 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::computed::{self, Context, ToComputedValue};
use style::values::distance::ComputeSquaredDistance; use style::values::distance::ComputeSquaredDistance;
use style::values::specified::gecko::IntersectionObserverRootMargin; 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) longhands::font_size::SpecifiedValue::from_html_size(value as u8)
}, },
FontStyle => { FontStyle => {
let val = if value == structs::NS_FONT_STYLE_ITALIC { style::values::specified::FontStyle::Specified(if value == structs::NS_FONT_STYLE_ITALIC {
FontStyle::Italic FontStyle::Italic
} else { } else {
debug_assert_eq!(value, structs::NS_FONT_STYLE_NORMAL); debug_assert_eq!(value, structs::NS_FONT_STYLE_NORMAL);
FontStyle::Normal FontStyle::Normal
}; })
ToComputedValue::from_computed_value(&val)
}, },
FontWeight => longhands::font_weight::SpecifiedValue::from_gecko_keyword(value), FontWeight => longhands::font_weight::SpecifiedValue::from_gecko_keyword(value),
ListStyleType => Box::new(longhands::list_style_type::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, value: &nsACString,
data: *mut URLExtraData, data: *mut URLExtraData,
family: &mut FontFamilyList, family: &mut FontFamilyList,
style: &mut ComputedFontStyleDescriptor, style: &mut FontStyle,
stretch: &mut f32, stretch: &mut FontStretch,
weight: &mut f32, weight: &mut FontWeight,
size: Option<&mut f32>, size: Option<&mut f32>,
) -> bool { ) -> bool {
use style::properties::shorthands::font; 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::generics::font::FontStyle as GenericFontStyle;
use style::values::specified::font::{
FontFamily, FontSize, FontStretch, FontStyle, FontWeight, SpecifiedFontStyle,
};
let string = value.as_str_unchecked(); let string = value.as_str_unchecked();
let mut input = ParserInput::new(&string); 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. // The system font is not acceptable, so we return false.
match font.font_family { match font.font_family {
FontFamily::Values(list) => *family = list, specified::FontFamily::Values(list) => *family = list,
FontFamily::System(_) => return false, specified::FontFamily::System(_) => return false,
} }
let specified_font_style = match font.font_style { let specified_font_style = match font.font_style {
FontStyle::Specified(ref s) => s, specified::FontStyle::Specified(ref s) => s,
FontStyle::System(_) => return false, specified::FontStyle::System(_) => return false,
}; };
*style = match *specified_font_style { *style = match *specified_font_style {
GenericFontStyle::Normal => ComputedFontStyleDescriptor::Normal, GenericFontStyle::Normal => FontStyle::NORMAL,
GenericFontStyle::Italic => ComputedFontStyleDescriptor::Italic, GenericFontStyle::Italic => FontStyle::ITALIC,
GenericFontStyle::Oblique(ref angle) => { GenericFontStyle::Oblique(ref angle) => FontStyle::oblique(angle.degrees()),
let angle = SpecifiedFontStyle::compute_angle_degrees(angle);
ComputedFontStyleDescriptor::Oblique(angle, angle)
},
}; };
*stretch = match font.font_stretch { *stretch = match font.font_stretch {
FontStretch::Keyword(ref k) => k.compute().0, specified::FontStretch::Keyword(ref k) => k.compute(),
FontStretch::Stretch(ref p) => p.0.get(), specified::FontStretch::Stretch(ref p) => FontStretch::from_percentage(p.0.get()),
FontStretch::System(_) => return false, specified::FontStretch::System(_) => return false,
}; };
*weight = match font.font_weight { *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 // Resolve relative font weights against the initial of font-weight
// (normal, which is equivalent to 400). // (normal, which is equivalent to 400).
FontWeight::Bolder => ComputedFontWeight::normal().bolder().0, specified::FontWeight::Bolder => FontWeight::normal().bolder(),
FontWeight::Lighter => ComputedFontWeight::normal().lighter().0, specified::FontWeight::Lighter => FontWeight::normal().lighter(),
FontWeight::System(_) => return false, specified::FontWeight::System(_) => return false,
}; };
// XXX This is unfinished; see values::specified::FontSize::ToComputedValue // XXX This is unfinished; see values::specified::FontSize::ToComputedValue
// for a more complete implementation (but we can't use it as-is). // for a more complete implementation (but we can't use it as-is).
if let Some(size) = size { if let Some(size) = size {
*size = match font.font_size { *size = match font.font_size {
FontSize::Length(lp) => { specified::FontSize::Length(lp) => {
use style::values::generics::transform::ToAbsoluteLength; use style::values::generics::transform::ToAbsoluteLength;
match lp.to_pixel_length(None) { match lp.to_pixel_length(None) {
Ok(len) => len, Ok(len) => len,
@@ -7095,7 +7087,7 @@ pub unsafe extern "C" fn Servo_ParseFontShorthandForMatching(
} }
}, },
// Map absolute-size keywords to sizes. // Map absolute-size keywords to sizes.
FontSize::Keyword(info) => { specified::FontSize::Keyword(info) => {
let metrics = get_metrics_provider_for_product(); let metrics = get_metrics_provider_for_product();
// TODO: Maybe get a meaningful language / quirks-mode from the // TODO: Maybe get a meaningful language / quirks-mode from the
// caller? // 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() info.kw.to_length_without_context(quirks_mode, &metrics, &language, family).0.px()
} }
// smaller, larger not currently supported // smaller, larger not currently supported
FontSize::Smaller | FontSize::Larger | FontSize::System(_) => { specified::FontSize::Smaller | specified::FontSize::Larger | specified::FontSize::System(_) => {
return false; return false;
} }
}; };
@@ -7348,6 +7340,31 @@ pub extern "C" fn Servo_LengthPercentage_ToCss(
lp.to_css(&mut CssWriter::new(result)).unwrap(); 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] #[no_mangle]
pub unsafe extern "C" fn Servo_CursorKind_Parse( pub unsafe extern "C" fn Servo_CursorKind_Parse(
cursor: &nsACString, cursor: &nsACString,

View File

@@ -245,12 +245,12 @@ wine:
strip-components: 1 strip-components: 1
add-prefix: wine-source/ add-prefix: wine-source/
cbindgen-0.24.2: cbindgen-0.24.3:
description: cbindgen source code description: cbindgen source code
fetch: fetch:
type: git type: git
repo: https://github.com/eqrion/cbindgen repo: https://github.com/eqrion/cbindgen
revision: 3d06ae1fc4984b82ada2d84ce74c7af06ffd499d revision: f43ccfc047a1a160267f32355c5e5e7154a2665a
cctools-port: cctools-port:
description: cctools-port source code description: cctools-port source code

View File

@@ -16,7 +16,7 @@ job-defaults:
fetch: fetch:
# If you update this, make sure to update the minimum version in # If you update this, make sure to update the minimum version in
# build/moz.configure/bindgen.configure as well. # build/moz.configure/bindgen.configure as well.
- cbindgen-0.24.2 - cbindgen-0.24.3
linux64-cbindgen: linux64-cbindgen:
treeherder: treeherder:

View File

@@ -418,9 +418,9 @@ nsresult nsLookAndFeel::NativeGetFloat(FloatID aID, float& aResult) {
bool nsLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, bool nsLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName,
gfxFontStyle& aFontStyle) { gfxFontStyle& aFontStyle) {
aFontName.AssignLiteral("Roboto"); aFontName.AssignLiteral("Roboto");
aFontStyle.style = FontSlantStyle::Normal(); aFontStyle.style = FontSlantStyle::NORMAL;
aFontStyle.weight = FontWeight::Normal(); aFontStyle.weight = FontWeight::NORMAL;
aFontStyle.stretch = FontStretch::Normal(); aFontStyle.stretch = FontStretch::NORMAL;
aFontStyle.size = 9.0 * 96.0f / 72.0f; aFontStyle.size = 9.0 * 96.0f / 72.0f;
aFontStyle.systemFont = true; aFontStyle.systemFont = true;
return true; return true;

View File

@@ -548,9 +548,9 @@ bool nsLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, gfxFontStyle&
// hack for now // hack for now
if (aID == FontID::MozWindow || aID == FontID::MozDocument) { if (aID == FontID::MozWindow || aID == FontID::MozDocument) {
aFontStyle.style = mozilla::FontSlantStyle::Normal(); aFontStyle.style = mozilla::FontSlantStyle::NORMAL;
aFontStyle.weight = mozilla::FontWeight::Normal(); aFontStyle.weight = mozilla::FontWeight::NORMAL;
aFontStyle.stretch = mozilla::FontStretch::Normal(); aFontStyle.stretch = mozilla::FontStretch::NORMAL;
aFontStyle.size = 14; aFontStyle.size = 14;
aFontStyle.systemFont = true; aFontStyle.systemFont = true;

View File

@@ -1017,7 +1017,7 @@ nsresult nsLookAndFeel::NativeGetFloat(FloatID aID, float& aResult) {
static void GetSystemFontInfo(GtkStyleContext* aStyle, nsString* aFontName, static void GetSystemFontInfo(GtkStyleContext* aStyle, nsString* aFontName,
gfxFontStyle* aFontStyle) { gfxFontStyle* aFontStyle) {
aFontStyle->style = FontSlantStyle::Normal(); aFontStyle->style = FontSlantStyle::NORMAL;
// As in // As in
// https://git.gnome.org/browse/gtk+/tree/gtk/gtkwidget.c?h=3.22.19#n10333 // 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)); NS_ConvertUTF8toUTF16 family(pango_font_description_get_family(desc));
*aFontName = quote + family + quote; *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! // FIXME: Set aFontStyle->stretch correctly!
aFontStyle->stretch = FontStretch::Normal(); aFontStyle->stretch = FontStretch::NORMAL;
float size = float(pango_font_description_get_size(desc)) / PANGO_SCALE; float size = float(pango_font_description_get_size(desc)) / PANGO_SCALE;

View File

@@ -209,9 +209,9 @@ nsresult HeadlessLookAndFeel::NativeGetFloat(FloatID aID, float& aResult) {
bool HeadlessLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, bool HeadlessLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName,
gfxFontStyle& aFontStyle) { gfxFontStyle& aFontStyle) {
// Default to san-serif for everything. // Default to san-serif for everything.
aFontStyle.style = FontSlantStyle::Normal(); aFontStyle.style = FontSlantStyle::NORMAL;
aFontStyle.weight = FontWeight::Normal(); aFontStyle.weight = FontWeight::NORMAL;
aFontStyle.stretch = FontStretch::Normal(); aFontStyle.stretch = FontStretch::NORMAL;
aFontStyle.size = 14; aFontStyle.size = 14;
aFontStyle.systemFont = true; aFontStyle.systemFont = true;

View File

@@ -982,9 +982,9 @@ bool nsXPLookAndFeel::LookAndFeelFontToStyle(const LookAndFeelFont& aFont,
aName = aFont.name(); aName = aFont.name();
aStyle = gfxFontStyle(); aStyle = gfxFontStyle();
aStyle.size = aFont.size(); aStyle.size = aFont.size();
aStyle.weight = FontWeight(aFont.weight()); aStyle.weight = FontWeight::FromInt(aFont.weight());
aStyle.style = aStyle.style =
aFont.italic() ? FontSlantStyle::Italic() : FontSlantStyle::Normal(); aFont.italic() ? FontSlantStyle::ITALIC : FontSlantStyle::NORMAL;
aStyle.systemFont = true; aStyle.systemFont = true;
return true; return true;
} }

View File

@@ -626,9 +626,9 @@ LookAndFeelFont nsLookAndFeel::GetLookAndFeelFontInternal(
result.size() = pixelHeight; result.size() = pixelHeight;
result.italic() = !!aLogFont.lfItalic; result.italic() = !!aLogFont.lfItalic;
// FIXME: Other weights? // FIXME: Other weights?
result.weight() = ((aLogFont.lfWeight == FW_BOLD) ? FontWeight::Bold() result.weight() =
: FontWeight::Normal()) ((aLogFont.lfWeight == FW_BOLD) ? FontWeight::BOLD : FontWeight::NORMAL)
.ToFloat(); .ToFloat();
return result; return result;
} }