Debian Codegraph @

Lib/fontFeatures/bin/siesta.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/bin/env python3
2 """Stupid Inefficient Exhaustive Shaping Test Architecture."""
3 import argparse
4 import json
5 import os
6 import random
7 import sys
8 import itertools
9 import re
10
11 import fontFeatures
12 import tqdm
13 from babelfont import load
14 from fontFeatures.shaperLib.Buffer import Buffer
15 from fontFeatures.shaperLib.Shaper import Shaper
16 from fontFeatures.ttLib import unparse
17 from fontTools.ttLib import TTFont
18 from vharfbuzz import Vharfbuzz
19
20 def main(args=None):
21 parser = argparse.ArgumentParser(description="Test coverage of OT features.")
22 subparsers = parser.add_subparsers(required=True, dest="cmd")
23 report = subparsers.add_parser("report")
24 report.add_argument("--suite", help="Test suite to read", metavar="JSON", required=True)
25 report.add_argument("font", metavar="TTF", help="font file")
26
27 generate = subparsers.add_parser("generate")
28 generate.add_argument(
29 "--suite",
30 help="Test suite to update/create (defaults to test.json)",
31 metavar="JSON",
32 default="test.json",
33 )
34 generate.add_argument(
35 "--language",
36 help="Language to pass to shaper",
37 )
38 generate.add_argument(
39 "--only", action="store_true", help="Add \"'only': FONT\" to JSON test cases"
40 )
41 generate.add_argument(
42 "--restrict-unicodes",
43 help="Restrict unicodes to the given range(s, comma separated)",
44 metavar="RANGE",
45 )
46 generate.add_argument(
47 "--just-blobs",
48 action="store_true",
49 help="Only use glyph sequences known to trigger rules",
50 )
51 generate.add_argument(
52 "--no-dotted-circle",
53 action="store_true",
54 help="Don't add tests with dotted circles",
55 )
56 generate.add_argument(
57 "--string-length",
58 type=int,
59 default=5,
60 help="Maximum string length",
61 )
62 generate.add_argument("font", metavar="TTF", help="font file")
63 args = parser.parse_args(args)
64
65
66 def restrict(unicodes, range_arg):
67 allowable = set()
68 ranges = range_arg.split(",")
69 for r in ranges:
70 m = re.match(r"\s*([0-9A-Fa-f]+)-([0-9A-Fa-f]+)", r)
71 if not m:
72 raise ValueError(f"Could not understand range {r}")
73 for cp in range(int(m[1], 16), int(m[2], 16) + 1):
74 allowable.add(chr(cp))
75 return set(allowable) & set(unicodes)
76
77
78 font = TTFont(args.font)
79 ff = unparse(font)
80 bbfont = load(args.font)
81 num_routines = 0
82 num_rules = 0
83
84
85 # Monkeypatch shaperLib functions
86 def wrap_do_apply(fn):
87 def result(*args, **kwargs):
88 fn.__self__.applied = True
89 fn.__self__.parent.applied = True
90 return fn(*args, **kwargs)
91
92 return result
93
94
95 for r in ff.routines:
96 r.applied = False
97 num_routines += 1
98 for rule in r.rules:
99 rule.applied = False
100 rule.parent = r
101 rule._do_apply = wrap_do_apply(rule._do_apply)
102 num_rules += 1
103
104
105 def count_triggered(ff):
106 num_triggered_routines = 0
107 num_triggered_rules = 0
108 for r in ff.routines:
109 if r.applied:
110 num_triggered_routines += 1
111 for rule in r.rules:
112 if rule.applied:
113 num_triggered_rules += 1
114 return num_triggered_routines, num_triggered_rules
115
116
117 num_triggered_routines = 0
118 num_triggered_rules = 0
119
120 shaper = Shaper(ff, bbfont)
121
122 unicodes = list(font.getBestCmap().keys())
123
124 dotted_circle = font.getBestCmap().get(0x25CC)
125
126 if args.cmd == "generate":
127 # Remove those not involved in rules?
128 # Complex shapers may mess this up?
129 involved = set()
130 reversecmap = font["cmap"].buildReversed()
131
132 blobs = []
133 for r in ff.routines:
134 try:
135 involved = involved | r.involved_glyphs
136 except Exception:
137 pass
138 for rule in r.rules:
139 if isinstance(rule, fontFeatures.Attachment):
140 fullinput = [list(rule.bases.keys())] + [list(rule.marks.keys())]
141 else:
142 fullinput = (
143 rule.precontext
144 + getattr(rule, "input", [])
145 + getattr(rule, "glyphs", [])
146 + rule.postcontext
147 )
148 allowable = []
149 for slot in fullinput:
150 this_slot = []
151 for x in slot:
152 if x in reversecmap:
153 this_slot.extend([chr(c) for c in reversecmap[x]])
154 allowable.append(this_slot)
155 if all(allowable):
156 blobs.extend(["".join(blob) for blob in itertools.product(*allowable)])
157
158 unicodes = [c for c in unicodes if font.getBestCmap()[c] in involved]
159 unicodes = [chr(c) for c in unicodes]
160 if args.restrict_unicodes:
161 unicodes = list(restrict(unicodes, args.restrict_unicodes))
162 if args.just_blobs:
163 unicodes = []
164 unicodes.extend(blobs)
165
166
167 rule = tqdm.tqdm(
168 total=num_rules,
169 position=1,
170 colour="green",
171 desc="Rules ",
172 bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt}",
173 )
174 routine = tqdm.tqdm(
175 total=num_routines,
176 position=2,
177 colour="yellow",
178 desc="Lookups",
179 bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt}",
180 )
181 vh = Vharfbuzz(args.font)
182
183
184 def run_a_test(string, tests=None, output=True):
185 global num_triggered_routines
186 global num_triggered_rules
187 buf = Buffer(bbfont, unicodes=string)#,language=args.language)
188 try:
189 shaper.execute(buf)
190 except Exception:
191 return False
192
193 if dotted_circle and args.no_dotted_circle:
194 # Check HB, FF shaper doesn't always add dotted circles
195 buf2 = vh.shape(string)
196 if dotted_circle in vh.serialize_buf(buf2):
197 return False
198
199 new_triggered_routines, new_triggered_rules = count_triggered(ff)
200 if (
201 new_triggered_routines > num_triggered_routines
202 or new_triggered_rules > num_triggered_rules
203 ):
204 if output:
205 routine.write(string)
206 if tests is not None:
207 tests.append({"input": string})
208 rule.n = 0
209 rule.update(new_triggered_rules)
210 routine.n = 0
211 routine.update(new_triggered_routines)
212 num_triggered_rules = new_triggered_rules
213 num_triggered_routines = new_triggered_routines
214 return new_triggered_rules == num_rules # Done?
215
216
217 tests = []
218 suite = {"tests": []}
219 if args.suite and os.path.exists(args.suite):
220 suite = json.load(open(args.suite))
221 if "tests" not in suite:
222 suite["tests"] = []
223 for t in suite["tests"]:
224 if "only" in t and os.path.basename(args.font) != t["only"]:
225 continue
226 run_a_test(t["input"], tests=None, output=False)
227
228 if args.cmd == "report":
229 sys.exit(0)
230
231 new_tests = []
232
233 try:
234 while True:
235 string = "".join(
236 random.choices(unicodes, k=random.randint(2, args.string_length))
237 )
238 if run_a_test(string, tests=new_tests, output=True):
239 break
240 except KeyboardInterrupt as e:
241 pass
242
243 fh = open(args.suite, "w")
244 params = {}
245 if args.language:
246 params["language"] = args.language
247 # Use HB for gold-standard output
248 for test in new_tests:
249 buf = vh.shape(test["input"],parameters=params)
250 test["expectation"] = vh.serialize_buf(buf)
251 if args.only:
252 test["only"] = os.path.basename(args.font)
253 test["note"] = "Added by SIESTA"
254 for k,v in params.items():
255 test[k] = v
256
257 suite["tests"].extend(new_tests)
258 json.dump(suite, fh, sort_keys=True, indent=4, ensure_ascii=False)
259
260 print("The following lookups were not triggered:")
261 for r in ff.routines:
262 if not r.applied:
263 print(r.asFea())
264 sys.exit(0)
265
266 if __name__ == "__main__":
267 main()