|
| 1 | +from xiblint.rules import Rule |
| 2 | +from xiblint.xibcontext import XibContext |
| 3 | + |
| 4 | + |
| 5 | +class StrictFonts(Rule): |
| 6 | + """ |
| 7 | + Ensures font name and size combinations are in the allowed set. This would generally be used instead |
| 8 | + of strict_font_names and strict_font_sizes. |
| 9 | +
|
| 10 | + Example configuration: |
| 11 | + { |
| 12 | + "allowed_fonts": [ |
| 13 | + { |
| 14 | + "name": "ComicSans-Regular", |
| 15 | + "size": 14 |
| 16 | + }, |
| 17 | + { |
| 18 | + "name": "ComicSans-Bold", |
| 19 | + "size": 14 |
| 20 | + } |
| 21 | + ] |
| 22 | + } |
| 23 | + """ |
| 24 | + def check(self, context): # type: (XibContext) -> None |
| 25 | + allowed_fonts = [(d["name"], d["size"]) for d in self.config.get('allowed_fonts', [])] |
| 26 | + |
| 27 | + for element in context.tree.findall('.//font') + context.tree.findall('.//fontDescription'): |
| 28 | + size_attribute_name = None |
| 29 | + |
| 30 | + if element.tag == 'font': |
| 31 | + # Skip <font> tags nested in a localization comment |
| 32 | + container = element.parent.parent.parent |
| 33 | + if container.tag == 'attributedString' and container.get('key') == 'userComments': |
| 34 | + continue |
| 35 | + |
| 36 | + size_attribute_name = 'size' |
| 37 | + else: |
| 38 | + size_attribute_name = 'pointSize' |
| 39 | + |
| 40 | + raw_size = element.get(size_attribute_name) |
| 41 | + if raw_size is None: |
| 42 | + context.error(element, 'Invalid <{}> found. Must have a {}.'.format(element.tag, size_attribute_name)) |
| 43 | + continue |
| 44 | + |
| 45 | + size = int(raw_size) |
| 46 | + |
| 47 | + name = element.get('name') |
| 48 | + if name is None: |
| 49 | + context.error(element, 'Invalid <{}> found. Must have a name.'.format(element.tag)) |
| 50 | + continue |
| 51 | + |
| 52 | + if (name, size) not in allowed_fonts: |
| 53 | + context.error(element, 'Invalid font found {} {}. Please use an allowed font.'.format(name, size)) |
0 commit comments