| 1 |
r""" |
| 2 |
|
| 3 |
Iconic Font |
| 4 |
=========== |
| 5 |
|
| 6 |
A lightweight module handling iconic fonts. |
| 7 |
|
| 8 |
It is designed to provide a simple way for creating QIcons from glyphs. |
| 9 |
|
| 10 |
From a user's viewpoint, the main entry point is the ``IconicFont`` class which |
| 11 |
contains methods for loading new iconic fonts with their character map and |
| 12 |
methods returning instances of ``QIcon``. |
| 13 |
|
| 14 |
""" |
| 15 |
|
| 16 |
|
| 17 |
import ctypes |
| 18 |
import json |
| 19 |
import os |
| 20 |
import shutil |
| 21 |
import warnings |
| 22 |
|
| 23 |
|
| 24 |
from qtpy import PYSIDE_VERSION |
| 25 |
from qtpy.QtCore import QObject, QPoint, QRect, Qt, QSizeF, QRectF, QPointF, QThread |
| 26 |
from qtpy.QtGui import ( |
| 27 |
QColor, |
| 28 |
QFont, |
| 29 |
QFontDatabase, |
| 30 |
QIcon, |
| 31 |
QIconEngine, |
| 32 |
QPainter, |
| 33 |
QPixmap, |
| 34 |
QTransform, |
| 35 |
QPalette, |
| 36 |
QRawFont, |
| 37 |
QImage, |
| 38 |
) |
| 39 |
from qtpy.QtWidgets import QApplication |
| 40 |
|
| 41 |
try: |
| 42 |
|
| 43 |
|
| 44 |
from qtpy.QtGui import QGlyphRun |
| 45 |
except ImportError: |
| 46 |
QGlyphRun = None |
| 47 |
|
| 48 |
|
| 49 |
|
| •50 |
SYSTEM_FONTS = True |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
if os.name == "nt": |
| 55 |
from ctypes import wintypes, windll |
| 56 |
import winreg |
| 57 |
|
| 58 |
user32 = ctypes.WinDLL("user32", use_last_error=True) |
| 59 |
gdi32 = ctypes.WinDLL("gdi32", use_last_error=True) |
| 60 |
|
| 61 |
FONTS_REG_PATH = r"Software\Microsoft\Windows NT\CurrentVersion\Fonts" |
| 62 |
GFRI_DESCRIPTION = 1 |
| 63 |
GFRI_ISTRUETYPE = 3 |
| 64 |
|
| 65 |
if not hasattr(wintypes, "LPDWORD"): |
| 66 |
wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD) |
| 67 |
|
| 68 |
user32.SendMessageTimeoutW.restype = wintypes.LPVOID |
| 69 |
user32.SendMessageTimeoutW.argtypes = ( |
| 70 |
wintypes.HWND, |
| 71 |
wintypes.UINT, |
| 72 |
wintypes.LPVOID, |
| 73 |
wintypes.LPVOID, |
| 74 |
wintypes.UINT, |
| 75 |
wintypes.UINT, |
| 76 |
wintypes.LPVOID, |
| 77 |
) |
| 78 |
|
| 79 |
gdi32.AddFontResourceW.argtypes = (wintypes.LPCWSTR,) |
| 80 |
|
| 81 |
|
| 82 |
gdi32.GetFontResourceInfoW.argtypes = ( |
| 83 |
wintypes.LPCWSTR, |
| 84 |
wintypes.LPDWORD, |
| 85 |
wintypes.LPVOID, |
| 86 |
wintypes.DWORD, |
| 87 |
) |
| 88 |
|
| 89 |
|
| 90 |
def text_color(): |
| 91 |
try: |
| 92 |
palette = QApplication.instance().palette() |
| 93 |
return palette.color(QPalette.Active, QPalette.Text) |
| 94 |
except AttributeError: |
| 95 |
return QColor(50, 50, 50) |
| 96 |
|
| 97 |
|
| 98 |
def text_color_disabled(): |
| 99 |
try: |
| 100 |
palette = QApplication.instance().palette() |
| 101 |
return palette.color(QPalette.Disabled, QPalette.Text) |
| 102 |
except AttributeError: |
| 103 |
return QColor(150, 150, 150) |
| 104 |
|
| 105 |
|
| 106 |
_default_options = { |
| 107 |
"color": text_color, |
| 108 |
"color_disabled": text_color_disabled, |
| 109 |
"opacity": 1.0, |
| 110 |
"scale_factor": 1.0, |
| 111 |
} |
| 112 |
|
| 113 |
|
| 114 |
def set_global_defaults(**kwargs): |
| 115 |
"""Set global defaults for the options passed to the icon painter.""" |
| 116 |
|
| 117 |
valid_options = [ |
| 118 |
"active", |
| 119 |
"selected", |
| 120 |
"disabled", |
| 121 |
"on", |
| 122 |
"off", |
| 123 |
"on_active", |
| 124 |
"on_selected", |
| 125 |
"on_disabled", |
| 126 |
"off_active", |
| 127 |
"off_selected", |
| 128 |
"off_disabled", |
| 129 |
"color", |
| 130 |
"color_on", |
| 131 |
"color_off", |
| 132 |
"color_active", |
| 133 |
"color_selected", |
| 134 |
"color_disabled", |
| 135 |
"color_on_selected", |
| 136 |
"color_on_active", |
| 137 |
"color_on_disabled", |
| 138 |
"color_off_selected", |
| 139 |
"color_off_active", |
| 140 |
"color_off_disabled", |
| 141 |
"animation", |
| 142 |
"offset", |
| 143 |
"scale_factor", |
| 144 |
"rotated", |
| 145 |
"hflip", |
| 146 |
"vflip", |
| 147 |
"draw", |
| 148 |
] |
| 149 |
|
| 150 |
for kw in kwargs: |
| 151 |
if kw in valid_options: |
| 152 |
_default_options[kw] = kwargs[kw] |
| 153 |
else: |
| 154 |
error = "Invalid option '{0}'".format(kw) |
| 155 |
raise KeyError(error) |
| 156 |
|
| 157 |
|
| 158 |
class CharIconPainter: |
| 159 |
"""Char icon painter.""" |
| 160 |
|
| 161 |
def paint(self, iconic, painter, rect, mode, state, options): |
| 162 |
"""Main paint method.""" |
| 163 |
for opt in options: |
| 164 |
self._paint_icon(iconic, painter, rect, mode, state, opt) |
| 165 |
|
| 166 |
def _paint_icon(self, iconic, painter, rect, mode, state, options): |
| 167 |
"""Paint a single icon.""" |
| 168 |
painter.save() |
| 169 |
|
| 170 |
color_options = { |
| 171 |
QIcon.On: { |
| 172 |
QIcon.Normal: (options["color_on"], options["on"]), |
| 173 |
QIcon.Disabled: (options["color_on_disabled"], options["on_disabled"]), |
| 174 |
QIcon.Active: (options["color_on_active"], options["on_active"]), |
| 175 |
QIcon.Selected: (options["color_on_selected"], options["on_selected"]), |
| 176 |
}, |
| 177 |
QIcon.Off: { |
| 178 |
QIcon.Normal: (options["color_off"], options["off"]), |
| 179 |
QIcon.Disabled: ( |
| 180 |
options["color_off_disabled"], |
| 181 |
options["off_disabled"], |
| 182 |
), |
| 183 |
QIcon.Active: (options["color_off_active"], options["off_active"]), |
| 184 |
QIcon.Selected: ( |
| 185 |
options["color_off_selected"], |
| 186 |
options["off_selected"], |
| 187 |
), |
| 188 |
}, |
| 189 |
} |
| 190 |
|
| 191 |
color, char = color_options[state][mode] |
| 192 |
alpha = None |
| 193 |
|
| 194 |
|
| 195 |
if isinstance(color, tuple): |
| 196 |
alpha = color[1] |
| 197 |
color = color[0] |
| 198 |
|
| 199 |
qcolor = QColor(color) |
| 200 |
if alpha: |
| 201 |
qcolor.setAlpha(alpha) |
| 202 |
|
| 203 |
painter.setPen(qcolor) |
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
draw_size = round(0.875 * rect.height() * options["scale_factor"]) |
| 211 |
prefix = options["prefix"] |
| 212 |
|
| 213 |
|
| 214 |
animation = options.get("animation") |
| 215 |
if animation is not None: |
| 216 |
animation.setup(self, painter, rect) |
| 217 |
|
| 218 |
if "offset" in options: |
| 219 |
rect = QRect(rect) |
| 220 |
rect.translate( |
| 221 |
round(options["offset"][0] * rect.width()), |
| 222 |
round(options["offset"][1] * rect.height()), |
| 223 |
) |
| 224 |
|
| 225 |
x_center = rect.width() * 0.5 |
| 226 |
y_center = rect.height() * 0.5 |
| 227 |
transform = QTransform() |
| 228 |
transform.translate(+x_center, +y_center) |
| 229 |
if "vflip" in options and options["vflip"] is True: |
| 230 |
transform.scale(1, -1) |
| 231 |
if "hflip" in options and options["hflip"] is True: |
| 232 |
transform.scale(-1, 1) |
| 233 |
if "rotated" in options: |
| 234 |
transform.rotate(options["rotated"]) |
| 235 |
transform.translate(-x_center, -y_center) |
| 236 |
painter.setTransform(transform, True) |
| 237 |
|
| 238 |
painter.setOpacity(options.get("opacity", 1.0)) |
| 239 |
|
| 240 |
draw = options.get("draw") |
| 241 |
if draw not in ("text", "path", "glyphrun", "image"): |
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
draw = "path" if animation is not None else "text" |
| 246 |
|
| 247 |
def try_draw_rawfont(): |
| 248 |
if draw == "glyphrun" and animation is not None: |
| 249 |
|
| 250 |
|
| 251 |
rawfont = iconic.rawfont(prefix, draw_size, QFont.PreferNoHinting) |
| 252 |
else: |
| 253 |
rawfont = iconic.rawfont(prefix, draw_size) |
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
if not rawfont.fontTable("glyf"): |
| 258 |
return False |
| 259 |
|
| 260 |
glyph = rawfont.glyphIndexesForString(char)[0] |
| 261 |
advance = rawfont.advancesForGlyphIndexes((glyph,))[0] |
| 262 |
ascent = rawfont.ascent() |
| 263 |
size = QSizeF(abs(advance.x()), ascent + rawfont.descent()) |
| 264 |
painter.translate(QRectF(rect).center()) |
| 265 |
painter.translate(-size.width() / 2, -size.height() / 2) |
| 266 |
|
| 267 |
if draw == "path": |
| 268 |
path = rawfont.pathForGlyph(glyph) |
| 269 |
path.translate(0, ascent) |
| 270 |
path.setFillRule(Qt.WindingFill) |
| 271 |
painter.setRenderHint(QPainter.Antialiasing, True) |
| 272 |
painter.fillPath(path, painter.pen().color()) |
| 273 |
|
| 274 |
elif draw == "glyphrun": |
| 275 |
if QGlyphRun: |
| 276 |
glyphrun = QGlyphRun() |
| 277 |
glyphrun.setRawFont(rawfont) |
| 278 |
glyphrun.setGlyphIndexes((glyph,)) |
| 279 |
glyphrun.setPositions((QPointF(0, ascent),)) |
| 280 |
painter.drawGlyphRun(QPointF(0, 0), glyphrun) |
| 281 |
else: |
| 282 |
warnings.warn( |
| 283 |
"QGlyphRun is unavailable for the current Qt binding! " |
| 284 |
"QtAwesome will use the default draw values" |
| 285 |
) |
| 286 |
return False |
| 287 |
elif draw == "image": |
| 288 |
image = rawfont.alphaMapForGlyph( |
| 289 |
glyph, QRawFont.PixelAntialiasing |
| 290 |
).convertToFormat(QImage.Format_ARGB32_Premultiplied) |
| 291 |
painter2 = QPainter(image) |
| 292 |
painter2.setCompositionMode(QPainter.CompositionMode_SourceIn) |
| 293 |
painter2.fillRect(image.rect(), painter.pen().color()) |
| 294 |
painter2.end() |
| 295 |
brect = rawfont.boundingRect(glyph) |
| 296 |
brect.translate(0, ascent) |
| 297 |
painter.setRenderHint(QPainter.SmoothPixmapTransform, True) |
| 298 |
painter.drawImage(brect.topLeft(), image) |
| 299 |
|
| 300 |
else: |
| 301 |
|
| 302 |
return False |
| 303 |
|
| 304 |
return True |
| 305 |
|
| 306 |
if draw == "text" or not try_draw_rawfont(): |
| 307 |
font = iconic.font(prefix, draw_size) |
| 308 |
|
| 309 |
|
| 310 |
if animation is not None: |
| 311 |
font.setHintingPreference(QFont.PreferNoHinting) |
| 312 |
painter.setFont(font) |
| 313 |
painter.drawText(rect, int(Qt.AlignCenter | Qt.AlignVCenter), char) |
| 314 |
|
| 315 |
painter.restore() |
| 316 |
|
| 317 |
|
| 318 |
class FontError(Exception): |
| 319 |
"""Exception for font errors.""" |
| 320 |
|
| 321 |
|
| 322 |
class CharIconEngine(QIconEngine): |
| 323 |
"""Specialization of QIconEngine used to draw font-based icons.""" |
| 324 |
|
| 325 |
def __init__(self, iconic, painter, options): |
| 326 |
super().__init__() |
| 327 |
self.iconic = iconic |
| 328 |
self.painter = painter |
| 329 |
self.options = options |
| 330 |
|
| 331 |
def paint(self, painter, rect, mode, state): |
| 332 |
self.painter.paint(self.iconic, painter, rect, mode, state, self.options) |
| 333 |
|
| 334 |
def pixmap(self, size, mode, state): |
| 335 |
pm = QPixmap(size) |
| 336 |
pm.fill(Qt.transparent) |
| 337 |
self.paint(QPainter(pm), QRect(QPoint(0, 0), size), mode, state) |
| 338 |
return pm |
| 339 |
|
| 340 |
|
| 341 |
class IconicFont(QObject): |
| 342 |
"""Main class for managing iconic fonts.""" |
| 343 |
|
| 344 |
def __init__(self, *args): |
| 345 |
"""IconicFont Constructor. |
| 346 |
|
| 347 |
Parameters |
| 348 |
---------- |
| 349 |
``*args``: tuples |
| 350 |
Each positional argument is a tuple of 3 or 4 values: |
| 351 |
- The prefix string to be used when accessing a given font set, |
| 352 |
- The ttf font filename, |
| 353 |
- The json charmap filename, |
| 354 |
- Optionally, the directory containing these files. When not |
| 355 |
provided, the files will be looked for in the QtAwesome ``fonts`` |
| 356 |
directory. |
| 357 |
""" |
| 358 |
super().__init__() |
| 359 |
self.painter = CharIconPainter() |
| 360 |
self.painters = {} |
| 361 |
self.fontname = {} |
| 362 |
self.fontdata = {} |
| 363 |
self.fontids = {} |
| 364 |
self.charmap = {} |
| 365 |
self.icon_cache = {} |
| 366 |
self.rawfont_cache = {} |
| 367 |
for fargs in args: |
| 368 |
self.load_font(*fargs) |
| 369 |
|
| 370 |
def load_font(self, prefix, ttf_filename, charmap_filename, directory=None): |
| 371 |
"""Loads a font file and the associated charmap. |
| 372 |
|
| 373 |
If ``directory`` is None, the files will be looked for in |
| 374 |
the qtawesome ``fonts`` directory. |
| 375 |
|
| 376 |
Parameters |
| 377 |
---------- |
| 378 |
prefix: str |
| 379 |
Prefix string to be used when accessing a given font set |
| 380 |
ttf_filename: str |
| 381 |
Ttf font filename |
| 382 |
charmap_filename: str |
| 383 |
Charmap filename |
| 384 |
directory: str or None, optional |
| 385 |
Directory path for font and charmap files |
| 386 |
""" |
| 387 |
|
| 388 |
def hook(obj): |
| 389 |
result = {} |
| 390 |
for key in obj: |
| 391 |
try: |
| 392 |
result[key] = chr(int(obj[key], 16)) |
| 393 |
except ValueError: |
| 394 |
if int(obj[key], 16) > 0xFFFF: |
| 395 |
|
| 396 |
|
| 397 |
pass |
| 398 |
else: |
| 399 |
raise FontError( |
| 400 |
"Failed to load character {0}:{1}".format(key, obj[key]) |
| 401 |
) |
| 402 |
return result |
| 403 |
|
| 404 |
if directory is None: |
| 405 |
directory = self._get_fonts_directory() |
| 406 |
|
| 407 |
|
| 408 |
if QApplication.instance() is not None: |
| 409 |
with open(os.path.join(directory, ttf_filename), "rb") as font_data: |
| 410 |
data = font_data.read() |
| 411 |
id_ = ( |
| 412 |
-1 |
| 413 |
if os.environ.get("QTA_FORCE_SYSTEM_FONTS_LOAD") and os.name == "nt" |
| 414 |
else QFontDatabase.addApplicationFontFromData(data) |
| 415 |
) |
| 416 |
font_data.close() |
| 417 |
|
| 418 |
if id_ == -1 and os.name == "nt": |
| 419 |
|
| 420 |
windows_dir = os.environ.get("WINDIR", r"C:\Windows") |
| 421 |
if os.path.isdir(windows_dir): |
| 422 |
from_system_ttf = os.path.join(windows_dir, "Fonts", ttf_filename) |
| 423 |
id_ = QFontDatabase.addApplicationFont(from_system_ttf) |
| 424 |
|
| 425 |
loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_) |
| 426 |
|
| 427 |
if loadedFontFamilies: |
| 428 |
self.fontids[prefix] = id_ |
| 429 |
self.fontname[prefix] = loadedFontFamilies[0] |
| 430 |
self.fontdata[prefix] = data |
| 431 |
else: |
| 432 |
raise FontError( |
| 433 |
"Font at '{0}' appears to be empty. " |
| 434 |
"If you are on Windows 10, please read " |
| 435 |
"https://support.microsoft.com/" |
| 436 |
"en-us/kb/3053676 " |
| 437 |
"to know how to prevent Windows from blocking " |
| 438 |
"the fonts that come with QtAwesome.".format( |
| 439 |
os.path.join(directory, ttf_filename) |
| 440 |
) |
| 441 |
) |
| 442 |
|
| 443 |
with open(os.path.join(directory, charmap_filename), "r") as codes: |
| 444 |
self.charmap[prefix] = json.load(codes, object_hook=hook) |
| 445 |
|
| 446 |
def icon(self, *names, **kwargs): |
| 447 |
"""Return a QIcon object corresponding to the provided icon name.""" |
| 448 |
cache_key = "{}{}".format(names, kwargs) |
| 449 |
|
| 450 |
if cache_key not in self.icon_cache: |
| 451 |
options_list = kwargs.pop("options", [{}] * len(names)) |
| 452 |
general_options = kwargs |
| 453 |
|
| 454 |
if len(options_list) != len(names): |
| 455 |
error = '"options" must be a list of size {0}'.format(len(names)) |
| 456 |
raise Exception(error) |
| 457 |
|
| 458 |
if QApplication.instance() is not None: |
| 459 |
parsed_options = [] |
| 460 |
for i in range(len(options_list)): |
| 461 |
specific_options = options_list[i] |
| 462 |
parsed_options.append( |
| 463 |
self._parse_options(specific_options, general_options, names[i]) |
| 464 |
) |
| 465 |
|
| 466 |
|
| 467 |
api_options = parsed_options |
| 468 |
|
| 469 |
self.icon_cache[cache_key] = self._icon_by_painter( |
| 470 |
self.painter, api_options |
| 471 |
) |
| 472 |
else: |
| 473 |
warnings.warn( |
| 474 |
"You need to have a running QApplication to use QtAwesome!" |
| 475 |
) |
| 476 |
return QIcon() |
| 477 |
return self.icon_cache[cache_key] |
| 478 |
|
| 479 |
def _parse_options(self, specific_options, general_options, name): |
| 480 |
live_dict = {k: v() if callable(v) else v for k, v in _default_options.items()} |
| 481 |
|
| 482 |
options = dict(live_dict, **general_options) |
| 483 |
options.update(specific_options) |
| 484 |
|
| 485 |
|
| 486 |
|
| 487 |
icon_kw = [ |
| 488 |
"char", |
| 489 |
"on", |
| 490 |
"off", |
| 491 |
"active", |
| 492 |
"selected", |
| 493 |
"disabled", |
| 494 |
"on_active", |
| 495 |
"on_selected", |
| 496 |
"on_disabled", |
| 497 |
"off_active", |
| 498 |
"off_selected", |
| 499 |
"off_disabled", |
| 500 |
] |
| 501 |
char = options.get("char", name) |
| 502 |
on = options.get("on", char) |
| 503 |
off = options.get("off", char) |
| 504 |
active = options.get("active", on) |
| 505 |
selected = options.get("selected", active) |
| 506 |
disabled = options.get("disabled", char) |
| 507 |
on_active = options.get("on_active", active) |
| 508 |
on_selected = options.get("on_selected", selected) |
| 509 |
on_disabled = options.get("on_disabled", disabled) |
| 510 |
off_active = options.get("off_active", active) |
| 511 |
off_selected = options.get("off_selected", selected) |
| 512 |
off_disabled = options.get("off_disabled", disabled) |
| 513 |
|
| 514 |
icon_dict = { |
| 515 |
"char": char, |
| 516 |
"on": on, |
| 517 |
"off": off, |
| 518 |
"active": active, |
| 519 |
"selected": selected, |
| 520 |
"disabled": disabled, |
| 521 |
"on_active": on_active, |
| 522 |
"on_selected": on_selected, |
| 523 |
"on_disabled": on_disabled, |
| 524 |
"off_active": off_active, |
| 525 |
"off_selected": off_selected, |
| 526 |
"off_disabled": off_disabled, |
| 527 |
} |
| 528 |
names = [icon_dict.get(kw, name) for kw in icon_kw] |
| 529 |
prefix, chars = self._get_prefix_chars(names) |
| 530 |
options.update(dict(zip(*(icon_kw, chars)))) |
| 531 |
options.update({"prefix": prefix}) |
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
color = options.get("color") |
| 536 |
options.setdefault("color_on", color) |
| 537 |
options.setdefault("color_active", options["color_on"]) |
| 538 |
options.setdefault("color_selected", options["color_active"]) |
| 539 |
options.setdefault("color_on_active", options["color_active"]) |
| 540 |
options.setdefault("color_on_selected", options["color_selected"]) |
| 541 |
options.setdefault("color_on_disabled", options["color_disabled"]) |
| 542 |
options.setdefault("color_off", color) |
| 543 |
options.setdefault("color_off_active", options["color_active"]) |
| 544 |
options.setdefault("color_off_selected", options["color_selected"]) |
| 545 |
options.setdefault("color_off_disabled", options["color_disabled"]) |
| 546 |
|
| 547 |
return options |
| 548 |
|
| 549 |
def _get_prefix_chars(self, names): |
| 550 |
chars = [] |
| 551 |
for name in names: |
| 552 |
if "." in name: |
| 553 |
prefix, n = name.split(".") |
| 554 |
if prefix in self.charmap: |
| 555 |
if n in self.charmap[prefix]: |
| 556 |
chars.append(self.charmap[prefix][n]) |
| 557 |
else: |
| 558 |
error = 'Invalid icon name "{0}" in font "{1}"'.format( |
| 559 |
n, prefix |
| 560 |
) |
| 561 |
raise Exception(error) |
| 562 |
else: |
| 563 |
error = 'Invalid font prefix "{0}"'.format(prefix) |
| 564 |
raise Exception(error) |
| 565 |
else: |
| 566 |
raise Exception("Invalid icon name") |
| 567 |
|
| 568 |
return prefix, chars |
| 569 |
|
| 570 |
def font(self, prefix, size): |
| 571 |
"""Return a QFont corresponding to the given prefix and size.""" |
| 572 |
font = QFont() |
| 573 |
font.setFamily(self.fontname[prefix]) |
| 574 |
font.setPixelSize(round(size)) |
| 575 |
if prefix[-1] == "s": |
| 576 |
font.setStyleName("Solid") |
| 577 |
return font |
| 578 |
|
| 579 |
def rawfont(self, prefix, size, hintingPreference=QFont.PreferDefaultHinting): |
| 580 |
"""Return a QRawFont corresponding to the given prefix and size.""" |
| 581 |
cache = self.rawfont_cache |
| 582 |
|
| 583 |
|
| 584 |
|
| 585 |
|
| 586 |
|
| 587 |
if PYSIDE_VERSION: |
| 588 |
|
| 589 |
tid = str(QThread.currentThread()) |
| 590 |
else: |
| 591 |
tid = int(QThread.currentThreadId()) |
| 592 |
|
| 593 |
if tid not in cache: |
| 594 |
cache[tid] = {} |
| 595 |
|
| 596 |
def clear_cache(): |
| 597 |
cache.pop(tid) |
| 598 |
|
| 599 |
|
| 600 |
|
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
if QThread.currentThread() is not QApplication.instance().thread(): |
| 608 |
QThread.currentThread().finished.connect(clear_cache) |
| 609 |
key = prefix, size, hintingPreference |
| 610 |
if key not in cache[tid]: |
| 611 |
cache[tid][key] = QRawFont(self.fontdata[prefix], size, hintingPreference) |
| 612 |
return cache[tid][key] |
| 613 |
|
| 614 |
def set_custom_icon(self, name, painter): |
| 615 |
"""Associate a user-provided CharIconPainter to an icon name. |
| 616 |
|
| 617 |
The custom icon can later be addressed by calling |
| 618 |
icon('custom.NAME') where NAME is the provided name for that icon. |
| 619 |
|
| 620 |
Parameters |
| 621 |
---------- |
| 622 |
name: str |
| 623 |
name of the custom icon |
| 624 |
painter: CharIconPainter |
| 625 |
The icon painter, implementing |
| 626 |
``paint(self, iconic, painter, rect, mode, state, options)`` |
| 627 |
""" |
| 628 |
self.painters[name] = painter |
| 629 |
|
| 630 |
def install_fonts_system_wide(self): |
| 631 |
"""Install bundled fonts system wide on Windows.""" |
| 632 |
if os.name == "nt": |
| 633 |
if windll.shell32.IsUserAnAdmin(): |
| 634 |
|
| 635 |
fonts_directory = os.path.join( |
| 636 |
os.path.dirname(os.path.realpath(__file__)), "fonts" |
| 637 |
) |
| 638 |
self._install_fonts(fonts_directory, system_wide=True) |
| 639 |
else: |
| 640 |
|
| 641 |
warnings.warn( |
| 642 |
"Admin privileges are needed to install the bundled fonts. " |
| 643 |
"A prompt to get them will be shown and after that this " |
| 644 |
"command will be relaunched..." |
| 645 |
) |
| 646 |
windll.shell32.ShellExecuteW( |
| 647 |
None, "runas", "qta-install-fonts-all-users", None, None, 0 |
| 648 |
) |
| 649 |
|
| 650 |
def _custom_icon(self, name, **kwargs): |
| 651 |
"""Return the custom icon corresponding to the given name.""" |
| 652 |
options = dict(_default_options, **kwargs) |
| 653 |
if name in self.painters: |
| 654 |
painter = self.painters[name] |
| 655 |
return self._icon_by_painter(painter, options) |
| 656 |
else: |
| 657 |
return QIcon() |
| 658 |
|
| 659 |
def _icon_by_painter(self, painter, options): |
| 660 |
"""Return the icon corresponding to the given painter.""" |
| 661 |
engine = CharIconEngine(self, painter, options) |
| 662 |
return QIcon(engine) |
| 663 |
|
| 664 |
def _get_fonts_directory(self): |
| 665 |
""" |
| 666 |
Get bundled fonts directory. |
| 667 |
|
| 668 |
On Windows an attempt to install the fonts per user is done |
| 669 |
to prevent errors with fonts loading. |
| 670 |
|
| 671 |
See spyder-ide/qtawesome#167 and spyder-ide/spyder#18642 for |
| 672 |
context. |
| 673 |
""" |
| 674 |
fonts_directory = os.path.join( |
| 675 |
os.path.dirname(os.path.realpath(__file__)), "fonts" |
| 676 |
) |
| 677 |
return self._install_fonts(fonts_directory) |
| 678 |
|
| 679 |
def _install_fonts(self, fonts_directory, system_wide=False): |
| 680 |
""" |
| 681 |
Install bundled fonts on Windows. |
| 682 |
|
| 683 |
By default copy the fonts to the user Fonts folder. Passing the |
| 684 |
`system_wide` kwarg as `True` will instead copy them to the system |
| 685 |
Fonts directory (operation will fail in case the required admin |
| 686 |
privileges are not available). |
| 687 |
|
| 688 |
Based on https://stackoverflow.com/a/41841088/15954282 and |
| 689 |
https://superuser.com/a/1663482 |
| 690 |
""" |
| 691 |
if os.name != "nt": |
| 692 |
return fonts_directory |
| 693 |
|
| 694 |
|
| 695 |
windows_dir = os.environ.get("WINDIR", None) |
| 696 |
if not windows_dir and system_wide: |
| 697 |
return fonts_directory |
| 698 |
|
| 699 |
local_appdata_dir = os.environ.get("LOCALAPPDATA", None) |
| 700 |
if not local_appdata_dir and not system_wide: |
| 701 |
return fonts_directory |
| 702 |
|
| 703 |
|
| 704 |
system_fonts_dir = os.path.join(windows_dir, "Fonts") |
| 705 |
|
| 706 |
user_fonts_dir = os.path.join( |
| 707 |
local_appdata_dir, "Microsoft", "Windows", "Fonts" |
| 708 |
) |
| 709 |
os.makedirs(user_fonts_dir, exist_ok=True) |
| 710 |
|
| 711 |
install_fonts_dir = system_fonts_dir if system_wide else user_fonts_dir |
| 712 |
|
| 713 |
|
| 714 |
for root, __, files in os.walk(fonts_directory): |
| 715 |
for filename in files: |
| 716 |
src_path = os.path.join(root, filename) |
| 717 |
dst_filename = filename |
| 718 |
dst_path = os.path.join(install_fonts_dir, dst_filename) |
| 719 |
|
| 720 |
|
| 721 |
|
| 722 |
if os.path.isfile(dst_path): |
| 723 |
continue |
| 724 |
|
| 725 |
shutil.copy(src_path, dst_path) |
| 726 |
|
| 727 |
|
| 728 |
if os.path.splitext(filename)[-1] == ".ttf": |
| 729 |
|
| 730 |
if not gdi32.AddFontResourceW(dst_path): |
| 731 |
try: |
| 732 |
os.remove(dst_path) |
| 733 |
except OSError: |
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
pass |
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
|
| 742 |
|
| 743 |
|
| 744 |
|
| 745 |
|
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
if not os.path.isfile(os.path.join(system_fonts_dir, filename)): |
| 751 |
warnings.warn( |
| 752 |
"Font at '{0}' could not be loaded. If " |
| 753 |
"possible, install it system wide to make it " |
| 754 |
"available to QtAwesome. The source file to " |
| 755 |
"be manually installed can be found at " |
| 756 |
"'{1}'".format(dst_path, src_path) |
| 757 |
) |
| 758 |
return fonts_directory |
| 759 |
|
| 760 |
|
| 761 |
fontname = os.path.splitext(filename)[0] |
| 762 |
|
| 763 |
|
| 764 |
cb = wintypes.DWORD() |
| 765 |
if gdi32.GetFontResourceInfoW( |
| 766 |
filename, ctypes.byref(cb), None, GFRI_DESCRIPTION |
| 767 |
): |
| 768 |
buf = (ctypes.c_wchar * cb.value)() |
| 769 |
if gdi32.GetFontResourceInfoW( |
| 770 |
filename, ctypes.byref(cb), buf, GFRI_DESCRIPTION |
| 771 |
): |
| 772 |
fontname = buf.value |
| 773 |
is_truetype = wintypes.BOOL() |
| 774 |
cb.value = ctypes.sizeof(is_truetype) |
| 775 |
gdi32.GetFontResourceInfoW( |
| 776 |
filename, |
| 777 |
ctypes.byref(cb), |
| 778 |
ctypes.byref(is_truetype), |
| 779 |
GFRI_ISTRUETYPE, |
| 780 |
) |
| 781 |
if is_truetype: |
| 782 |
fontname += " (TrueType)" |
| 783 |
try: |
| 784 |
with winreg.OpenKey( |
| 785 |
winreg.HKEY_LOCAL_MACHINE |
| 786 |
if system_wide |
| 787 |
else winreg.HKEY_CURRENT_USER, |
| 788 |
FONTS_REG_PATH, |
| 789 |
0, |
| 790 |
winreg.KEY_SET_VALUE, |
| 791 |
) as key: |
| 792 |
winreg.SetValueEx(key, fontname, 0, winreg.REG_SZ, filename) |
| 793 |
except OSError: |
| 794 |
|
| 795 |
|
| 796 |
|
| 797 |
|
| 798 |
return fonts_directory |
| 799 |
|
| 800 |
return install_fonts_dir |