1# Copyright 2011 Google Inc. All Rights Reserved. 2 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6 7# http://www.apache.org/licenses/LICENSE-2.0 8 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limit 14 15"""Class that generates CMap data from a font using fontTools.ttLib.""" 16 17 18class CMapDataGeneratorXML(object): 19 """Generate CMap table data from an XML. 20 21 Can set the number of CMaps in the XML description and 22 the number of mappings from a CMap. 23 """ 24 25 def __init__(self, wanted_cmap_ids, num_mappings): 26 """CMapDataGeneratorXML constructor. 27 28 Args: 29 wanted_cmap_ids: List of (platform_id, encoding_id) tuples for the CMaps 30 to be dumped. 31 num_mappings: Number of mappings from the CMap that will be output. They 32 are as evenly spread-out as possible. If num_mappings = n and 33 total_mappings is t, every t/n-th mapping.' 34 """ 35 self.wanted_cmap_ids = wanted_cmap_ids 36 self.num_mappings = num_mappings 37 38 def Generate(self, font, document, root_element): 39 self.document = document 40 self.root_element = root_element 41 self.font = font 42 table = self.font['cmap'] 43 root_element.setAttribute('num_cmaps', str(len(table.tables))) 44 45 for cmap_id in self.wanted_cmap_ids: 46 cmap = table.getcmap(cmap_id[0], cmap_id[1]) 47 if not cmap: 48 continue 49 cmap_element = document.createElement('cmap') 50 root_element.appendChild(cmap_element) 51 self.CMapInfoToXML(cmap_element, cmap) 52 53 def CMapInfoToXML(self, cmap_element, cmap): 54 """Converts a CMap info tuple to XML by added data to the cmap_element.""" 55 cmap_element.setAttribute('byte_length', str(cmap.length)) 56 cmap_element.setAttribute('format', str(cmap.format)) 57 cmap_element.setAttribute('platform_id', str(cmap.platformID)) 58 cmap_element.setAttribute('encoding_id', str(cmap.platEncID)) 59 cmap_element.setAttribute('num_chars', str(len(cmap.cmap))) 60 cmap_element.setAttribute('language', str(cmap.language)) 61 cmap_entries = cmap.cmap.items() 62 cmap_entries.sort() 63 increment = len(cmap_entries) / self.num_mappings 64 if increment == 0: 65 increment = 1 66 for i in range(0, len(cmap_entries), increment): 67 entry = cmap_entries[i] 68 mapping_element = self.document.createElement('map') 69 cmap_element.appendChild(mapping_element) 70 mapping_element.setAttribute('char', '0x%05x' % entry[0]) 71 mapping_element.setAttribute('glyph_name', entry[1]) 72 mapping_element.setAttribute('gid', str(self.font.getGlyphID(entry[1]))) 73