/
font.mako.rs
2255 lines (2002 loc) · 90.6 KB
/
font.mako.rs
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method, to_camel_case, to_rust_ident, to_camel_case_lower, SYSTEM_FONT_LONGHANDS %>
<% data.new_style_struct("Font", inherited=True) %>
<%def name="nongecko_unreachable()">
%if product == "gecko":
${caller.body()}
%else:
unreachable!()
%endif
</%def>
#[cfg(feature = "gecko")]
macro_rules! impl_gecko_keyword_conversions {
($name: ident, $utype: ty) => {
impl From<$utype> for $name {
fn from(bits: $utype) -> $name {
$name::from_gecko_keyword(bits)
}
}
impl From<$name> for $utype {
fn from(v: $name) -> $utype {
v.to_gecko_keyword()
}
}
};
}
// Define ToComputedValue, ToCss, and other boilerplate for a specified value
// which is of the form `enum SpecifiedValue {Value(..), System(SystemFont)}`
<%def name="simple_system_boilerplate(name)">
impl SpecifiedValue {
pub fn system_font(f: SystemFont) -> Self {
SpecifiedValue::System(f)
}
pub fn get_system(&self) -> Option<SystemFont> {
if let SpecifiedValue::System(s) = *self {
Some(s)
} else {
None
}
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
fn to_computed_value(&self, _context: &Context) -> computed_value::T {
match *self {
SpecifiedValue::Value(ref v) => v.clone(),
SpecifiedValue::System(_) => {
<%self:nongecko_unreachable>
_context.cached_system_font.as_ref().unwrap().${name}.clone()
</%self:nongecko_unreachable>
}
}
}
fn from_computed_value(other: &computed_value::T) -> Self {
SpecifiedValue::Value(other.clone())
}
}
</%def>
<%helpers:longhand name="font-family" animation_value_type="discrete"
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER"
spec="https://drafts.csswg.org/css-fonts/#propdef-font-family">
#[cfg(feature = "gecko")] use gecko_bindings::bindings;
#[cfg(feature = "gecko")] use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use properties::longhands::system_font::SystemFont;
use self::computed_value::{FontFamily, FontFamilyList, FamilyName};
use std::fmt;
use style_traits::ToCss;
pub mod computed_value {
use cssparser::{CssStringWriter, Parser, serialize_identifier};
#[cfg(feature = "gecko")] use gecko_bindings::{bindings, structs};
#[cfg(feature = "gecko")] use gecko_bindings::sugar::refptr::RefPtr;
#[cfg(feature = "gecko")] use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use std::fmt::{self, Write};
#[cfg(feature = "gecko")] use std::hash::{Hash, Hasher};
#[cfg(feature = "servo")] use std::slice;
use style_traits::{ToCss, ParseError};
use Atom;
pub use self::FontFamily as SingleComputedValue;
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub enum FontFamily {
FamilyName(FamilyName),
Generic(Atom),
}
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct FamilyName {
pub name: Atom,
pub syntax: FamilyNameSyntax,
}
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub enum FamilyNameSyntax {
/// The family name was specified in a quoted form, e.g. "Font Name"
/// or 'Font Name'.
Quoted,
/// The family name was specified in an unquoted form as a sequence of
/// identifiers. The `String` is the serialization of the sequence of
/// identifiers.
Identifiers(String),
}
impl FontFamily {
#[inline]
pub fn atom(&self) -> &Atom {
match *self {
FontFamily::FamilyName(ref family_name) => &family_name.name,
FontFamily::Generic(ref name) => name,
}
}
#[inline]
#[cfg(not(feature = "gecko"))] // Gecko can't borrow atoms as UTF-8.
pub fn name(&self) -> &str {
self.atom()
}
#[cfg(not(feature = "gecko"))] // Gecko can't borrow atoms as UTF-8.
pub fn from_atom(input: Atom) -> FontFamily {
match input {
atom!("serif") |
atom!("sans-serif") |
atom!("cursive") |
atom!("fantasy") |
atom!("monospace") => {
return FontFamily::Generic(input)
}
_ => {}
}
match_ignore_ascii_case! { &input,
"serif" => return FontFamily::Generic(atom!("serif")),
"sans-serif" => return FontFamily::Generic(atom!("sans-serif")),
"cursive" => return FontFamily::Generic(atom!("cursive")),
"fantasy" => return FontFamily::Generic(atom!("fantasy")),
"monospace" => return FontFamily::Generic(atom!("monospace")),
_ => {}
}
// We don't know if it's quoted or not. So we set it to
// quoted by default.
FontFamily::FamilyName(FamilyName {
name: input,
syntax: FamilyNameSyntax::Quoted,
})
}
/// Parse a font-family value
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
if let Ok(value) = input.try(|i| i.expect_string_cloned()) {
return Ok(FontFamily::FamilyName(FamilyName {
name: Atom::from(&*value),
syntax: FamilyNameSyntax::Quoted,
}))
}
let first_ident = input.expect_ident()?.clone();
// FIXME(bholley): The fast thing to do here would be to look up the
// string (as lowercase) in the static atoms table. We don't have an
// API to do that yet though, so we do the simple thing for now.
let mut css_wide_keyword = false;
match_ignore_ascii_case! { &first_ident,
"serif" => return Ok(FontFamily::Generic(atom!("serif"))),
"sans-serif" => return Ok(FontFamily::Generic(atom!("sans-serif"))),
"cursive" => return Ok(FontFamily::Generic(atom!("cursive"))),
"fantasy" => return Ok(FontFamily::Generic(atom!("fantasy"))),
"monospace" => return Ok(FontFamily::Generic(atom!("monospace"))),
% if product == "gecko":
"-moz-fixed" => return Ok(FontFamily::Generic(atom!("-moz-fixed"))),
% endif
// https://drafts.csswg.org/css-fonts/#propdef-font-family
// "Font family names that happen to be the same as a keyword value
// (`inherit`, `serif`, `sans-serif`, `monospace`, `fantasy`, and `cursive`)
// must be quoted to prevent confusion with the keywords with the same names.
// The keywords ‘initial’ and ‘default’ are reserved for future use
// and must also be quoted when used as font names.
// UAs must not consider these keywords as matching the <family-name> type."
"inherit" => css_wide_keyword = true,
"initial" => css_wide_keyword = true,
"unset" => css_wide_keyword = true,
"default" => css_wide_keyword = true,
_ => {}
}
let mut value = first_ident.as_ref().to_owned();
let mut serialization = String::new();
serialize_identifier(&first_ident, &mut serialization).unwrap();
// These keywords are not allowed by themselves.
// The only way this value can be valid with with another keyword.
if css_wide_keyword {
let ident = input.expect_ident()?;
value.push(' ');
value.push_str(&ident);
serialization.push(' ');
serialize_identifier(&ident, &mut serialization).unwrap();
}
while let Ok(ident) = input.try(|i| i.expect_ident_cloned()) {
value.push(' ');
value.push_str(&ident);
serialization.push(' ');
serialize_identifier(&ident, &mut serialization).unwrap();
}
Ok(FontFamily::FamilyName(FamilyName {
name: Atom::from(value),
syntax: FamilyNameSyntax::Identifiers(serialization),
}))
}
#[cfg(feature = "gecko")]
/// Return the generic ID for a given generic font name
pub fn generic(name: &Atom) -> (structs::FontFamilyType, u8) {
use gecko_bindings::structs::FontFamilyType;
if *name == atom!("serif") {
(FontFamilyType::eFamily_serif,
structs::kGenericFont_serif)
} else if *name == atom!("sans-serif") {
(FontFamilyType::eFamily_sans_serif,
structs::kGenericFont_sans_serif)
} else if *name == atom!("cursive") {
(FontFamilyType::eFamily_cursive,
structs::kGenericFont_cursive)
} else if *name == atom!("fantasy") {
(FontFamilyType::eFamily_fantasy,
structs::kGenericFont_fantasy)
} else if *name == atom!("monospace") {
(FontFamilyType::eFamily_monospace,
structs::kGenericFont_monospace)
} else if *name == atom!("-moz-fixed") {
(FontFamilyType::eFamily_moz_fixed,
structs::kGenericFont_moz_fixed)
} else {
panic!("Unknown generic {}", name);
}
}
#[cfg(feature = "gecko")]
fn from_font_family_name(family: &structs::FontFamilyName) -> FontFamily {
use gecko_bindings::structs::FontFamilyType;
match family.mType {
FontFamilyType::eFamily_serif => FontFamily::Generic(atom!("serif")),
FontFamilyType::eFamily_sans_serif => FontFamily::Generic(atom!("sans-serif")),
FontFamilyType::eFamily_monospace => FontFamily::Generic(atom!("monospace")),
FontFamilyType::eFamily_cursive => FontFamily::Generic(atom!("cursive")),
FontFamilyType::eFamily_fantasy => FontFamily::Generic(atom!("fantasy")),
FontFamilyType::eFamily_moz_fixed => FontFamily::Generic(Atom::from("-moz-fixed")),
FontFamilyType::eFamily_named => {
let name = Atom::from(&*family.mName);
let mut serialization = String::new();
serialize_identifier(&name.to_string(), &mut serialization).unwrap();
FontFamily::FamilyName(FamilyName {
name: name.clone(),
syntax: FamilyNameSyntax::Identifiers(serialization),
})
},
FontFamilyType::eFamily_named_quoted => FontFamily::FamilyName(FamilyName {
name: (&*family.mName).into(),
syntax: FamilyNameSyntax::Quoted,
}),
x => panic!("Found unexpected font FontFamilyType: {:?}", x),
}
}
}
impl ToCss for FamilyName {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match self.syntax {
FamilyNameSyntax::Quoted => {
dest.write_char('"')?;
write!(CssStringWriter::new(dest), "{}", self.name)?;
dest.write_char('"')
}
FamilyNameSyntax::Identifiers(ref serialization) => {
// Note that `serialization` is already escaped/
// serialized appropriately.
dest.write_str(&*serialization)
}
}
}
}
impl ToCss for FontFamily {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
FontFamily::FamilyName(ref name) => name.to_css(dest),
// All generic values accepted by the parser are known to not require escaping.
FontFamily::Generic(ref name) => {
% if product == "gecko":
// We should treat -moz-fixed as monospace
if name == &atom!("-moz-fixed") {
return dest.write_str("monospace");
}
% endif
write!(dest, "{}", name)
},
}
}
}
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter();
iter.next().unwrap().to_css(dest)?;
for family in iter {
dest.write_str(", ")?;
family.to_css(dest)?;
}
Ok(())
}
}
#[cfg(feature = "servo")]
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq)]
pub struct FontFamilyList(Vec<FontFamily>);
#[cfg(feature = "gecko")]
#[derive(Clone, Debug)]
pub struct FontFamilyList(pub RefPtr<structs::SharedFontList>);
#[cfg(feature = "gecko")]
impl Hash for FontFamilyList {
fn hash<H>(&self, state: &mut H) where H: Hasher {
for name in self.0.mNames.iter() {
name.mType.hash(state);
name.mName.hash(state);
}
}
}
#[cfg(feature = "gecko")]
impl PartialEq for FontFamilyList {
fn eq(&self, other: &FontFamilyList) -> bool {
if self.0.mNames.len() != other.0.mNames.len() {
return false;
}
for (a, b) in self.0.mNames.iter().zip(other.0.mNames.iter()) {
if a.mType != b.mType || &*a.mName != &*b.mName {
return false;
}
}
true
}
}
#[cfg(feature = "gecko")]
impl Eq for FontFamilyList {}
impl FontFamilyList {
#[cfg(feature = "servo")]
pub fn new(families: Vec<FontFamily>) -> FontFamilyList {
FontFamilyList(families)
}
#[cfg(feature = "gecko")]
pub fn new(families: Vec<FontFamily>) -> FontFamilyList {
let fontlist;
let names;
unsafe {
fontlist = bindings::Gecko_SharedFontList_Create();
names = &mut (*fontlist).mNames;
names.ensure_capacity(families.len());
};
for family in families {
match family {
FontFamily::FamilyName(ref f) => {
let quoted = matches!(f.syntax, FamilyNameSyntax::Quoted);
unsafe {
bindings::Gecko_nsTArray_FontFamilyName_AppendNamed(
names,
f.name.as_ptr(),
quoted
);
}
}
FontFamily::Generic(ref name) => {
let (family_type, _generic) = FontFamily::generic(name);
unsafe {
bindings::Gecko_nsTArray_FontFamilyName_AppendGeneric(
names,
family_type
);
}
}
}
}
FontFamilyList(unsafe { RefPtr::from_addrefed(fontlist) })
}
#[cfg(feature = "servo")]
pub fn iter(&self) -> slice::Iter<FontFamily> {
self.0.iter()
}
#[cfg(feature = "gecko")]
pub fn iter(&self) -> FontFamilyNameIter {
FontFamilyNameIter {
names: &self.0.mNames,
cur: 0,
}
}
#[cfg(feature = "gecko")]
/// Return the generic ID if it is a single generic font
pub fn single_generic(&self) -> Option<u8> {
let mut iter = self.iter();
if let Some(FontFamily::Generic(ref name)) = iter.next() {
if iter.next().is_none() {
return Some(FontFamily::generic(name).1);
}
}
None
}
}
#[cfg(feature = "gecko")]
pub struct FontFamilyNameIter<'a> {
names: &'a structs::nsTArray<structs::FontFamilyName>,
cur: usize,
}
#[cfg(feature = "gecko")]
impl<'a> Iterator for FontFamilyNameIter<'a> {
type Item = FontFamily;
fn next(&mut self) -> Option<Self::Item> {
if self.cur < self.names.len() {
let item = FontFamily::from_font_family_name(&self.names[self.cur]);
self.cur += 1;
Some(item)
} else {
None
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub struct T(pub FontFamilyList);
#[cfg(feature = "gecko")]
impl MallocSizeOf for T {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
// SharedFontList objects are generally shared from the pointer
// stored in the specified value. So only count this if the
// SharedFontList is unshared.
unsafe {
bindings::Gecko_SharedFontList_SizeOfIncludingThisIfUnshared(
(self.0).0.get()
)
}
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(
FontFamilyList::new(vec![FontFamily::Generic(atom!("serif"))])
)
}
/// <family-name>#
/// <family-name> = <string> | [ <ident>+ ]
/// TODO: <generic-family>
pub fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
SpecifiedValue::parse(input)
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum SpecifiedValue {
Values(FontFamilyList),
System(SystemFont),
}
#[cfg(feature = "gecko")]
impl SpecifiedValue {
/// Return the generic ID if it is a single generic font
pub fn single_generic(&self) -> Option<u8> {
match *self {
SpecifiedValue::Values(ref values) => values.single_generic(),
_ => None,
}
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
fn to_computed_value(&self, _cx: &Context) -> Self::ComputedValue {
match *self {
SpecifiedValue::Values(ref v) => computed_value::T(v.clone()),
SpecifiedValue::System(_) => {
<%self:nongecko_unreachable>
_cx.cached_system_font.as_ref().unwrap().font_family.clone()
</%self:nongecko_unreachable>
}
}
}
fn from_computed_value(other: &computed_value::T) -> Self {
SpecifiedValue::Values(other.0.clone())
}
}
#[cfg(feature = "gecko")]
impl MallocSizeOf for SpecifiedValue {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
match *self {
SpecifiedValue::Values(ref v) => {
// Although a SharedFontList object is refcounted, we always
// attribute its size to the specified value.
unsafe {
bindings::Gecko_SharedFontList_SizeOfIncludingThis(
v.0.get()
)
}
}
SpecifiedValue::System(_) => 0,
}
}
}
impl SpecifiedValue {
pub fn system_font(f: SystemFont) -> Self {
SpecifiedValue::System(f)
}
pub fn get_system(&self) -> Option<SystemFont> {
if let SpecifiedValue::System(s) = *self {
Some(s)
} else {
None
}
}
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
input.parse_comma_separated(|input| FontFamily::parse(input)).map(|v| {
SpecifiedValue::Values(FontFamilyList::new(v))
})
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
SpecifiedValue::Values(ref v) => {
let mut iter = v.iter();
iter.next().unwrap().to_css(dest)?;
for family in iter {
dest.write_str(", ")?;
family.to_css(dest)?;
}
Ok(())
}
SpecifiedValue::System(sys) => sys.to_css(dest),
}
}
}
/// `FamilyName::parse` is based on `FontFamily::parse` and not the other way around
/// because we want the former to exclude generic family keywords.
impl Parse for FamilyName {
fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
match FontFamily::parse(input) {
Ok(FontFamily::FamilyName(name)) => Ok(name),
Ok(FontFamily::Generic(_)) => Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
Err(e) => Err(e)
}
}
}
</%helpers:longhand>
${helpers.single_keyword_system("font-style",
"normal italic oblique",
gecko_constant_prefix="NS_FONT_STYLE",
gecko_ffi_name="mFont.style",
spec="https://drafts.csswg.org/css-fonts/#propdef-font-style",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
animation_value_type="discrete")}
<% font_variant_caps_custom_consts= { "small-caps": "SMALLCAPS",
"all-small-caps": "ALLSMALL",
"petite-caps": "PETITECAPS",
"all-petite-caps": "ALLPETITE",
"titling-caps": "TITLING" } %>
${helpers.single_keyword_system("font-variant-caps",
"normal small-caps",
extra_gecko_values="all-small-caps petite-caps all-petite-caps unicase titling-caps",
gecko_constant_prefix="NS_FONT_VARIANT_CAPS",
gecko_ffi_name="mFont.variantCaps",
spec="https://drafts.csswg.org/css-fonts/#propdef-font-variant-caps",
custom_consts=font_variant_caps_custom_consts,
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
animation_value_type="discrete")}
${helpers.predefined_type("font-weight",
"FontWeight",
initial_value="computed::FontWeight::normal()",
initial_specified_value="specified::FontWeight::Normal",
animation_value_type="ComputedValue",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-fonts/#propdef-font-weight")}
<%helpers:longhand name="font-size" animation_value_type="NonNegativeLength"
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER"
allow_quirks="True" spec="https://drafts.csswg.org/css-fonts/#propdef-font-size">
use app_units::Au;
use values::specified::AllowQuirks;
use values::specified::length::FontBaseSize;
use values::specified::font::{FONT_MEDIUM_PX, KeywordSize};
use values::computed::font::{KeywordInfo};
pub mod computed_value {
use values::computed::font;
pub type T = font::FontSize;
}
pub use values::specified::font::FontSize as SpecifiedValue;
#[inline]
#[allow(missing_docs)]
pub fn get_initial_value() -> computed_value::T {
computed_value::T {
size: Au::from_px(FONT_MEDIUM_PX).into(),
keyword_info: Some(KeywordInfo::medium())
}
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::Keyword(KeywordInfo::medium())
}
/// <length> | <percentage> | <absolute-size> | <relative-size>
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
parse_quirky(context, input, AllowQuirks::No)
}
/// Parses a font-size, with quirks.
pub fn parse_quirky<'i, 't>(context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks)
-> Result<SpecifiedValue, ParseError<'i>> {
use self::specified::LengthOrPercentage;
if let Ok(lop) = input.try(|i| LengthOrPercentage::parse_non_negative_quirky(context, i, allow_quirks)) {
return Ok(SpecifiedValue::Length(lop))
}
if let Ok(kw) = input.try(KeywordSize::parse) {
return Ok(SpecifiedValue::Keyword(kw.into()))
}
try_match_ident_ignore_ascii_case! { input,
"smaller" => Ok(SpecifiedValue::Smaller),
"larger" => Ok(SpecifiedValue::Larger),
}
}
#[allow(unused_mut)]
pub fn cascade_specified_font_size(context: &mut Context,
specified_value: &SpecifiedValue,
mut computed: computed_value::T) {
// we could use clone_language and clone_font_family() here but that's
// expensive. Do it only in gecko mode for now.
% if product == "gecko":
// if the language or generic changed, we need to recalculate
// the font size from the stored font-size origin information.
if context.builder.get_font().gecko().mLanguage.mRawPtr !=
context.builder.get_parent_font().gecko().mLanguage.mRawPtr ||
context.builder.get_font().gecko().mGenericID !=
context.builder.get_parent_font().gecko().mGenericID {
if let Some(info) = computed.keyword_info {
computed.size = info.to_computed_value(context);
}
}
% endif
let device = context.builder.device;
let mut font = context.builder.take_font();
let parent_unconstrained = {
let parent_font = context.builder.get_parent_font();
font.apply_font_size(computed, parent_font, device)
};
context.builder.put_font(font);
if let Some(parent) = parent_unconstrained {
let new_unconstrained =
specified_value
.to_computed_value_against(context, FontBaseSize::Custom(Au::from(parent)));
context.builder
.mutate_font()
.apply_unconstrained_font_size(new_unconstrained.size);
}
}
/// FIXME(emilio): This is very complex. Also, it should move to
/// StyleBuilder.
pub fn cascade_inherit_font_size(context: &mut Context) {
// If inheriting, we must recompute font-size in case of language
// changes using the font_size_keyword. We also need to do this to
// handle mathml scriptlevel changes
let kw_inherited_size = context.builder.get_parent_font()
.clone_font_size()
.keyword_info.map(|info| {
SpecifiedValue::Keyword(info).to_computed_value(context).size
});
let mut font = context.builder.take_font();
font.inherit_font_size_from(context.builder.get_parent_font(),
kw_inherited_size,
context.builder.device);
context.builder.put_font(font);
}
/// Cascade the initial value for the `font-size` property.
///
/// FIXME(emilio): This is the only function that is outside of the
/// `StyleBuilder`, and should really move inside!
///
/// Can we move the font stuff there?
pub fn cascade_initial_font_size(context: &mut Context) {
// font-size's default ("medium") does not always
// compute to the same value and depends on the font
let computed =
longhands::font_size::get_initial_specified_value()
.to_computed_value(context);
context.builder.mutate_font().set_font_size(computed);
% if product == "gecko":
let device = context.builder.device;
context.builder.mutate_font().fixup_font_min_size(device);
% endif
}
</%helpers:longhand>
<%helpers:longhand products="gecko" name="font-size-adjust"
animation_value_type="longhands::font_size_adjust::computed_value::T"
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER"
spec="https://drafts.csswg.org/css-fonts/#propdef-font-size-adjust">
use properties::longhands::system_font::SystemFont;
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss)]
pub enum SpecifiedValue {
None,
Number(specified::Number),
System(SystemFont),
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self {
SpecifiedValue::None => computed_value::T::None,
SpecifiedValue::Number(ref n) => computed_value::T::Number(n.to_computed_value(context)),
SpecifiedValue::System(_) => {
<%self:nongecko_unreachable>
context.cached_system_font.as_ref().unwrap().font_size_adjust
</%self:nongecko_unreachable>
}
}
}
fn from_computed_value(computed: &computed_value::T) -> Self {
match *computed {
computed_value::T::None => SpecifiedValue::None,
computed_value::T::Number(ref v) => SpecifiedValue::Number(specified::Number::from_computed_value(v)),
}
}
}
impl SpecifiedValue {
pub fn system_font(f: SystemFont) -> Self {
SpecifiedValue::System(f)
}
pub fn get_system(&self) -> Option<SystemFont> {
if let SpecifiedValue::System(s) = *self {
Some(s)
} else {
None
}
}
}
pub mod computed_value {
use values::CSSFloat;
use values::animated::{ToAnimatedValue, ToAnimatedZero};
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq,
ToCss)]
pub enum T {
#[animation(error)]
None,
Number(CSSFloat),
}
impl T {
pub fn from_gecko_adjust(gecko: f32) -> Self {
if gecko == -1.0 {
T::None
} else {
T::Number(gecko)
}
}
}
impl ToAnimatedZero for T {
#[inline]
fn to_animated_zero(&self) -> Result<Self, ()> { Err(()) }
}
impl ToAnimatedValue for T {
type AnimatedValue = Self;
#[inline]
fn to_animated_value(self) -> Self {
self
}
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
match animated {
T::Number(number) => T::Number(number.max(0.)),
_ => animated
}
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::None
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::None
}
/// none | <number>
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
use values::specified::Number;
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue::None);
}
Ok(SpecifiedValue::Number(Number::parse_non_negative(context, input)?))
}
</%helpers:longhand>
<%helpers:longhand products="gecko" name="font-synthesis" animation_value_type="discrete"
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER"
spec="https://drafts.csswg.org/css-fonts/#propdef-font-synthesis">
use std::fmt;
use style_traits::ToCss;
pub mod computed_value {
pub use super::SpecifiedValue as T;
}
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct SpecifiedValue {
pub weight: bool,
pub style: bool,
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.weight && self.style {
dest.write_str("weight style")
} else if self.style {
dest.write_str("style")
} else if self.weight {
dest.write_str("weight")
} else {
dest.write_str("none")
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
SpecifiedValue { weight: true, style: true }
}
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let mut result = SpecifiedValue { weight: false, style: false };
// FIXME: remove clone() when lifetimes are non-lexical
try_match_ident_ignore_ascii_case! { input,
"none" => Ok(result),
"weight" => {
result.weight = true;
if input.try(|input| input.expect_ident_matching("style")).is_ok() {
result.style = true;
}
Ok(result)
},
"style" => {
result.style = true;
if input.try(|input| input.expect_ident_matching("weight")).is_ok() {
result.weight = true;
}
Ok(result)
},
}
}
#[cfg(feature = "gecko")]
impl From<u8> for SpecifiedValue {
fn from(bits: u8) -> SpecifiedValue {
use gecko_bindings::structs;
SpecifiedValue {
weight: bits & structs::NS_FONT_SYNTHESIS_WEIGHT as u8 != 0,
style: bits & structs::NS_FONT_SYNTHESIS_STYLE as u8 != 0
}
}
}
#[cfg(feature = "gecko")]
impl From<SpecifiedValue> for u8 {
fn from(v: SpecifiedValue) -> u8 {
use gecko_bindings::structs;
let mut bits: u8 = 0;
if v.weight {
bits |= structs::NS_FONT_SYNTHESIS_WEIGHT as u8;
}
if v.style {
bits |= structs::NS_FONT_SYNTHESIS_STYLE as u8;
}
bits
}
}
</%helpers:longhand>
${helpers.single_keyword_system("font-stretch",
"normal ultra-condensed extra-condensed condensed \
semi-condensed semi-expanded expanded extra-expanded \
ultra-expanded",
gecko_ffi_name="mFont.stretch",
gecko_constant_prefix="NS_FONT_STRETCH",
cast_type='i16',
spec="https://drafts.csswg.org/css-fonts/#propdef-font-stretch",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
animation_value_type="ComputedValue")}
${helpers.single_keyword_system("font-kerning",
"auto none normal",
products="gecko",
gecko_ffi_name="mFont.kerning",
gecko_constant_prefix="NS_FONT_KERNING",
spec="https://drafts.csswg.org/css-fonts/#propdef-font-kerning",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
animation_value_type="discrete")}
<%helpers:longhand name="font-variant-alternates" products="gecko" animation_value_type="discrete"
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER"
spec="https://drafts.csswg.org/css-fonts/#propdef-font-variant-alternates">
use properties::longhands::system_font::SystemFont;
use std::fmt;
use style_traits::ToCss;
use values::CustomIdent;
#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
pub enum VariantAlternates {
Stylistic(CustomIdent),
Styleset(Box<[CustomIdent]>),
CharacterVariant(Box<[CustomIdent]>),
Swash(CustomIdent),
Ornaments(CustomIdent),
Annotation(CustomIdent),