|
14 | 14 |
|
15 | 15 | from functools import lru_cache |
16 | 16 | import re |
17 | | - |
| 17 | +import numpy as np |
18 | 18 | from pyparsing import (Literal, ZeroOrMore, Optional, Regex, StringEnd, |
19 | 19 | ParseException, Suppress) |
20 | 20 |
|
@@ -177,19 +177,36 @@ def _property(self, s, loc, tokens): |
177 | 177 | parse_fontconfig_pattern = lru_cache()(FontconfigPatternParser().parse) |
178 | 178 |
|
179 | 179 |
|
| 180 | +def _escape_val(val, escape_func): |
| 181 | + """ |
| 182 | + Given a string value or a list of string values, run each value through |
| 183 | + the input escape function to make the values into legal font config |
| 184 | + strings. The result is returned as a string. |
| 185 | + """ |
| 186 | + if not np.iterable(val) or isinstance(val, str): |
| 187 | + val = [val] |
| 188 | + |
| 189 | + return ','.join(escape_func(r'\\\1', str(x)) for x in val |
| 190 | + if x is not None) |
| 191 | + |
| 192 | + |
180 | 193 | def generate_fontconfig_pattern(d): |
181 | 194 | """ |
182 | 195 | Given a dictionary of key/value pairs, generates a fontconfig |
183 | 196 | pattern string. |
184 | 197 | """ |
185 | 198 | props = [] |
186 | | - for key in 'family style variant weight stretch file size'.split(): |
| 199 | + |
| 200 | + # Family is added first w/o a keyword |
| 201 | + family = d.get_family() |
| 202 | + if family is not None and family != []: |
| 203 | + props.append(_escape_val(family, family_escape)) |
| 204 | + |
| 205 | + # The other keys are added as key=value |
| 206 | + for key in ['style', 'variant', 'weight', 'stretch', 'file', 'size']: |
187 | 207 | val = getattr(d, 'get_' + key)() |
| 208 | + # Don't use 'if not val' because 0 is a valid input. |
188 | 209 | if val is not None and val != []: |
189 | | - if type(val) == list: |
190 | | - val = [value_escape(r'\\\1', str(x)) for x in val |
191 | | - if x is not None] |
192 | | - if val != []: |
193 | | - val = ','.join(val) |
194 | | - props.append(":%s=%s" % (key, val)) |
| 210 | + props.append(":%s=%s" % (key, _escape_val(val, value_escape))) |
| 211 | + |
195 | 212 | return ''.join(props) |
0 commit comments