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
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;

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

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

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

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

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

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(Format::parse)?)
    } else {
      None
    };

    Ok(UrlSource { url, format })
  }
}

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(')')?;
    }
    Ok(())
  }
}

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

impl<'i> Parse<'i> for Format<'i> {
  fn parse<'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<'i> ToCss for Format<'i> {
  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<'i> {
  WOFF,
  WOFF2,
  TrueType,
  OpenType,
  EmbeddedOpenType,
  Collection,
  SVG,
  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! {
  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<'i> Parse<'i> for FontTechnology {
  fn parse<'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"),
    }
  }
}

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

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(());
      }
    }

    cssparser::ToCss::to_css(self, dest)?;
    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, input)?));
  }
}

/// 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)
      }
    }
  }
}