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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! The `@font-face` rule.

use super::Location;
use crate::error::{ParserError, PrinterError};
use crate::macros::enum_property;
use crate::printer::Printer;
use crate::properties::custom::CustomProperty;
use crate::properties::font::{FontFamily, FontStretch, FontStyle, FontWeight};
use crate::traits::{Parse, ToCss};
use crate::values::size::Size2D;
use crate::values::string::CowArcStr;
use crate::values::url::Url;
use cssparser::*;
use std::fmt::Write;

/// A [@font-face](https://drafts.csswg.org/css-fonts/#font-face-rule) rule.
#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FontFaceRule<'i> {
  /// Declarations in the `@font-face` rule.
  #[cfg_attr(feature = "serde", serde(borrow))]
  pub properties: Vec<FontFaceProperty<'i>>,
  /// The location of the rule in the source file.
  pub loc: Location,
}

/// A property within an `@font-face` rule.
///
/// See [FontFaceRule](FontFaceRule).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum FontFaceProperty<'i> {
  /// The `src` property.
  #[cfg_attr(feature = "serde", serde(borrow))]
  Source(Vec<Source<'i>>),
  /// The `font-family` property.
  FontFamily(FontFamily<'i>),
  /// The `font-style` property.
  FontStyle(FontStyle),
  /// The `font-weight` property.
  FontWeight(Size2D<FontWeight>),
  /// The `font-stretch` property.
  FontStretch(Size2D<FontStretch>),
  /// The `unicode-range` property.
  UnicodeRange(Vec<UnicodeRange>),
  /// An unknown or unsupported property.
  Custom(CustomProperty<'i>),
}

/// A value for the [src](https://drafts.csswg.org/css-fonts/#src-desc)
/// property in an `@font-face` rule.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum Source<'i> {
  /// A `url()` with optional format metadata.
  Url(UrlSource<'i>),
  /// The `local()` function.
  #[cfg_attr(feature = "serde", serde(borrow))]
  Local(FontFamily<'i>),
}

impl<'i> Parse<'i> for Source<'i> {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    match input.try_parse(UrlSource::parse) {
      Ok(url) => return Ok(Source::Url(url)),
      e @ Err(ParseError {
        kind: ParseErrorKind::Basic(BasicParseErrorKind::AtRuleBodyInvalid),
        ..
      }) => {
        return Err(e.err().unwrap());
      }
      _ => {}
    }

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

impl<'i> ToCss for Source<'i> {
  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(')')
      }
    }
  }
}

/// A `url()` value for the [src](https://drafts.csswg.org/css-fonts/#src-desc)
/// property in an `@font-face` rule.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UrlSource<'i> {
  /// The URL.
  pub url: Url<'i>,
  /// Optional `format()` function.
  #[cfg_attr(feature = "serde", serde(borrow))]
  pub format: Option<FontFormat<'i>>,
  /// Optional `tech()` function.
  pub tech: Vec<FontTechnology>,
}

impl<'i> Parse<'i> for UrlSource<'i> {
  fn parse<'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(FontFormat::parse)?)
    } else {
      None
    };

    let tech = if input.try_parse(|input| input.expect_function_matching("tech")).is_ok() {
      input.parse_nested_block(Vec::<FontTechnology>::parse)?
    } else {
      vec![]
    };

    Ok(UrlSource { url, format, tech })
  }
}

impl<'i> ToCss for UrlSource<'i> {
  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(')')?;
    }

    if !self.tech.is_empty() {
      dest.whitespace()?;
      dest.write_str("tech(")?;
      self.tech.to_css(dest)?;
      dest.write_char(')')?;
    }
    Ok(())
  }
}

/// A font format keyword in the `format()` function of the the
/// [src](https://drafts.csswg.org/css-fonts/#src-desc)
/// property of an `@font-face` rule.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum FontFormat<'i> {
  /// [src](https://drafts.csswg.org/css-fonts/#font-format-definitions)
  /// A WOFF 1.0 font.
  WOFF,
  /// A WOFF 2.0 font.
  WOFF2,
  /// A TrueType font.
  TrueType,
  /// An OpenType font.
  OpenType,
  /// An Embedded OpenType (.eot) font.
  EmbeddedOpenType,
  /// OpenType Collection.
  Collection,
  /// An SVG font.
  SVG,
  /// An unknown format.
  #[cfg_attr(feature = "serde", serde(borrow))]
  String(CowArcStr<'i>),
}

impl<'i> Parse<'i> for FontFormat<'i> {
  fn parse<'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.into()))
    }
  }
}

