/usr/lib/python2.7/dist-packages/qtawesome/iconic_font.py is in python-qtawesome 0.4.4+ds1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | r"""
Iconic Font
===========
A lightweight module handling iconic fonts.
It is designed to provide a simple way for creating QIcons from glyphs.
From a user's viewpoint, the main entry point is the ``IconicFont`` class which
contains methods for loading new iconic fonts with their character map and
methods returning instances of ``QIcon``.
"""
# Standard library imports
from __future__ import print_function
import json
import os
import hashlib
import warnings
# Third party imports
from qtpy.QtCore import QObject, QPoint, QRect, qRound, Qt
from qtpy.QtGui import (QColor, QFont, QFontDatabase, QIcon, QIconEngine,
QPainter, QPixmap)
from qtpy.QtWidgets import QApplication
from six import unichr
# Linux packagers, please set this to True if you want to make qtawesome
# use system fonts
SYSTEM_FONTS = True
_default_options = {
'color': QColor(50, 50, 50),
'color_disabled': QColor(150, 150, 150),
'opacity': 1.0,
'scale_factor': 1.0,
}
def set_global_defaults(**kwargs):
"""Set global defaults for the options passed to the icon painter."""
valid_options = [
'active', 'selected', 'disabled', 'on', 'off',
'on_active', 'on_selected', 'on_disabled',
'off_active', 'off_selected', 'off_disabled',
'color', 'color_on', 'color_off',
'color_active', 'color_selected', 'color_disabled',
'color_on_selected', 'color_on_active', 'color_on_disabled',
'color_off_selected', 'color_off_active', 'color_off_disabled',
'animation', 'offset', 'scale_factor',
]
for kw in kwargs:
if kw in valid_options:
_default_options[kw] = kwargs[kw]
else:
error = "Invalid option '{0}'".format(kw)
raise KeyError(error)
class CharIconPainter:
"""Char icon painter."""
def paint(self, iconic, painter, rect, mode, state, options):
"""Main paint method."""
for opt in options:
self._paint_icon(iconic, painter, rect, mode, state, opt)
def _paint_icon(self, iconic, painter, rect, mode, state, options):
"""Paint a single icon."""
painter.save()
color = options['color']
char = options['char']
color_options = {
QIcon.On: {
QIcon.Normal: (options['color_on'], options['on']),
QIcon.Disabled: (options['color_on_disabled'],
options['on_disabled']),
QIcon.Active: (options['color_on_active'],
options['on_active']),
QIcon.Selected: (options['color_on_selected'],
options['on_selected'])
},
QIcon.Off: {
QIcon.Normal: (options['color_off'], options['off']),
QIcon.Disabled: (options['color_off_disabled'],
options['off_disabled']),
QIcon.Active: (options['color_off_active'],
options['off_active']),
QIcon.Selected: (options['color_off_selected'],
options['off_selected'])
}
}
color, char = color_options[state][mode]
painter.setPen(QColor(color))
# A 16 pixel-high icon yields a font size of 14, which is pixel perfect
# for font-awesome. 16 * 0.875 = 14
# The reason why the glyph size is smaller than the icon size is to
# account for font bearing.
draw_size = 0.875 * qRound(rect.height() * options['scale_factor'])
prefix = options['prefix']
# Animation setup hook
animation = options.get('animation')
if animation is not None:
animation.setup(self, painter, rect)
painter.setFont(iconic.font(prefix, draw_size))
if 'offset' in options:
rect = QRect(rect)
rect.translate(options['offset'][0] * rect.width(),
options['offset'][1] * rect.height())
painter.setOpacity(options.get('opacity', 1.0))
painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char)
painter.restore()
class FontError(Exception):
"""Exception for font errors."""
class CharIconEngine(QIconEngine):
"""Specialization of QIconEngine used to draw font-based icons."""
def __init__(self, iconic, painter, options):
super(CharIconEngine, self).__init__()
self.iconic = iconic
self.painter = painter
self.options = options
def paint(self, painter, rect, mode, state):
self.painter.paint(
self.iconic, painter, rect, mode, state, self.options)
def pixmap(self, size, mode, state):
pm = QPixmap(size)
pm.fill(Qt.transparent)
self.paint(QPainter(pm), QRect(QPoint(0, 0), size), mode, state)
return pm
class IconicFont(QObject):
"""Main class for managing iconic fonts."""
def __init__(self, *args):
"""IconicFont Constructor.
Parameters
----------
``*args``: tuples
Each positional argument is a tuple of 3 or 4 values:
- The prefix string to be used when accessing a given font set,
- The ttf font filename,
- The json charmap filename,
- Optionally, the directory containing these files. When not
provided, the files will be looked for in ``./fonts/``.
"""
super(IconicFont, self).__init__()
self.painter = CharIconPainter()
self.painters = {}
self.fontname = {}
self.charmap = {}
for fargs in args:
self.load_font(*fargs)
def load_font(self, prefix, ttf_filename, charmap_filename, directory=None):
"""Loads a font file and the associated charmap.
If ``directory`` is None, the files will be looked for in ``./fonts/``.
Parameters
----------
prefix: str
Prefix string to be used when accessing a given font set
ttf_filename: str
Ttf font filename
charmap_filename: str
Charmap filename
directory: str or None, optional
Directory for font and charmap files
"""
def hook(obj):
result = {}
for key in obj:
result[key] = unichr(int(obj[key], 16))
return result
if directory is None:
directory = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'fonts')
# Load font
if QApplication.instance() is not None:
id_ = QFontDatabase.addApplicationFont(os.path.join(directory,
ttf_filename))
loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)
if(loadedFontFamilies):
self.fontname[prefix] = loadedFontFamilies[0]
else:
raise FontError(u"Font at '{0}' appears to be empty. "
"If you are on Windows 10, please read "
"https://support.microsoft.com/"
"en-us/kb/3053676 "
"to know how to prevent Windows from blocking "
"the fonts that come with QtAwesome.".format(
os.path.join(directory, ttf_filename)))
with open(os.path.join(directory, charmap_filename), 'r') as codes:
self.charmap[prefix] = json.load(codes, object_hook=hook)
# Verify that vendorized fonts are not corrupt
if not SYSTEM_FONTS:
md5_hashes = {'fontawesome-webfont.ttf':
'a3de2170e4e9df77161ea5d3f31b2668',
'elusiveicons-webfont.ttf':
'207966b04c032d5b873fd595a211582e'}
ttf_hash = md5_hashes.get(ttf_filename, None)
if ttf_hash is not None:
hasher = hashlib.md5()
with open(os.path.join(directory, ttf_filename),
'rb') as f:
content = f.read()
hasher.update(content)
ttf_calculated_hash_code = hasher.hexdigest()
if ttf_calculated_hash_code != ttf_hash:
raise FontError(u"Font is corrupt at: '{0}'".format(
os.path.join(directory, ttf_filename)))
def icon(self, *names, **kwargs):
"""Return a QIcon object corresponding to the provided icon name."""
options_list = kwargs.pop('options', [{}] * len(names))
general_options = kwargs
if len(options_list) != len(names):
error = '"options" must be a list of size {0}'.format(len(names))
raise Exception(error)
if QApplication.instance() is not None:
parsed_options = []
for i in range(len(options_list)):
specific_options = options_list[i]
parsed_options.append(self._parse_options(specific_options,
general_options,
names[i]))
# Process high level API
api_options = parsed_options
return self._icon_by_painter(self.painter, api_options)
else:
warnings.warn("You need to have a running "
"QApplication to use QtAwesome!")
return QIcon()
def _parse_options(self, specific_options, general_options, name):
options = dict(_default_options, **general_options)
options.update(specific_options)
# Handle icons for modes (Active, Disabled, Selected, Normal)
# and states (On, Off)
icon_kw = ['char', 'on', 'off', 'active', 'selected', 'disabled',
'on_active', 'on_selected', 'on_disabled', 'off_active',
'off_selected', 'off_disabled']
char = options.get('char', name)
on = options.get('on', char)
off = options.get('off', char)
active = options.get('active', on)
selected = options.get('selected', active)
disabled = options.get('disabled', char)
on_active = options.get('on_active', active)
on_selected = options.get('on_selected', selected)
on_disabled = options.get('on_disabled', disabled)
off_active = options.get('off_active', active)
off_selected = options.get('off_selected', selected)
off_disabled = options.get('off_disabled', disabled)
icon_dict = {'char': char,
'on': on,
'off': off,
'active': active,
'selected': selected,
'disabled': disabled,
'on_active': on_active,
'on_selected': on_selected,
'on_disabled': on_disabled,
'off_active': off_active,
'off_selected': off_selected,
'off_disabled': off_disabled,
}
names = [icon_dict.get(kw, name) for kw in icon_kw]
prefix, chars = self._get_prefix_chars(names)
options.update(dict(zip(*(icon_kw, chars))))
options.update({'prefix': prefix})
# Handle colors for modes (Active, Disabled, Selected, Normal)
# and states (On, Off)
color = options.get('color')
options.setdefault('color_on', color)
options.setdefault('color_active', options['color_on'])
options.setdefault('color_selected', options['color_active'])
options.setdefault('color_on_active', options['color_active'])
options.setdefault('color_on_selected', options['color_selected'])
options.setdefault('color_on_disabled', options['color_disabled'])
options.setdefault('color_off', color)
options.setdefault('color_off_active', options['color_active'])
options.setdefault('color_off_selected', options['color_selected'])
options.setdefault('color_off_disabled', options['color_disabled'])
return options
def _get_prefix_chars(self, names):
chars = []
for name in names:
if '.' in name:
prefix, n = name.split('.')
if prefix in self.charmap:
if n in self.charmap[prefix]:
chars.append(self.charmap[prefix][n])
else:
error = 'Invalid icon name "{0}" in font "{1}"'.format(
n, prefix)
raise Exception(error)
else:
error = 'Invalid font prefix "{0}"'.format(prefix)
raise Exception(error)
else:
raise Exception('Invalid icon name')
return prefix, chars
def font(self, prefix, size):
"""Return a QFont corresponding to the given prefix and size."""
font = QFont(self.fontname[prefix])
font.setPixelSize(size)
return font
def set_custom_icon(self, name, painter):
"""Associate a user-provided CharIconPainter to an icon name.
The custom icon can later be addressed by calling
icon('custom.NAME') where NAME is the provided name for that icon.
Parameters
----------
name: str
name of the custom icon
painter: CharIconPainter
The icon painter, implementing
``paint(self, iconic, painter, rect, mode, state, options)``
"""
self.painters[name] = painter
def _custom_icon(self, name, **kwargs):
"""Return the custom icon corresponding to the given name."""
options = dict(_default_options, **kwargs)
if name in self.painters:
painter = self.painters[name]
return self._icon_by_painter(painter, options)
else:
return QIcon()
def _icon_by_painter(self, painter, options):
"""Return the icon corresponding to the given painter."""
engine = CharIconEngine(self, painter, options)
return QIcon(engine)
|