Skip to content

Commit 1853d3d

Browse files
authored
Merge pull request #60 from dalthviz/validation_for_fonts
PR: Add validation to raise exception when fonts are empty or corrupt
2 parents 8bd01b1 + cad434f commit 1853d3d

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

qtawesome/iconic_font.py

+28-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from __future__ import print_function
1818
import json
1919
import os
20+
import hashlib
2021

2122
# Third party imports
2223
from qtpy.QtCore import QObject, QPoint, QRect, qRound, Qt
@@ -121,6 +122,10 @@ def _paint_icon(self, iconic, painter, rect, mode, state, options):
121122
painter.restore()
122123

123124

125+
class FontError(Exception):
126+
"""Exception for font errors."""
127+
128+
124129
class CharIconEngine(QIconEngine):
125130

126131
"""Specialization of QIconEngine used to draw font-based icons."""
@@ -197,14 +202,35 @@ def hook(obj):
197202
with open(os.path.join(directory, charmap_filename), 'r') as codes:
198203
self.charmap[prefix] = json.load(codes, object_hook=hook)
199204

200-
id_ = QFontDatabase.addApplicationFont(os.path.join(directory, ttf_filename))
205+
md5_hashes = {'fontawesome-webfont.ttf':
206+
'a3de2170e4e9df77161ea5d3f31b2668',
207+
'elusiveicons-webfont.ttf':
208+
'207966b04c032d5b873fd595a211582e'}
209+
ttf_hash = md5_hashes.get(ttf_filename, None)
210+
if ttf_hash is not None:
211+
hasher = hashlib.md5()
212+
with open(os.path.join(directory, ttf_filename), 'rb') as tff_font:
213+
buffer = tff_font.read()
214+
hasher.update(buffer)
215+
ttf_calculated_hash_code = hasher.hexdigest()
216+
if ttf_calculated_hash_code != ttf_hash:
217+
raise FontError(u"Font is corrupt at: '{0}'".format(
218+
os.path.join(directory, ttf_filename)))
219+
220+
id_ = QFontDatabase.addApplicationFont(os.path.join(directory,
221+
ttf_filename))
201222

202223
loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)
203224

204225
if(loadedFontFamilies):
205226
self.fontname[prefix] = loadedFontFamilies[0]
206227
else:
207-
print('Font is empty')
228+
raise FontError(u"Font at '{0}' appears to be empty. "
229+
"If you are on Windows 10, please read "
230+
"https://support.microsoft.com/en-us/kb/3053676 "
231+
"to know how to prevent Windows from blocking "
232+
"the fonts that come with QtAwesome.".format(
233+
os.path.join(directory, ttf_filename)))
208234

209235
def icon(self, *names, **kwargs):
210236
"""

0 commit comments

Comments
 (0)