impl<'i> ToCss for FontFormat<'i> {
  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! {
  /// A font format keyword in the `format()` function of the the
  /// [src](https://drafts.csswg.org/css-fonts/#src-desc)
  /// property of an `@font-face` rule.
  pub enum FontTechnology {
    /// A font feature tech descriptor in the `tech()`function of the
    /// [src](https://drafts.csswg.org/css-fonts/#font-feature-tech-values)
    /// property of an `@font-face` rule.
    /// Supports OpenType Features.
    /// https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
    "feature-opentype": FeatureOpentype,
    /// Supports Apple Advanced Typography Font Features.
    /// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html
    "feature-aat": FeatureAat,
    /// Supports Graphite Table Format.
    /// https://scripts.sil.org/cms/scripts/render_download.php?site_id=nrsi&format=file&media_id=GraphiteBinaryFormat_3_0&filename=GraphiteBinaryFormat_3_0.pdf
    "feature-graphite": FeatureGraphite,

    /// A color font tech descriptor in the `tech()`function of the
    /// [src](https://drafts.csswg.org/css-fonts/#src-desc)
    /// property of an `@font-face` rule.
    /// Supports the `COLR` v0 table.
    "color-colrv0": ColorCOLRv0,
    /// Supports the `COLR` v1 table.
    "color-colrv1": ColorCOLRv1,
    /// Supports the `SVG` table.
    "color-svg": ColorSVG,
    /// Supports the `sbix` table.
    "color-sbix": ColorSbix,
    /// Supports the `CBDT` table.
    "color-cbdt": ColorCBDT,

    /// Supports Variations
    /// The variations tech refers to the support of font variations
    "variations": Variations,
    /// Supports Palettes
    /// The palettes tech refers to support for font palettes
    "palettes": Palettes,
    /// Supports Incremental
    /// The incremental tech refers to client support for incremental font loading, using either the range-request or the patch-subset method
    "incremental": Incremental,
  }
}

/// A contiguous range of Unicode code points.
///
/// Cannot be empty. Can represent a single code point when start == end.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UnicodeRange {
  /// Inclusive start of the range. In [0, end].
  pub start: u32,
  /// Inclusive end of the range. In [0, 0x10FFFF].
  pub end: u32,
}

impl<'i> Parse<'i> for UnicodeRange {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    let range = cssparser::UnicodeRange::parse(input)?;
    Ok(UnicodeRange {
      start: range.start,
      end: range.end,
    })
  }
}

impl ToCss for UnicodeRange {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    // Attempt to optimize the range to use question mark syntax.
    if self.start != self.end {
      // Find the first hex digit that differs between the start and end values.
      let mut shift = 24;
      let mut mask = 0xf << shift;
      while shift > 0 {
        let c1 = self.start & mask;
        let c2 = self.end & mask;
        if c1 != c2 {
          break;
        }

        mask = mask >> 4;
        shift -= 4;
      }

      // Get the remainder of the value. This must be 0x0 to 0xf for the rest
      // of the value to use the question mark syntax.
      shift += 4;
      let remainder_mask = (1 << shift) - 1;
      let start_remainder = self.start & remainder_mask;
      let end_remainder = self.end & remainder_mask;

      if start_remainder == 0 && end_remainder == remainder_mask {
        let start = (self.start & !remainder_mask) >> shift;
        if start != 0 {
          write!(dest, "U+{:X}", start)?;
        } else {
          dest.write_str("U+")?;
        }

        while shift > 0 {
          dest.write_char('?')?;
          shift -= 4;
        }

        return Ok(());
      }
    }

    write!(dest, "U+{:X}", self.start)?;
    if self.end != self.start {
      write!(dest, "-{:X}", self.end)?;
    }
    Ok(())
  }
}

pub(crate) struct FontFaceDeclarationParser;

/// Parse a declaration within {} block: `color: blue`
impl<'i> cssparser::DeclarationParser<'i> for FontFaceDeclarationParser {
  type Declaration = FontFaceProperty<'i>;
  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>),
      "unicode-range" => property!(UnicodeRange, Vec<UnicodeRange>),
      _ => {}
    }

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

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

impl<'i> ToCss for FontFaceRule<'i> {
  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<'i> ToCss for FontFaceProperty<'i> {
  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),
      UnicodeRange(value) => property!("unicode-range", value),
      Custom(custom) => {
        dest.write_str(custom.name.as_ref())?;
        dest.delim(':', false)?;
        custom.value.to_css(dest, true)
      }
    }
  }
}