Auto merge of #20047 - servo:derive-all-the-things, r=emilio

Move some font code around

The only notable change is that KeywordInfo is now generic.

<!-- Reviewable:start -->
---
This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/servo/20047)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2018-02-15 06:26:02 -05:00 committed by GitHub
commit 0baab064df
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 213 additions and 191 deletions

View file

@ -21,7 +21,8 @@ use std::fmt::{self, Write};
use std::str;
use str::CssStringWriter;
use values::computed::font::FamilyName;
use values::specified::font::{FontTag, FontVariationSettings, SpecifiedFontFeatureSettings};
use values::generics::font::FontTag;
use values::specified::font::{FontVariationSettings, SpecifiedFontFeatureSettings};
/// A @font-face rule
pub type FontFaceRule = RefPtr<nsCSSFontFaceRule>;

View file

@ -1452,8 +1452,7 @@ impl Clone for ${style_struct.gecko_struct_name} {
}
pub fn clone_${ident}(&self) -> longhands::${ident}::computed_value::T {
use values::generics::font::{FontSettings, ${tag_type}};
use values::specified::font::FontTag;
use values::generics::font::{FontSettings, FontTag, ${tag_type}};
FontSettings(
self.gecko.mFont.${gecko_ffi_name}.iter().map(|gecko_font_setting| {
@ -2390,7 +2389,7 @@ fn static_assert() {
}
pub fn set_font_size(&mut self, v: FontSize) {
use values::specified::font::KeywordSize;
use values::generics::font::KeywordSize;
self.gecko.mSize = v.size().0;
self.gecko.mScriptUnconstrainedSize = v.size().0;
if let Some(info) = v.keyword_info {
@ -2602,8 +2601,7 @@ fn static_assert() {
}
pub fn clone_font_size(&self) -> FontSize {
use values::computed::font::KeywordInfo;
use values::specified::font::KeywordSize;
use values::generics::font::{KeywordInfo, KeywordSize};
let size = Au(self.gecko.mSize).into();
let kw = match self.gecko.mFontSizeKeyword as u32 {
structs::NS_STYLE_FONT_SIZE_XXSMALL => KeywordSize::XXSmall,

View file

@ -52,14 +52,12 @@ use values::computed::transform::Translate as ComputedTranslate;
use values::computed::transform::Scale as ComputedScale;
use values::generics::transform::{self, Rotate, Translate, Scale, Transform, TransformOperation};
use values::distance::{ComputeSquaredDistance, SquaredDistance};
use values::generics::font::FontSettings as GenericFontSettings;
use values::generics::font::{FontSettings as GenericFontSettings, FontTag, VariationValue};
use values::computed::font::FontVariationSettings;
use values::generics::font::VariationValue;
use values::generics::effects::Filter;
use values::generics::position as generic_position;
use values::generics::svg::{SVGLength, SvgLengthOrPercentageOrNumber, SVGPaint};
use values::generics::svg::{SVGPaintKind, SVGStrokeDashArray, SVGOpacity};
use values::specified::font::FontTag;
use void::{self, Void};
/// <https://drafts.csswg.org/css-transitions/#animtype-repeatable-list>

View file

@ -13,7 +13,7 @@ use values::Impossible;
use values::animated::{Animate, Procedure, ToAnimatedValue, ToAnimatedZero};
use values::animated::color::RGBA;
use values::computed::{Angle, Number};
use values::computed::length::{Length, NonNegativeLength};
use values::computed::length::Length;
use values::distance::{ComputeSquaredDistance, SquaredDistance};
use values::generics::effects::BoxShadow as GenericBoxShadow;
use values::generics::effects::Filter as GenericFilter;
@ -33,7 +33,7 @@ pub type TextShadowList = ShadowList<SimpleShadow>;
pub struct ShadowList<Shadow>(Vec<Shadow>);
/// An animated value for a single `box-shadow`.
pub type BoxShadow = GenericBoxShadow<Option<RGBA>, Length, NonNegativeLength, Length>;
pub type BoxShadow = GenericBoxShadow<Option<RGBA>, Length, Length, Length>;
/// An animated value for the `filter` property.
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
@ -42,14 +42,14 @@ pub struct FilterList(pub Vec<Filter>);
/// An animated value for a single `filter`.
#[cfg(feature = "gecko")]
pub type Filter = GenericFilter<Angle, Number, NonNegativeLength, SimpleShadow>;
pub type Filter = GenericFilter<Angle, Number, Length, SimpleShadow>;
/// An animated value for a single `filter`.
#[cfg(not(feature = "gecko"))]
pub type Filter = GenericFilter<Angle, Number, NonNegativeLength, Impossible>;
pub type Filter = GenericFilter<Angle, Number, Length, Impossible>;
/// An animated value for the `drop-shadow()` filter.
pub type SimpleShadow = GenericSimpleShadow<Option<RGBA>, Length, NonNegativeLength>;
pub type SimpleShadow = GenericSimpleShadow<Option<RGBA>, Length, Length>;
impl ToAnimatedValue for ComputedBoxShadowList {
type AnimatedValue = BoxShadowList;

View file

@ -17,7 +17,6 @@ use values::computed::BorderCornerRadius as ComputedBorderCornerRadius;
use values::computed::ComputedUrl;
use values::computed::MaxLength as ComputedMaxLength;
use values::computed::MozLength as ComputedMozLength;
use values::computed::NonNegativeLength as ComputedNonNegativeLength;
use values::specified::url::SpecifiedUrl;
pub mod color;
@ -261,20 +260,6 @@ trivial_to_animated_value!(ComputedUrl);
trivial_to_animated_value!(bool);
trivial_to_animated_value!(f32);
impl ToAnimatedValue for ComputedNonNegativeLength {
type AnimatedValue = Self;
#[inline]
fn to_animated_value(self) -> Self {
self
}
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
ComputedNonNegativeLength::new(animated.px().max(0.))
}
}
impl ToAnimatedValue for ComputedBorderCornerRadius {
type AnimatedValue = Self;
@ -380,3 +365,16 @@ where
}
}
}
impl<T> ToAnimatedZero for Size2D<T>
where
T: ToAnimatedZero,
{
#[inline]
fn to_animated_zero(&self) -> Result<Self, ()> {
Ok(Size2D::new(
self.width.to_animated_zero()?,
self.height.to_animated_zero()?,
))
}
}

View file

@ -69,14 +69,6 @@ impl BorderCornerRadius {
}
}
impl ToAnimatedZero for BorderSpacing {
#[inline]
fn to_animated_zero(&self) -> Result<Self, ()> {
// FIXME(emilio): Why?
Err(())
}
}
impl ToAnimatedZero for BorderCornerRadius {
#[inline]
fn to_animated_zero(&self) -> Result<Self, ()> {

View file

@ -23,7 +23,8 @@ use style_traits::{CssWriter, ParseError, ToCss};
use values::CSSFloat;
use values::animated::{ToAnimatedValue, ToAnimatedZero};
use values::computed::{Context, NonNegativeLength, ToComputedValue, Integer, Number};
use values::generics::font::{FontSettings, FeatureTagValue, VariationValue};
use values::generics::font::{FontSettings, FeatureTagValue};
use values::generics::font::{KeywordInfo as GenericKeywordInfo, VariationValue};
use values::specified::font as specified;
use values::specified::length::{FontBaseSize, NoCalcLength};
@ -49,50 +50,8 @@ pub struct FontSize {
pub keyword_info: Option<KeywordInfo>,
}
#[derive(Animate, ComputeSquaredDistance, MallocSizeOf, ToAnimatedValue, ToAnimatedZero)]
#[derive(Clone, Copy, Debug, PartialEq)]
/// Additional information for keyword-derived font sizes.
pub struct KeywordInfo {
/// The keyword used
pub kw: specified::KeywordSize,
/// A factor to be multiplied by the computed size of the keyword
pub factor: f32,
/// An additional Au offset to add to the kw*factor in the case of calcs
pub offset: NonNegativeLength,
}
impl KeywordInfo {
/// Computes the final size for this font-size keyword, accounting for
/// text-zoom.
pub fn to_computed_value(&self, context: &Context) -> NonNegativeLength {
let base = context.maybe_zoom_text(self.kw.to_computed_value(context));
base.scale_by(self.factor) + context.maybe_zoom_text(self.offset)
}
/// Given a parent keyword info (self), apply an additional factor/offset to it
pub fn compose(self, factor: f32, offset: NonNegativeLength) -> Self {
KeywordInfo {
kw: self.kw,
factor: self.factor * factor,
offset: self.offset.scale_by(factor) + offset,
}
}
/// KeywordInfo value for font-size: medium
pub fn medium() -> Self {
specified::KeywordSize::Medium.into()
}
}
impl From<specified::KeywordSize> for KeywordInfo {
fn from(x: specified::KeywordSize) -> Self {
KeywordInfo {
kw: x,
factor: 1.,
offset: Au(0).into(),
}
}
}
/// Additional information for computed keyword-derived font sizes.
pub type KeywordInfo = GenericKeywordInfo<NonNegativeLength>;
impl FontWeight {
/// Value for normal

View file

@ -815,6 +815,20 @@ pub type LengthOrNormal = Either<Length, Normal>;
/// A wrapper of Length, whose value must be >= 0.
pub type NonNegativeLength = NonNegative<Length>;
impl ToAnimatedValue for NonNegativeLength {
type AnimatedValue = Length;
#[inline]
fn to_animated_value(self) -> Self::AnimatedValue {
self.0
}
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
NonNegativeLength::new(animated.px().max(0.))
}
}
impl NonNegativeLength {
/// Create a NonNegativeLength.
#[inline]

View file

@ -43,7 +43,7 @@ impl<L> BorderCornerRadius<L> {
/// A generic value for the `border-spacing` property.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf)]
#[derive(PartialEq, ToAnimatedValue, ToComputedValue, ToCss)]
#[derive(PartialEq, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)]
pub struct BorderSpacing<L>(pub Size<L>);
impl<L> BorderSpacing<L> {

View file

@ -4,13 +4,15 @@
//! Generic types for font stuff.
use app_units::Au;
use byteorder::{ReadBytesExt, BigEndian};
use cssparser::Parser;
use num_traits::One;
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, ToCss};
use std::io::Cursor;
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::distance::{ComputeSquaredDistance, SquaredDistance};
use values::specified::font::FontTag;
/// https://drafts.csswg.org/css-fonts-4/#feature-tag-value
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue)]
@ -117,3 +119,144 @@ impl<T: ToCss> ToCss for FontSettings<T> {
Ok(())
}
}
/// A font four-character tag, represented as a u32 for convenience.
///
/// See:
/// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def
/// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings
///
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct FontTag(pub u32);
impl ToCss for FontTag {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
use byteorder::{BigEndian, ByteOrder};
use std::str;
let mut raw = [0u8; 4];
BigEndian::write_u32(&mut raw, self.0);
str::from_utf8(&raw).unwrap_or_default().to_css(dest)
}
}
impl Parse for FontTag {
fn parse<'i, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let location = input.current_source_location();
let tag = input.expect_string()?;
// allowed strings of length 4 containing chars: <U+20, U+7E>
if tag.len() != 4 || tag.as_bytes().iter().any(|c| *c < b' ' || *c > b'~') {
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
let mut raw = Cursor::new(tag.as_bytes());
Ok(FontTag(raw.read_u32::<BigEndian>().unwrap()))
}
}
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf)]
#[derive(PartialEq, ToAnimatedValue, ToAnimatedZero)]
/// Additional information for keyword-derived font sizes.
pub struct KeywordInfo<Length> {
/// The keyword used
pub kw: KeywordSize,
/// A factor to be multiplied by the computed size of the keyword
pub factor: f32,
/// An additional Au offset to add to the kw*factor in the case of calcs
pub offset: Length,
}
impl<L> KeywordInfo<L>
where
Au: Into<L>,
{
/// KeywordInfo value for font-size: medium
pub fn medium() -> Self {
KeywordSize::Medium.into()
}
}
impl<L> From<KeywordSize> for KeywordInfo<L>
where
Au: Into<L>,
{
fn from(x: KeywordSize) -> Self {
KeywordInfo {
kw: x,
factor: 1.,
offset: Au(0).into(),
}
}
}
/// CSS font keywords
#[derive(Animate, ComputeSquaredDistance, MallocSizeOf, ToAnimatedValue, ToAnimatedZero)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[allow(missing_docs)]
pub enum KeywordSize {
XXSmall = 1, // This is to enable the NonZero optimization
// which simplifies the representation of Option<KeywordSize>
// in bindgen
XSmall,
Small,
Medium,
Large,
XLarge,
XXLarge,
// This is not a real font keyword and will not parse
// HTML font-size 7 corresponds to this value
XXXLarge,
}
impl KeywordSize {
/// Convert to an HTML <font size> value
pub fn html_size(&self) -> u8 {
match *self {
KeywordSize::XXSmall => 0,
KeywordSize::XSmall => 1,
KeywordSize::Small => 2,
KeywordSize::Medium => 3,
KeywordSize::Large => 4,
KeywordSize::XLarge => 5,
KeywordSize::XXLarge => 6,
KeywordSize::XXXLarge => 7,
}
}
}
impl Default for KeywordSize {
fn default() -> Self {
KeywordSize::Medium
}
}
impl ToCss for KeywordSize {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str(match *self {
KeywordSize::XXSmall => "xx-small",
KeywordSize::XSmall => "x-small",
KeywordSize::Small => "small",
KeywordSize::Medium => "medium",
KeywordSize::Large => "large",
KeywordSize::XLarge => "x-large",
KeywordSize::XXLarge => "xx-large",
KeywordSize::XXXLarge => {
debug_assert!(
false,
"We should never serialize specified values set via HTML presentation attributes"
);
"-servo-xxx-large"
},
})
}
}

View file

@ -14,7 +14,7 @@ use values::animated::ToAnimatedValue;
/// A generic size, for `border-*-radius` longhand properties, or
/// `border-spacing`.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug)]
#[derive(MallocSizeOf, PartialEq, ToComputedValue)]
#[derive(MallocSizeOf, PartialEq, ToAnimatedZero, ToComputedValue)]
pub struct Size<L>(pub Size2D<L>);
impl<L> Size<L> {

View file

@ -21,7 +21,8 @@ use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use values::CustomIdent;
use values::computed::{font as computed, Context, Length, NonNegativeLength, ToComputedValue};
use values::computed::font::{SingleFontFamily, FontFamilyList, FamilyName};
use values::generics::font::{FontSettings, FeatureTagValue, VariationValue};
use values::generics::font::{FontSettings, FontTag, FeatureTagValue};
use values::generics::font::{KeywordInfo as GenericKeywordInfo, KeywordSize, VariationValue};
use values::specified::{AllowQuirks, Integer, LengthOrPercentage, NoCalcLength, Number};
use values::specified::length::{AU_PER_PT, AU_PER_PX, FontBaseSize};
@ -134,7 +135,7 @@ pub enum FontSize {
/// go into the ratio, and the remaining units all computed together
/// will go into the offset.
/// See bug 1355707.
Keyword(computed::KeywordInfo),
Keyword(KeywordInfo),
/// font-size: smaller
Smaller,
/// font-size: larger
@ -340,27 +341,29 @@ impl Parse for FontSizeAdjust {
}
}
/// CSS font keywords
#[derive(Animate, ComputeSquaredDistance, MallocSizeOf, ToAnimatedValue, ToAnimatedZero)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[allow(missing_docs)]
pub enum KeywordSize {
XXSmall = 1, // This is to enable the NonZero optimization
// which simplifies the representation of Option<KeywordSize>
// in bindgen
XSmall,
Small,
Medium,
Large,
XLarge,
XXLarge,
// This is not a real font keyword and will not parse
// HTML font-size 7 corresponds to this value
XXXLarge,
/// Additional information for specified keyword-derived font sizes.
pub type KeywordInfo = GenericKeywordInfo<NonNegativeLength>;
impl KeywordInfo {
/// Computes the final size for this font-size keyword, accounting for
/// text-zoom.
pub fn to_computed_value(&self, context: &Context) -> NonNegativeLength {
let base = context.maybe_zoom_text(self.kw.to_computed_value(context));
base.scale_by(self.factor) + context.maybe_zoom_text(self.offset)
}
/// Given a parent keyword info (self), apply an additional factor/offset to it
pub fn compose(self, factor: f32, offset: NonNegativeLength) -> Self {
KeywordInfo {
kw: self.kw,
factor: self.factor * factor,
offset: self.offset.scale_by(factor) + offset,
}
}
}
impl KeywordSize {
/// Parse a keyword size
/// Parses a keyword size.
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
try_match_ident_ignore_ascii_case! { input,
"xx-small" => Ok(KeywordSize::XXSmall),
@ -372,46 +375,6 @@ impl KeywordSize {
"xx-large" => Ok(KeywordSize::XXLarge),
}
}
/// Convert to an HTML <font size> value
pub fn html_size(&self) -> u8 {
match *self {
KeywordSize::XXSmall => 0,
KeywordSize::XSmall => 1,
KeywordSize::Small => 2,
KeywordSize::Medium => 3,
KeywordSize::Large => 4,
KeywordSize::XLarge => 5,
KeywordSize::XXLarge => 6,
KeywordSize::XXXLarge => 7,
}
}
}
impl Default for KeywordSize {
fn default() -> Self {
KeywordSize::Medium
}
}
impl ToCss for KeywordSize {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str(match *self {
KeywordSize::XXSmall => "xx-small",
KeywordSize::XSmall => "x-small",
KeywordSize::Small => "small",
KeywordSize::Medium => "medium",
KeywordSize::Large => "large",
KeywordSize::XLarge => "x-large",
KeywordSize::XXLarge => "xx-large",
KeywordSize::XXXLarge => unreachable!("We should never serialize \
specified values set via
HTML presentation attributes"),
})
}
}
/// This is the ratio applied for font-size: larger
@ -672,7 +635,7 @@ impl FontSize {
#[inline]
/// Get initial value for specified font size.
pub fn medium() -> Self {
FontSize::Keyword(computed::KeywordInfo::medium())
FontSize::Keyword(KeywordInfo::medium())
}
/// Parses a font-size, with quirks.
@ -1945,50 +1908,6 @@ impl Parse for FontLanguageOverride {
}
}
/// A font four-character tag, represented as a u32 for convenience.
///
/// See:
/// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def
/// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings
///
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct FontTag(pub u32);
impl Parse for FontTag {
fn parse<'i, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
use byteorder::{ReadBytesExt, BigEndian};
use std::io::Cursor;
let location = input.current_source_location();
let tag = input.expect_string()?;
// allowed strings of length 4 containing chars: <U+20, U+7E>
if tag.len() != 4 || tag.as_bytes().iter().any(|c| *c < b' ' || *c > b'~') {
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
let mut raw = Cursor::new(tag.as_bytes());
Ok(FontTag(raw.read_u32::<BigEndian>().unwrap()))
}
}
impl ToCss for FontTag {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
use byteorder::{BigEndian, ByteOrder};
use std::str;
let mut raw = [0u8; 4];
BigEndian::write_u32(&mut raw, self.0);
str::from_utf8(&raw).unwrap_or_default().to_css(dest)
}
}
/// This property provides low-level control over OpenType or TrueType font
/// variations.
pub type FontVariationSettings = FontSettings<VariationValue<Number>>;