1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
use cssparser::*;
use crate::traits::{Parse, ToCss};
use crate::printer::Printer;
use crate::properties::font::{FontFamily, FontStyle, FontWeight, FontStretch};
use crate::values::size::Size2D;
use crate::properties::custom::CustomProperty;
use crate::macros::enum_property;
use crate::values::url::Url;
use crate::error::{ParserError, PrinterError};

#[derive(Debug, PartialEq)]
pub struct FontFaceRule {
  pub properties: Vec<FontFaceProperty>,
  pub loc: SourceLocation
}

#[derive(Debug, Clone, PartialEq)]
pub enum FontFaceProperty {
  Source(Vec<Source>),
  FontFamily(FontFamily),
  FontStyle(FontStyle),
  FontWeight(Size2D<FontWeight>),
  FontStretch(Size2D<FontStretch>),
  Custom(CustomProperty)
}

/// https://www.w3.org/TR/2021/WD-css-fonts-4-20210729/#font-face-src-parsing
#[derive(Debug, Clone, PartialEq)]
pub enum Source {
  Url(UrlSource),
  Local(FontFamily)
}

impl Parse for Source {
  fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    if let Ok(url) = input.try_parse(UrlSource::parse) {
      return Ok(Source::Url(url))
    }

    input.expect_function_matching("local")?;
    let local = input.parse_nested_block(FontFamily::parse)?;
    Ok(Source::Local(local))
  }
}

impl ToCss for Source {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
    match self {
      Source::Url(url) => url.to_css(dest),
      Source::Local(local) => {
        dest.write_str("local(")?;
        local.to_css(dest)?;
        dest.write_char(')')
      }
    }
  }
}

#[derive(Debug, Clone, PartialEq)]
pub struct UrlSource {
  pub url: Url,
  pub format: Option<Format>
}

impl Parse for UrlSource {
  fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    let url = Url::parse(input)?;

    let format = if input.try_parse(|input| input.expect_function_matching("format")).is_ok() {
      Some(input.parse_nested_block(Format::parse)?)
    } else {
      None
    };

    Ok(UrlSource { url, format })
  }
}

impl ToCss for UrlSource {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
    self.url.to_css(dest)?;
    if let Some(format) = &self.format {
      dest.whitespace()?;
      dest.write_str("format(")?;
      format.to_css(dest)?;
      dest.write_char(')')?;
    }
    Ok(())
  }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Format {
  pub format: FontFormat,
  pub supports: Vec<FontTechnology>
}

impl Parse for Format {
  fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    let format = FontFormat::parse(input)?;
    let mut supports = vec![];
    if input.try_parse(|input| input.expect_ident_matching("supports")).is_ok() {
      loop {
        if let Ok(technology) = input.try_parse(FontTechnology::parse) {
          supports.push(technology)
        } else {
          break
        }
      }
    }
    Ok(Format { format, supports })
  }
}


impl ToCss for Format {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
    self.format.to_css(dest)?;
    if !self.supports.is_empty() {
      dest.write_str(" supports ")?;
      let mut first = true;
      for technology in &self.supports {
        if first {
          first = false;
        } else {
          dest.write_char(' ')?;
        }
        technology.to_css(dest)?;
      }
    }
    Ok(())
  }
}

#[derive(Debug, Clone, PartialEq)]
pub enum FontFormat {
  WOFF,
  WOFF2,
  TrueType,
  OpenType,
  EmbeddedOpenType,
  Collection,
  SVG,
  String(String)
}

impl Parse for FontFormat {
  fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    let s = input.expect_ident_or_string()?;
    match_ignore_ascii_case! { &s,
      "woff" => Ok(FontFormat::WOFF),
      "woff2" => Ok(FontFormat::WOFF2),
      "truetype" => Ok(FontFormat::TrueType),
      "opentype" => Ok(FontFormat::OpenType),
      "embedded-opentype" => Ok(FontFormat::EmbeddedOpenType),
      "collection" => Ok(FontFormat::Collection),
      "svg" => Ok(FontFormat::SVG),
      _ => Ok(FontFormat::String(s.as_ref().to_owned()))
    }
  }
}

impl ToCss for FontFormat {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
    use FontFormat::*;
    let s = match self {
      WOFF => "woff",
      WOFF2 => "woff2",
      TrueType => "truetype",
      OpenType => "opentype",
      EmbeddedOpenType => "embedded-opentype",
      Collection => "collection",
      SVG => "svg",
      String(s) => &s
    };
    // Browser support for keywords rather than strings is very limited.
    // https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src
    serialize_string(&s, dest)?;
    Ok(())
  }
}

enum_property! {
  pub enum FontFeatureTechnology {
    OpenType,
    AAT,
    Graphite,
  }
}

enum_property! {
  pub enum ColorFontTechnology {
    COLRv0,
    COLRv1,
    SVG,
    SBIX,
    CBDT,
  }
}

