Debian Codegraph @

Lib/fontFeatures/shaperLib/Buffer.py

raw
1 from dataclasses import dataclass
2 from fontFeatures import ValueRecord
3 from fontFeatures.utils import categorize_glyph
4 from youseedee import ucd_data
5 import sys
6 import warnings
7
8
9 def _add_value_records(vr1, vr2):
10 if vr1.xPlacement or vr2.xPlacement:
11 vr1.xPlacement = (vr1.xPlacement or 0) + (vr2.xPlacement or 0)
12 if vr1.yPlacement or vr2.yPlacement:
13 vr1.yPlacement = (vr1.yPlacement or 0) + (vr2.yPlacement or 0)
14 if vr1.xAdvance or vr2.xAdvance:
15 vr1.xAdvance = (vr1.xAdvance or 0) + (vr2.xAdvance or 0)
16 if vr1.yAdvance or vr2.yAdvance:
17 vr1.yAdvance = (vr1.yAdvance or 0) + (vr2.yAdvance or 0)
18
19
20 @dataclass
21 class BufferItem:
22 # codepoint: int
23 # glyph: str
24 # position: ValueRecord
25 # category: str
26
27 def __repr__(self):
28 s = ""
29 if self.glyph:
30 s = self.glyph
31 if self.category[0] == "base":
32 s = s + "_"
33 elif self.category[0] == "mark":
34 s = s + "^"
35 elif self.category[0] == "ligature":
36 s = s + "(fi)"
37 else:
38 s = s + "?"
39 else:
40 s = "U+%04x" % self.codepoint
41 return "BufferItem(%s)" % s
42
43 @classmethod
44 def new_unicode(klass, codepoint):
45 self = klass()
46 self.codepoint = codepoint
47 self.glyph = None
48 self.feature_masks = {}
49 return self
50
51 @classmethod
52 def new_glyph(klass, glyph, font):
53 self = klass()
54 self.codepoint = None
55 self.glyph = glyph
56 self.feature_masks = {}
57 self.prep_glyph(font)
58 return self
59
60 def map_to_glyph(self, font):
61 if not self.glyph:
62 self.glyph = font.unicode_map.get(self.codepoint)
63 if not self.glyph:
64 # Notdef
65 self.glyph = list(font.glyphs.keys())[0]
66 self.prep_glyph(font)
67
68 def prep_glyph(self, font):
69 if "pytest" in sys.modules:
70 if self.glyph in font.exported_glyphs():
71 self.gid = font.exported_glyphs().index(self.glyph)
72 else:
73 self.gid = -1 # ?
74 self.substituted = False
75 self.ligated = False
76 self.multiplied = False
77 self.recategorize(font)
78 try:
79 self.position = ValueRecord(xAdvance=0)
80 self.position.xAdvance = font.default_master.get_glyph_layer(
81 self.glyph
82 ).width
83 except Exception:
84 if "pytest" in sys.modules:
85 # We tolerate broken fonts in pytest
86 pass
87 else:
88 raise ValueError(
89 "Could not get xAdvance for glyph %s (%i)"
90 % (self.glyph, self.codepoint)
91 )
92
93 def recategorize(self, font):
94 try:
95 self.category = categorize_glyph(font, self.glyph)
96 if not self.category[0]:
97 self.category = ("unknown", None)
98 except Exception as e:
99 warnings.warn("Error getting category: %s" % str(e))
100 self._fallback_categorize()
101
102 def _fallback_categorize(self):
103 if not self.codepoint:
104 # Now what?
105 self.category = ("unknown", None)
106 return
107 genCat = ucd_data(self.codepoint).get("General_Category", "L")
108 if genCat[0] == "M":
109 self.category = ("mark", None)
110 elif genCat == "Ll":
111 self.category = ("ligature", None)
112 elif genCat[0] == "L":
113 self.category = ("base", None)
114 else:
115 self.category = ("unknown", None)
116
117 def add_position(self, vr2):
118 _add_value_records(self.position, vr2)
119
120
121 class Buffer:
122 """A buffer holding either characters to be shaped or shaped glyphs."""
123
124 itemclass = BufferItem
125
126 def __init__(
127 self, font, glyphs=[], unicodes=[], direction=None, script=None, language=None
128 ):
129 self.font = font
130 self.direction = direction
131 self.script = script
132 self.language = language
133 self.fallback_mark_positioning = False
134 self.fallback_glyph_classes = False
135 self.items = []
136 self.mask = []
137 self.flags = 0
138 self.current_feature_mask = None
139 if glyphs:
140 self.store_glyphs(glyphs)
141 self.clear_mask()
142 elif unicodes:
143 self.store_unicode(unicodes)
144 self.guess_segment_properties()
145
146 def store_glyphs(self, glyphs):
147 """Initialize the buffer with list of glyphs.
148
149 Args:
150 glyphs (list): A list of glyph names.
151 """
152 self.items = [self.itemclass.new_glyph(g, self.font) for g in glyphs]
153
154 def store_unicode(self, unistring):
155 """Initialize the buffer with list of Unicode codepoints.
156
157 Args:
158 glyphs (list or str): A list of characters.
159 """
160 self.items = [self.itemclass.new_unicode(ord(char)) for char in unistring]
161
162 def guess_segment_properties(self):
163 """Try to automatically determine the script and direction properties."""
164 for u in self.items:
165 # Guess segment properties
166 if not self.script:
167 thisScript = ucd_data(u.codepoint)["Script"]
168 if thisScript not in ["Common", "Unknown", "Inherited"]:
169 self.script = thisScript
170 if not self.direction:
171 from fontFeatures.shaperLib.Shaper import _script_direction
172
173 self.direction = _script_direction(self.script)
174
175 def map_to_glyphs(self):
176 """Convert a buffer of codepoints to its initial glyph mapping."""
177 for u in self.items:
178 u.map_to_glyph(self.font)
179 self.clear_mask()
180
181 @property
182 def is_all_glyphs(self):
183 """Returns true if the contents are glyph items."""
184 return all([x.glyph is not None for x in self.items])
185
186 @property
187 def is_all_unicodes(self):
188 """Returns true if the contents are character items."""
189 return all([x.codepoint is not None for x in self.items])
190
191 def __getitem__(self, key):
192 indexed = self.mask[key]
193 if isinstance(indexed, range) or isinstance(indexed, slice):
194 indexed = slice(indexed.start, indexed.stop, indexed.step)
195 if isinstance(indexed, list):
196 return [self.items[g] for g in indexed]
197 return self.items[indexed]
198
199 def __setitem__(self, key, value):
200 indexed = self.mask[key]
201 if len(indexed) == 1: # Easy
202 self.items[indexed[0] : indexed[0] + 1] = value
203 return
204 if len(value) == 1: # Also easy
205 self.items[indexed[0]] = value[0]
206 for i in reversed(indexed[1:]):
207 del self.items[i]
208 return
209 else:
210 raise ValueError("Too hard :-(")
211
212 def __len__(self):
213 return len(self.mask)
214
215 def update(self):
216 """Categorises glyphs and recomputes masks.
217
218 Called internally when the contents of the buffer changes."""
219 for g in self.items:
220 g.recategorize(self.font)
221 self.recompute_mask()
222
223 def clear_mask(self):
224 """Clear the buffer mask."""
225 self.flags = 0
226 self.markFilteringSet = None
227 self.markAttachmentSet = None
228 self.current_feature_mask = None
229 self.recompute_mask()
230
231 def set_mask(self, flags, markFilteringSet=None, markAttachmentSet=None):
232 """Apply a routine's flags and mark filtering set to the buffer."""
233 self.flags = flags
234 if self.flags & 0x10:
235 assert markFilteringSet
236 self.markFilteringSet = markFilteringSet
237 if self.flags & 0xFF00:
238 assert markAttachmentSet
239 self.markAttachmentSet = markAttachmentSet
240 self.recompute_mask()
241
242 def recompute_mask(self):
243 """Computes the mask property
244
245 ``buffer.mask`` is a list of buffer item indices which is the current
246 "view" of the buffer. For example, if ``buffer.flags == 0x8``, then the
247 indices of all mark glyphs will be excluded from ``buffer.mask``.
248 """
249 mask = range(0, len(self.items))
250 self.flags = self.flags or 0
251 if self.flags & 0x2: # IgnoreBases
252 mask = list(filter(lambda ix: self.items[ix].category[0] != "base", mask))
253 if self.flags & 0x4: # IgnoreLigatures
254 mask = list(
255 filter(lambda ix: self.items[ix].category[0] != "ligature", mask)
256 )
257 if self.flags & 0x8: # IgnoreMarks
258 mask = list(filter(lambda ix: self.items[ix].category[0] != "mark", mask))
259 if self.flags & 0x10: # UseMarkFilteringSet
260 mask = list(
261 filter(
262 lambda ix: self.items[ix].category[0] != "mark"
263 or self.items[ix].glyph in self.markFilteringSet,
264 mask,
265 )
266 )
267 if self.flags & 0xFF00: # MarkAttachmentType
268 mask = list(
269 filter(
270 lambda ix: self.items[ix].category[0] != "mark"
271 or self.items[ix].glyph in self.markAttachmentSet,
272 mask,
273 )
274 )
275
276 if self.current_feature_mask:
277 feature = self.current_feature_mask
278 mask = list(
279 filter(
280 lambda ix: (feature not in self.items[ix].feature_masks)
281 or (not self.items[ix].feature_masks[feature]),
282 mask,
283 )
284 )
285 self.mask = mask
286
287 def set_feature_mask(self, feature):
288 """Applies the mask for a particular feature."""
289 self.current_feature_mask = feature
290 self.recompute_mask()
291
292 def move_item(self, src, dest):
293 """Moves an item from src to dest."""
294 self.items[dest:dest] = [self.items.pop(src)]
295
296 def merge_clusters(self, start, end):
297 """Currently unimplemented."""
298 pass # XXX
299
300 def serialize(self, additional=None, position=True, names=True, ned=False):
301 """Serialize a buffer to a string.
302
303 Returns:
304 The contents of the given buffer in a string format similar to
305 that used by ``hb-shape``.
306
307 """
308 outs = []
309 if additional:
310 if not isinstance(additional, list):
311 additional = [additional]
312 else:
313 additional = []
314 xcursor = 0
315 for ix, info in enumerate(self.items):
316 if hasattr(info, "glyph") and info.glyph:
317 if names:
318 outs.append("%s" % info.glyph)
319 else:
320 outs.append("%s" % info.gid)
321 else:
322 outs.append("U+%04x" % info.codepoint)
323 if ned:
324 position = info.position
325 if xcursor + (position.xPlacement or 0):
326 outs[-1] = outs[-1] + "@%i,%i" % (
327 xcursor + (position.xPlacement or 0),
328 position.yPlacement or 0,
329 )
330 xcursor = xcursor + position.xAdvance
331 elif position and hasattr(info, "position"):
332 position = info.position
333 if hasattr(info, "syllable_index"):
334 cluster = info.syllable_index
335 else:
336 cluster = ix
337 outs[-1] = outs[-1] + "=%i" % (cluster)
338 if position.xPlacement or position.yPlacement:
339 outs[-1] = outs[-1] + "@%i,%i" % (
340 position.xPlacement or 0,
341 position.yPlacement or 0,
342 )
343 outs[-1] = outs[-1] + "+%i" % (position.xAdvance)
344 relevant = list(filter(lambda a: hasattr(info, a), additional))
345 if relevant:
346 outs[-1] = outs[-1] + "(%s)" % ",".join(
347 [str(getattr(info, a)) for a in relevant]
348 )
349 return "|".join(outs)