From eb304c88348fd048b4c057cabb0309dbce808038 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Thu, 8 Nov 2012 19:18:57 +0530 Subject: [PATCH] ... --- src/calibre/utils/fonts/sfnt/cff/table.py | 2 +- src/calibre/utils/fonts/sfnt/cff/writer.py | 61 ++++++++++++++++++++-- 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/src/calibre/utils/fonts/sfnt/cff/table.py b/src/calibre/utils/fonts/sfnt/cff/table.py index accb5f91f3..dc1c737461 100644 --- a/src/calibre/utils/fonts/sfnt/cff/table.py +++ b/src/calibre/utils/fonts/sfnt/cff/table.py @@ -297,7 +297,7 @@ class CFFTable(UnknownTable): # Rebuild character_map with the glyph ids from the subset font character_map.clear() - for code, charname in charset_map: + for code, charname in charset_map.iteritems(): glyph_id = s.charname_map.get(charname, None) if glyph_id: character_map[code] = glyph_id diff --git a/src/calibre/utils/fonts/sfnt/cff/writer.py b/src/calibre/utils/fonts/sfnt/cff/writer.py index cab5707fa0..c89a0206af 100644 --- a/src/calibre/utils/fonts/sfnt/cff/writer.py +++ b/src/calibre/utils/fonts/sfnt/cff/writer.py @@ -7,10 +7,65 @@ __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' __docformat__ = 'restructuredtext en' +from struct import pack +from collections import OrderedDict + +class Index(list): + + def __init__(self): + list.__init__(self) + self.raw = None + + def calcsize(self, largest_offset): + if largest_offset < 0x100: + return 1 + elif largest_offset < 0x10000: + return 2 + elif largest_offset < 0x1000000: + return 3 + return 4 + + def compile(self): + if len(self) == 0: + self.raw = pack(b'>H', 0) + else: + offsets = [1] + for i, obj in enumerate(self): + offsets.append(offsets[-1] + len(obj)) + offsize = self.calcsize(offsets[-1]) + obj_data = b''.join(self) + prefix = pack(b'>HB', len(self), offsize) + + if offsize == 3: + offsets = b''.join(pack(b'>L', x)[1:] for x in offsets) + else: + fmt = {1:'B', 2:'H', 4:'L'}[offsize] + offsets = pack( ('>%d%s'%(len(self), fmt)).encode('ascii'), + *offsets) + + self.raw = prefix + offsets + obj_data + return self.raw + + class Subset(object): - def __init__(self, cff, character_map): + def __init__(self, cff, keep_charnames): self.cff = cff - self.character_map = character_map - self.charname_map = {} + self.keep_charnames = keep_charnames + + # Font names Index + font_names = Index() + font_names.extend(self.cff.font_names) + + # CharStrings Index + char_strings = Index() + self.charname_map = OrderedDict() + + for i in xrange(self.cff.num_glyphs): + cname = self.cff.charset.safe_lookup(i) + if cname in keep_charnames: + char_strings.append(self.cff.char_strings[i]) + self.charname_map[cname] = i + + char_strings.compile()