|
7 | 7 | :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. |
8 | 8 | :license: BSD, see LICENSE for details. |
9 | 9 | """ |
10 | | - |
11 | 10 | import os |
12 | 11 | import sys |
13 | 12 |
|
@@ -68,6 +67,15 @@ def __init__(self, font_name, font_size=14): |
68 | 67 | self.font_size = font_size |
69 | 68 | self.fonts = {} |
70 | 69 | self.encoding = None |
| 70 | + self.variable = False |
| 71 | + if hasattr(font_name, 'read') or os.path.isfile(font_name): |
| 72 | + font = ImageFont.truetype(font_name, self.font_size) |
| 73 | + self.variable = True |
| 74 | + for style in STYLES: |
| 75 | + self.fonts[style] = font |
| 76 | + |
| 77 | + return |
| 78 | + |
71 | 79 | if sys.platform.startswith('win'): |
72 | 80 | if not font_name: |
73 | 81 | self.font_name = DEFAULT_FONT_NAME_WIN |
@@ -223,14 +231,42 @@ def get_font(self, bold, oblique): |
223 | 231 | Get the font based on bold and italic flags. |
224 | 232 | """ |
225 | 233 | if bold and oblique: |
| 234 | + if self.variable: |
| 235 | + return self.get_style('BOLDITALIC') |
| 236 | + |
226 | 237 | return self.fonts['BOLDITALIC'] |
227 | 238 | elif bold: |
| 239 | + if self.variable: |
| 240 | + return self.get_style('BOLD') |
| 241 | + |
228 | 242 | return self.fonts['BOLD'] |
229 | 243 | elif oblique: |
| 244 | + if self.variable: |
| 245 | + return self.get_style('ITALIC') |
| 246 | + |
230 | 247 | return self.fonts['ITALIC'] |
231 | 248 | else: |
| 249 | + if self.variable: |
| 250 | + return self.get_style('NORMAL') |
| 251 | + |
232 | 252 | return self.fonts['NORMAL'] |
233 | 253 |
|
| 254 | + def get_style(self, style): |
| 255 | + """ |
| 256 | + Get the specified style of the font if it is a variable font. |
| 257 | + If not found, return the normal font. |
| 258 | + """ |
| 259 | + font = self.fonts[style] |
| 260 | + for style_name in STYLES[style]: |
| 261 | + try: |
| 262 | + font.set_variation_by_name(style_name) |
| 263 | + return font |
| 264 | + except ValueError: |
| 265 | + pass |
| 266 | + except OSError: |
| 267 | + return font |
| 268 | + |
| 269 | + return font |
234 | 270 |
|
235 | 271 | class ImageFormatter(Formatter): |
236 | 272 | """ |
@@ -258,6 +294,8 @@ class ImageFormatter(Formatter): |
258 | 294 | The font name to be used as the base font from which others, such as |
259 | 295 | bold and italic fonts will be generated. This really should be a |
260 | 296 | monospace font to look sane. |
| 297 | + If a filename or a file-like object is specified, the user must |
| 298 | + provide different styles of the font. |
261 | 299 |
|
262 | 300 | Default: "Courier New" on Windows, "Menlo" on Mac OS, and |
263 | 301 | "DejaVu Sans Mono" on \\*nix |
|
0 commit comments