Debian Codegraph @

Lib/fontFeatures/shaperLib/Shaper.py

raw
1 """A Python Unicode Shaping Engine."""
2
3 from fontFeatures import FontFeatures
4 from .BaseShaper import BaseShaper
5 from .ArabicShaper import ArabicShaper
6 from .IndicShaper import IndicShaper
7 from .MyanmarShaper import MyanmarShaper
8 from .HangulShaper import HangulShaper
9 from .KhmerShaper import KhmerShaper
10 from .USEShaper import USEShaper
11 import logging
12 import re
13
14
15 class Shaper:
16 """Initialize a shaping engine.
17
18 Args:
19 ff: A :py:class:`fontFeatures.FontFeatures` object.
20 font: A ``Babelfont`` font object.
21 message_function: A function called with a message and buffer object.
22 """
23
24 def __init__(self, ff, font, message_function=None):
25 assert isinstance(ff, FontFeatures)
26 self.fontfeatures = ff
27 self.babelfont = font
28 if message_function:
29 self.msg = message_function
30 else:
31 self.msg = self.default_message_function
32
33 def execute(self, buf, features=[]):
34 """Run the shaper on a given buffer.
35
36 Args:
37 buf: :py:class:`fontFeatures.shaperLib.buffer.Buffer` object.
38 features: either a list of feature tags or a feature string ("+foox,-barx")
39 """
40 # Choose complex shaper
41 self.complexshaper = self.categorize(buf)(self, self.babelfont, buf, features)
42 self.msg("Using %s" % type(self.complexshaper).__name__)
43 self.stages = [[]]
44 if isinstance(features, str):
45 self.user_features = self._parse_user_feature_string(features)
46 else:
47 self.user_features = features
48 self.collect_features(buf)
49 self.complexshaper.shape()
50 buf.clear_mask()
51 return buf
52
53 def default_message_function(self, msg, buffer=None, serialize_options=None):
54 """A logger function to be used if one is not provided in the constructor.
55
56 By default, debugging and informational log messages are reported to the
57 ``fontFeatures.shaperLib`` facility."""
58 ser = ""
59 if buffer:
60 ser = buffer.serialize(additional=serialize_options)
61 msg = msg + " : " + ser
62 logging.getLogger("fontFeatures.shaperLib").info(msg)
63
64 def _parse_user_feature_string(self, features):
65 features = features.split(",")
66 outfeat = []
67 for f in features:
68 f = f.rstrip()
69 m = re.match(r"^([+\-]?)(\w+)", f)
70 if m:
71 outfeat.append({"tag": m[2], "value": m[1] != "-"})
72 continue
73 m = re.match(r"^(\w+)=([10])", f)
74 if m:
75 outfeat.append({"tag": m[1], "value": m[2] == "1"})
76 else:
77 outfeat.append({"tag": f, "value": True})
78 return outfeat
79
80 def add_pause(self, thing=None):
81 """Add a pause in the shaping stage. Used internally."""
82 if thing:
83 self.stages.append(thing)
84 self.stages.append([])
85
86 def add_features(self, *tags):
87 """Adds feature tags to the current shaping stage."""
88 for t in tags:
89 if any([isinstance(x, list) and t in x for x in self.stages]):
90 continue
91 self.stages[-1].append(t)
92
93 def disable_feature(self, tag):
94 """Removes a feature from processing."""
95 for s in self.stages:
96 if isinstance(s, list) and tag in s:
97 s.remove(tag)
98
99 def collect_features(self, buf):
100 """Determine the features, and their order, to process the buffer."""
101 self.add_features("rvrn")
102 self.add_pause()
103 if buf.direction == "LTR":
104 self.add_features("ltra", "ltrm")
105 elif buf.direction == "RTL":
106 self.add_features("rtla", "rtlm")
107 self.add_features("frac", "numr", "dnom", "rand")
108 # trak?
109 self.complexshaper.collect_features(self)
110 # common features
111 self.add_features("abvm", "blwm", "ccmp", "locl", "mark", "mkmk", "rlig")
112 if buf.direction == "LTR" or buf.direction == "RTL":
113 self.add_features("calt", "clig", "curs", "dist", "kern", "liga", "rclt")
114 else:
115 self.add_features("vert")
116 for uf in self.user_features:
117 if not uf["value"]: # Turn it off if it's already on
118 self.disable_feature(uf["tag"])
119 else:
120 self.add_features(uf["tag"])
121 if hasattr(self.complexshaper, "override_features"):
122 self.complexshaper.override_features(self)
123
124 def categorize(self, buf):
125 """Returns the appropriate complex shaper class to shape this buffer."""
126 if buf.script == "Arabic":
127 return ArabicShaper
128
129 connected_scripts = {
130 "Mongolian": "mong",
131 "Syriac": "syrc",
132 "Nko": "nko ",
133 "Phags_Pa": "phag",
134 "Mandaic": "mand",
135 "Manichaean": "mand",
136 "Psalter_Pahlavi": "phlp",
137 "Adlam": "adlm",
138 "Hanifi_Rohingya": "rohg",
139 "Sogdian": "sogd",
140 }
141 if buf.script in connected_scripts:
142 if self.fontfeatures.hasScriptSupport(connected_scripts[buf.script]):
143 return ArabicShaper
144 else:
145 return BaseShaper
146
147 # if buf.script in ["Thai", "Lao"]:
148 # return ThaiShaper
149 if buf.script == "Hangul":
150 return HangulShaper
151 # if buf.script == "Hebrew":
152 # return HebrewShaper
153 if buf.script in [
154 "Bengali",
155 "Devanagari",
156 "Gujarati",
157 "Gurmukhi",
158 "Kannada",
159 "Malayalam",
160 "Oriya",
161 "Tamil",
162 "Telugu",
163 "Sinhala",
164 ]:
165 indic23map = {
166 "Bengali": "bng",
167 "Devanagari": "dev",
168 "Gujarati": "gjr",
169 "Gurmukhi": "gur",
170 "Kannada": "knd",
171 "Malayalam": "mlm",
172 "Oriya": "ory",
173 "Tamil": "tml",
174 "Telugu": "tel",
175 }
176 # Sinhala is different
177 if buf.script in indic23map and self.fontfeatures.hasScriptSupport(
178 indic23map[buf.script] + "3"
179 ):
180 return USEShaper
181 else:
182 return IndicShaper
183 if buf.script == "Khmer":
184 return KhmerShaper
185
186 if buf.script == "Myanmar":
187 if self.fontfeatures.hasScriptSupport("mymr"):
188 return BaseShaper
189 else:
190 return MyanmarShaper
191
192 # if buf.script = "Qaag": return MyanmarZawgyiShaper
193 if buf.script in [
194 "Tibetan",
195 "Buhid",
196 "Hanunoo",
197 "Tagalog",
198 "Tagbanwa",
199 "Limbu",
200 "Tai_Le",
201 "Buginese",
202 "Kharoshthi",
203 "Syloti_Nagri",
204 "Tifinagh",
205 "Balinese",
206 "Cham",
207 "Kayah_Li",
208 "Lepcha",
209 "Rejang",
210 "Saurashtra",
211 "Sundanese",
212 "Egyptian_Hieroglyphs",
213 "Javanese",
214 "Kaithi",
215 "Meetei_Mayek",
216 "Tai_Tham",
217 "Tai_Viet",
218 "Batak",
219 "Brahmi",
220 "Chakma",
221 "Sharada",
222 "Takri",
223 "Duployan",
224 "Grantha",
225 "Khojki",
226 "Khudawadi",
227 "Mahajani",
228 "Modi",
229 "Pahawh_Hmong",
230 "Siddham",
231 "Tirhuta",
232 "Ahom",
233 "Bhaiksuki",
234 "Marchen",
235 "Newa",
236 "Masaram_Gondi",
237 "Soyombo",
238 "Zanabazar_Square",
239 "Dogra",
240 "Gunjala_Gondi",
241 "Makasar",
242 "Nandinagari",
243 ]:
244 return USEShaper
245 return BaseShaper
246
247
248 def _script_direction(script):
249 if script in [
250 "Arabic",
251 "Hebrew",
252 "Syriac",
253 "Thaana",
254 "Cypriot",
255 "Kharoshthi",
256 "Phoenician",
257 "Nko",
258 "Lydian",
259 "Avestan",
260 "Imperial_Aramaic",
261 "Inscriptional_Parthian",
262 "Inscriptional_Pahlavi",
263 "Old_South_Arabian",
264 "Old_Turkic",
265 "Samaritan",
266 "Mandaic",
267 "Meroitic_Cursive",
268 "Meroitic_Hieroglyphs",
269 "Manichaean",
270 "Mende_Kikakui",
271 "Nabataean",
272 "Old_North_Arabian",
273 "Palmyrene",
274 "Psalter_Pahlavi",
275 "Hatran",
276 "Adlam",
277 "Hanifi_Rohingya",
278 "Old_Sogdian",
279 "Sogdian",
280 "Elymaic",
281 "Chorasmian",
282 "Yezidi",
283 ]:
284 return "RTL"
285 if script in ["Old_Hungarian", "Old_Italic", "Runic"]:
286 return "invalid"
287 return "LTR"