#[derive(Debug, Clone, PartialEq)]
pub enum FontTechnology {
  Features(FontFeatureTechnology),
  Variations,
  Color(ColorFontTechnology),
  Palettes
}

impl Parse for FontTechnology {
  fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    let location = input.current_source_location();
    match input.next()? {
      Token::Function(f) => {
        match_ignore_ascii_case! { &f,
          "features" => Ok(FontTechnology::Features(input.parse_nested_block(FontFeatureTechnology::parse)?)),
          "color" => Ok(FontTechnology::Color(input.parse_nested_block(ColorFontTechnology::parse)?)),
          _ => Err(location.new_unexpected_token_error(
            cssparser::Token::Ident(f.clone())
          ))
        }
      }
      Token::Ident(ident) => {
        match_ignore_ascii_case! { &ident,
          "variations" => Ok(FontTechnology::Variations),
          "palettes" => Ok(FontTechnology::Palettes),
          _ => Err(location.new_unexpected_token_error(
            cssparser::Token::Ident(ident.clone())
          ))
        }
      }
      tok => Err(location.new_unexpected_token_error(tok.clone()))
    }
  }
}

impl ToCss for FontTechnology {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
    match self {
      FontTechnology::Features(f) => {
        dest.write_str("features(")?;
        f.to_css(dest)?;
        dest.write_char(')')
      }
      FontTechnology::Color(c) => {
        dest.write_str("color(")?;
        c.to_css(dest)?;
        dest.write_char(')')
      }
      FontTechnology::Variations => dest.write_str("variations"),
      FontTechnology::Palettes => dest.write_str("palettes")
    }
  }
}

pub(crate) struct FontFaceDeclarationParser;

/// Parse a declaration within {} block: `color: blue`
impl<'i> cssparser::DeclarationParser<'i> for FontFaceDeclarationParser {
  type Declaration = FontFaceProperty;
  type Error = ParserError<'i>;

  fn parse_value<'t>(
      &mut self,
      name: CowRcStr<'i>,
      input: &mut cssparser::Parser<'i, 't>,
  ) -> Result<Self::Declaration, cssparser::ParseError<'i, Self::Error>> {
    macro_rules! property {
      ($property: ident, $type: ty) => {
        if let Ok(c) = <$type>::parse(input) {
          return Ok(FontFaceProperty::$property(c))
        }
      };
    }

    let state = input.state();
    match_ignore_ascii_case! { &name,
      "src" => {
        if let Ok(sources) = input.parse_comma_separated(Source::parse) {
          return Ok(FontFaceProperty::Source(sources))
        }
      },
      "font-family" => property!(FontFamily, FontFamily),
      "font-weight" => property!(FontWeight, Size2D<FontWeight>),
      "font-style" => property!(FontStyle, FontStyle),
      "font-stretch" => property!(FontStretch, Size2D<FontStretch>),
      _ => {}
    }

    input.reset(&state);
    return Ok(FontFaceProperty::Custom(CustomProperty::parse(name, input)?))
  }
}

/// Default methods reject all at rules.
impl<'i> AtRuleParser<'i> for FontFaceDeclarationParser {
  type Prelude = ();
  type AtRule = FontFaceProperty;
  type Error = ParserError<'i>;
}

impl ToCss for FontFaceRule {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
    dest.add_mapping(self.loc);
    dest.write_str("@font-face")?;
    dest.whitespace()?;
    dest.write_char('{')?;
    dest.indent();
    let len = self.properties.len();
    for (i, prop) in self.properties.iter().enumerate() {
      dest.newline()?;
      prop.to_css(dest)?;
      if i != len - 1 || !dest.minify {
        dest.write_char(';')?;
      }
    }
    dest.dedent();
    dest.newline()?;
    dest.write_char('}')
  }
}

impl ToCss for FontFaceProperty {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
    use FontFaceProperty::*;
    macro_rules! property {
      ($prop: literal, $value: expr) => {{
        dest.write_str($prop)?;
        dest.delim(':', false)?;
        $value.to_css(dest)
      }};
      ($prop: literal, $value: expr, $multi: expr) => {{
        dest.write_str($prop)?;
        dest.delim(':', false)?;
        let len = $value.len();
        for (idx, val) in $value.iter().enumerate() {
          val.to_css(dest)?;
          if idx < len - 1 {
            dest.delim(',', false)?;
          }
        }
        Ok(())
      }};
    }

    match self {
      Source(value) => property!("src", value, true),
      FontFamily(value) => property!("font-family", value),
      FontStyle(value) => property!("font-style", value),
      FontWeight(value) => property!("font-weight", value),
      FontStretch(value) => property!("font-stretch", value),
      Custom(custom) => {
        dest.write_str(custom.name.as_ref())?;
        dest.delim(':', false)?;
        dest.write_str(custom.value.as_ref())
      }
    }
  }
}