interpolatablePlot.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. from fontTools.ttLib import TTFont
  2. from fontTools.pens.recordingPen import (
  3. RecordingPen,
  4. DecomposingRecordingPen,
  5. RecordingPointPen,
  6. )
  7. from fontTools.pens.boundsPen import ControlBoundsPen
  8. from fontTools.pens.cairoPen import CairoPen
  9. from fontTools.pens.pointPen import (
  10. SegmentToPointPen,
  11. PointToSegmentPen,
  12. ReverseContourPointPen,
  13. )
  14. from fontTools.varLib.interpolatable import (
  15. PerContourOrComponentPen,
  16. SimpleRecordingPointPen,
  17. LerpGlyphSet,
  18. )
  19. from itertools import cycle
  20. from functools import wraps
  21. from io import BytesIO
  22. import cairo
  23. import math
  24. import os
  25. import logging
  26. log = logging.getLogger("fontTools.varLib.interpolatable")
  27. class OverridingDict(dict):
  28. def __init__(self, parent_dict):
  29. self.parent_dict = parent_dict
  30. def __missing__(self, key):
  31. return self.parent_dict[key]
  32. class InterpolatablePlot:
  33. width = 640
  34. height = 480
  35. pad = 16
  36. line_height = 36
  37. page_number = 1
  38. head_color = (0.3, 0.3, 0.3)
  39. label_color = (0.2, 0.2, 0.2)
  40. border_color = (0.9, 0.9, 0.9)
  41. border_width = 1
  42. fill_color = (0.8, 0.8, 0.8)
  43. stroke_color = (0.1, 0.1, 0.1)
  44. stroke_width = 2
  45. oncurve_node_color = (0, 0.8, 0, 0.7)
  46. oncurve_node_diameter = 10
  47. offcurve_node_color = (0, 0.5, 0, 0.7)
  48. offcurve_node_diameter = 8
  49. handle_color = (0, 0.5, 0, 0.7)
  50. handle_width = 1
  51. corrected_start_point_color = (0, 0.9, 0, 0.7)
  52. corrected_start_point_size = 15
  53. wrong_start_point_color = (1, 0, 0, 0.7)
  54. start_point_color = (0, 0, 1, 0.7)
  55. start_arrow_length = 20
  56. kink_point_size = 10
  57. kink_point_color = (1, 0, 1, 0.7)
  58. kink_circle_size = 25
  59. kink_circle_stroke_width = 1.5
  60. kink_circle_color = (1, 0, 1, 0.7)
  61. contour_colors = ((1, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 0), (1, 0, 1), (0, 1, 1))
  62. contour_alpha = 0.5
  63. weight_issue_contour_color = (0, 0, 0, 0.4)
  64. no_issues_label = "Your font's good! Have a cupcake..."
  65. no_issues_label_color = (0, 0.5, 0)
  66. cupcake_color = (0.3, 0, 0.3)
  67. cupcake = r"""
  68. ,@.
  69. ,@.@@,.
  70. ,@@,.@@@. @.@@@,.
  71. ,@@. @@@. @@. @@,.
  72. ,@@@.@,.@. @. @@@@,.@.@@,.
  73. ,@@.@. @@.@@. @,. .@' @' @@,
  74. ,@@. @. .@@.@@@. @@' @,
  75. ,@. @@. @,
  76. @. @,@@,. , .@@,
  77. @,. .@,@@,. .@@,. , .@@, @, @,
  78. @. .@. @ @@,. , @
  79. @,.@@. @,. @@,. @. @,. @'
  80. @@||@,. @'@,. @@,. @@ @,. @'@@, @'
  81. \\@@@@' @,. @'@@@@' @@,. @@@' //@@@'
  82. |||||||| @@,. @@' ||||||| |@@@|@|| ||
  83. \\\\\\\ ||@@@|| ||||||| ||||||| //
  84. ||||||| |||||| |||||| |||||| ||
  85. \\\\\\ |||||| |||||| |||||| //
  86. |||||| ||||| ||||| ||||| ||
  87. \\\\\ ||||| ||||| ||||| //
  88. ||||| |||| ||||| |||| ||
  89. \\\\ |||| |||| |||| //
  90. ||||||||||||||||||||||||
  91. """
  92. emoticon_color = (0, 0.3, 0.3)
  93. shrug = r"""\_(")_/"""
  94. underweight = r"""
  95. o
  96. /|\
  97. / \
  98. """
  99. overweight = r"""
  100. o
  101. /O\
  102. / \
  103. """
  104. yay = r""" \o/ """
  105. def __init__(self, out, glyphsets, names=None, **kwargs):
  106. self.out = out
  107. self.glyphsets = glyphsets
  108. self.names = names or [repr(g) for g in glyphsets]
  109. for k, v in kwargs.items():
  110. if not hasattr(self, k):
  111. raise TypeError("Unknown keyword argument: %s" % k)
  112. setattr(self, k, v)
  113. def __enter__(self):
  114. return self
  115. def __exit__(self, type, value, traceback):
  116. pass
  117. def set_size(self, width, height):
  118. raise NotImplementedError
  119. def show_page(self):
  120. self.page_number += 1
  121. def total_width(self):
  122. return self.width * 2 + self.pad * 3
  123. def total_height(self):
  124. return (
  125. self.pad
  126. + self.line_height
  127. + self.pad
  128. + self.line_height
  129. + self.pad
  130. + 2 * (self.height + self.pad * 2 + self.line_height)
  131. + self.pad
  132. )
  133. def add_title_page(
  134. self, files, *, show_tolerance=True, tolerance=None, kinkiness=None
  135. ):
  136. self.set_size(self.total_width(), self.total_height())
  137. pad = self.pad
  138. width = self.total_width() - 3 * self.pad
  139. height = self.total_height() - 2 * self.pad
  140. x = y = pad
  141. self.draw_label("Problem report for:", x=x, y=y, bold=True, width=width)
  142. y += self.line_height
  143. import hashlib
  144. for file in files:
  145. base_file = os.path.basename(file)
  146. y += self.line_height
  147. self.draw_label(base_file, x=x, y=y, bold=True, width=width)
  148. y += self.line_height
  149. h = hashlib.sha1(open(file, "rb").read()).hexdigest()
  150. self.draw_label("sha1: %s" % h, x=x + pad, y=y, width=width)
  151. y += self.line_height
  152. if file.endswith(".ttf"):
  153. ttFont = TTFont(file)
  154. name = ttFont["name"] if "name" in ttFont else None
  155. if name:
  156. for what, nameIDs in (
  157. ("Family name", (21, 16, 1)),
  158. ("Version", (5,)),
  159. ):
  160. n = name.getFirstDebugName(nameIDs)
  161. if n is None:
  162. continue
  163. self.draw_label(
  164. "%s: %s" % (what, n), x=x + pad, y=y, width=width
  165. )
  166. y += self.line_height
  167. elif file.endswith(".glyphs"):
  168. from glyphsLib import GSFont
  169. f = GSFont(file)
  170. for what, field in (
  171. ("Family name", "familyName"),
  172. ("VersionMajor", "versionMajor"),
  173. ("VersionMinor", "_versionMinor"),
  174. ):
  175. self.draw_label(
  176. "%s: %s" % (what, getattr(f, field)),
  177. x=x + pad,
  178. y=y,
  179. width=width,
  180. )
  181. y += self.line_height
  182. self.draw_legend(
  183. show_tolerance=show_tolerance, tolerance=tolerance, kinkiness=kinkiness
  184. )
  185. self.show_page()
  186. def draw_legend(self, *, show_tolerance=True, tolerance=None, kinkiness=None):
  187. cr = cairo.Context(self.surface)
  188. x = self.pad
  189. y = self.total_height() - self.pad - self.line_height * 2
  190. width = self.total_width() - 2 * self.pad
  191. xx = x + self.pad * 2
  192. xxx = x + self.pad * 4
  193. if show_tolerance:
  194. self.draw_label(
  195. "Tolerance: badness; closer to zero the worse", x=xxx, y=y, width=width
  196. )
  197. y -= self.pad + self.line_height
  198. self.draw_label("Underweight contours", x=xxx, y=y, width=width)
  199. cr.rectangle(xx - self.pad * 0.7, y, 1.5 * self.pad, self.line_height)
  200. cr.set_source_rgb(*self.fill_color)
  201. cr.fill_preserve()
  202. if self.stroke_color:
  203. cr.set_source_rgb(*self.stroke_color)
  204. cr.set_line_width(self.stroke_width)
  205. cr.stroke_preserve()
  206. cr.set_source_rgba(*self.weight_issue_contour_color)
  207. cr.fill()
  208. y -= self.pad + self.line_height
  209. self.draw_label(
  210. "Colored contours: contours with the wrong order", x=xxx, y=y, width=width
  211. )
  212. cr.rectangle(xx - self.pad * 0.7, y, 1.5 * self.pad, self.line_height)
  213. if self.fill_color:
  214. cr.set_source_rgb(*self.fill_color)
  215. cr.fill_preserve()
  216. if self.stroke_color:
  217. cr.set_source_rgb(*self.stroke_color)
  218. cr.set_line_width(self.stroke_width)
  219. cr.stroke_preserve()
  220. cr.set_source_rgba(*self.contour_colors[0], self.contour_alpha)
  221. cr.fill()
  222. y -= self.pad + self.line_height
  223. self.draw_label("Kink artifact", x=xxx, y=y, width=width)
  224. self.draw_circle(
  225. cr,
  226. x=xx,
  227. y=y + self.line_height * 0.5,
  228. diameter=self.kink_circle_size,
  229. stroke_width=self.kink_circle_stroke_width,
  230. color=self.kink_circle_color,
  231. )
  232. y -= self.pad + self.line_height
  233. self.draw_label("Point causing kink in the contour", x=xxx, y=y, width=width)
  234. self.draw_dot(
  235. cr,
  236. x=xx,
  237. y=y + self.line_height * 0.5,
  238. diameter=self.kink_point_size,
  239. color=self.kink_point_color,
  240. )
  241. y -= self.pad + self.line_height
  242. self.draw_label("Suggested new contour start point", x=xxx, y=y, width=width)
  243. self.draw_dot(
  244. cr,
  245. x=xx,
  246. y=y + self.line_height * 0.5,
  247. diameter=self.corrected_start_point_size,
  248. color=self.corrected_start_point_color,
  249. )
  250. y -= self.pad + self.line_height
  251. self.draw_label(
  252. "Contour start point in contours with wrong direction",
  253. x=xxx,
  254. y=y,
  255. width=width,
  256. )
  257. self.draw_arrow(
  258. cr,
  259. x=xx - self.start_arrow_length * 0.3,
  260. y=y + self.line_height * 0.5,
  261. color=self.wrong_start_point_color,
  262. )
  263. y -= self.pad + self.line_height
  264. self.draw_label(
  265. "Contour start point when the first two points overlap",
  266. x=xxx,
  267. y=y,
  268. width=width,
  269. )
  270. self.draw_dot(
  271. cr,
  272. x=xx,
  273. y=y + self.line_height * 0.5,
  274. diameter=self.corrected_start_point_size,
  275. color=self.start_point_color,
  276. )
  277. y -= self.pad + self.line_height
  278. self.draw_label("Contour start point and direction", x=xxx, y=y, width=width)
  279. self.draw_arrow(
  280. cr,
  281. x=xx - self.start_arrow_length * 0.3,
  282. y=y + self.line_height * 0.5,
  283. color=self.start_point_color,
  284. )
  285. y -= self.pad + self.line_height
  286. self.draw_label("Legend:", x=x, y=y, width=width, bold=True)
  287. y -= self.pad + self.line_height
  288. if kinkiness is not None:
  289. self.draw_label(
  290. "Kink-reporting aggressiveness: %g" % kinkiness,
  291. x=xxx,
  292. y=y,
  293. width=width,
  294. )
  295. y -= self.pad + self.line_height
  296. if tolerance is not None:
  297. self.draw_label(
  298. "Error tolerance: %g" % tolerance,
  299. x=xxx,
  300. y=y,
  301. width=width,
  302. )
  303. y -= self.pad + self.line_height
  304. self.draw_label("Parameters:", x=x, y=y, width=width, bold=True)
  305. y -= self.pad + self.line_height
  306. def add_problems(self, problems, *, show_tolerance=True, show_page_number=True):
  307. for glyph, glyph_problems in problems.items():
  308. last_masters = None
  309. current_glyph_problems = []
  310. for p in glyph_problems:
  311. masters = (
  312. p["master_idx"]
  313. if "master_idx" in p
  314. else (p["master_1_idx"], p["master_2_idx"])
  315. )
  316. if masters == last_masters:
  317. current_glyph_problems.append(p)
  318. continue
  319. # Flush
  320. if current_glyph_problems:
  321. self.add_problem(
  322. glyph,
  323. current_glyph_problems,
  324. show_tolerance=show_tolerance,
  325. show_page_number=show_page_number,
  326. )
  327. self.show_page()
  328. current_glyph_problems = []
  329. last_masters = masters
  330. current_glyph_problems.append(p)
  331. if current_glyph_problems:
  332. self.add_problem(
  333. glyph,
  334. current_glyph_problems,
  335. show_tolerance=show_tolerance,
  336. show_page_number=show_page_number,
  337. )
  338. self.show_page()
  339. def add_problem(
  340. self, glyphname, problems, *, show_tolerance=True, show_page_number=True
  341. ):
  342. if type(problems) not in (list, tuple):
  343. problems = [problems]
  344. problem_type = problems[0]["type"]
  345. problem_types = set(problem["type"] for problem in problems)
  346. if not all(pt == problem_type for pt in problem_types):
  347. problem_type = ", ".join(sorted({problem["type"] for problem in problems}))
  348. log.info("Drawing %s: %s", glyphname, problem_type)
  349. master_keys = (
  350. ("master_idx",)
  351. if "master_idx" in problems[0]
  352. else ("master_1_idx", "master_2_idx")
  353. )
  354. master_indices = [problems[0][k] for k in master_keys]
  355. if problem_type == "missing":
  356. sample_glyph = next(
  357. i for i, m in enumerate(self.glyphsets) if m[glyphname] is not None
  358. )
  359. master_indices.insert(0, sample_glyph)
  360. self.set_size(self.total_width(), self.total_height())
  361. x = self.pad
  362. y = self.pad
  363. self.draw_label(
  364. "Glyph name: " + glyphname,
  365. x=x,
  366. y=y,
  367. color=self.head_color,
  368. align=0,
  369. bold=True,
  370. )
  371. tolerance = min(p.get("tolerance", 1) for p in problems)
  372. if tolerance < 1 and show_tolerance:
  373. self.draw_label(
  374. "tolerance: %.2f" % tolerance,
  375. x=x,
  376. y=y,
  377. width=self.total_width() - 2 * self.pad,
  378. align=1,
  379. bold=True,
  380. )
  381. y += self.line_height + self.pad
  382. self.draw_label(
  383. problem_type,
  384. x=x,
  385. y=y,
  386. width=self.total_width() - 2 * self.pad,
  387. color=self.head_color,
  388. align=0.5,
  389. bold=True,
  390. )
  391. y += self.line_height + self.pad
  392. scales = []
  393. for which, master_idx in enumerate(master_indices):
  394. glyphset = self.glyphsets[master_idx]
  395. name = self.names[master_idx]
  396. self.draw_label(name, x=x, y=y, color=self.label_color, align=0.5)
  397. y += self.line_height + self.pad
  398. if glyphset[glyphname] is not None:
  399. scales.append(
  400. self.draw_glyph(glyphset, glyphname, problems, which, x=x, y=y)
  401. )
  402. else:
  403. self.draw_emoticon(self.shrug, x=x, y=y)
  404. y += self.height + self.pad
  405. if any(
  406. pt
  407. in (
  408. "nothing",
  409. "wrong_start_point",
  410. "contour_order",
  411. "kink",
  412. "underweight",
  413. "overweight",
  414. )
  415. for pt in problem_types
  416. ):
  417. x = self.pad + self.width + self.pad
  418. y = self.pad
  419. y += self.line_height + self.pad
  420. y += self.line_height + self.pad
  421. glyphset1 = self.glyphsets[master_indices[0]]
  422. glyphset2 = self.glyphsets[master_indices[1]]
  423. # Draw the mid-way of the two masters
  424. self.draw_label(
  425. "midway interpolation", x=x, y=y, color=self.head_color, align=0.5
  426. )
  427. y += self.line_height + self.pad
  428. midway_glyphset = LerpGlyphSet(glyphset1, glyphset2)
  429. self.draw_glyph(
  430. midway_glyphset,
  431. glyphname,
  432. [{"type": "midway"}]
  433. + [
  434. p
  435. for p in problems
  436. if p["type"] in ("kink", "underweight", "overweight")
  437. ],
  438. None,
  439. x=x,
  440. y=y,
  441. scale=min(scales),
  442. )
  443. y += self.height + self.pad
  444. if any(
  445. pt
  446. in (
  447. "wrong_start_point",
  448. "contour_order",
  449. "kink",
  450. )
  451. for pt in problem_types
  452. ):
  453. # Draw the proposed fix
  454. self.draw_label("proposed fix", x=x, y=y, color=self.head_color, align=0.5)
  455. y += self.line_height + self.pad
  456. overriding1 = OverridingDict(glyphset1)
  457. overriding2 = OverridingDict(glyphset2)
  458. perContourPen1 = PerContourOrComponentPen(
  459. RecordingPen, glyphset=overriding1
  460. )
  461. perContourPen2 = PerContourOrComponentPen(
  462. RecordingPen, glyphset=overriding2
  463. )
  464. glyphset1[glyphname].draw(perContourPen1)
  465. glyphset2[glyphname].draw(perContourPen2)
  466. for problem in problems:
  467. if problem["type"] == "contour_order":
  468. fixed_contours = [
  469. perContourPen2.value[i] for i in problems[0]["value_2"]
  470. ]
  471. perContourPen2.value = fixed_contours
  472. for problem in problems:
  473. if problem["type"] == "wrong_start_point":
  474. # Save the wrong contours
  475. wrongContour1 = perContourPen1.value[problem["contour"]]
  476. wrongContour2 = perContourPen2.value[problem["contour"]]
  477. # Convert the wrong contours to point pens
  478. points1 = RecordingPointPen()
  479. converter = SegmentToPointPen(points1, False)
  480. wrongContour1.replay(converter)
  481. points2 = RecordingPointPen()
  482. converter = SegmentToPointPen(points2, False)
  483. wrongContour2.replay(converter)
  484. proposed_start = problem["value_2"]
  485. # See if we need reversing; fragile but worth a try
  486. if problem["reversed"]:
  487. new_points2 = RecordingPointPen()
  488. reversedPen = ReverseContourPointPen(new_points2)
  489. points2.replay(reversedPen)
  490. points2 = new_points2
  491. proposed_start = len(points2.value) - 2 - proposed_start
  492. # Rotate points2 so that the first point is the same as in points1
  493. beginPath = points2.value[:1]
  494. endPath = points2.value[-1:]
  495. pts = points2.value[1:-1]
  496. pts = pts[proposed_start:] + pts[:proposed_start]
  497. points2.value = beginPath + pts + endPath
  498. # Convert the point pens back to segment pens
  499. segment1 = RecordingPen()
  500. converter = PointToSegmentPen(segment1, True)
  501. points1.replay(converter)
  502. segment2 = RecordingPen()
  503. converter = PointToSegmentPen(segment2, True)
  504. points2.replay(converter)
  505. # Replace the wrong contours
  506. wrongContour1.value = segment1.value
  507. wrongContour2.value = segment2.value
  508. perContourPen1.value[problem["contour"]] = wrongContour1
  509. perContourPen2.value[problem["contour"]] = wrongContour2
  510. for problem in problems:
  511. # If we have a kink, try to fix it.
  512. if problem["type"] == "kink":
  513. # Save the wrong contours
  514. wrongContour1 = perContourPen1.value[problem["contour"]]
  515. wrongContour2 = perContourPen2.value[problem["contour"]]
  516. # Convert the wrong contours to point pens
  517. points1 = RecordingPointPen()
  518. converter = SegmentToPointPen(points1, False)
  519. wrongContour1.replay(converter)
  520. points2 = RecordingPointPen()
  521. converter = SegmentToPointPen(points2, False)
  522. wrongContour2.replay(converter)
  523. i = problem["value"]
  524. # Position points to be around the same ratio
  525. # beginPath / endPath dance
  526. j = i + 1
  527. pt0 = points1.value[j][1][0]
  528. pt1 = points2.value[j][1][0]
  529. j_prev = (i - 1) % (len(points1.value) - 2) + 1
  530. pt0_prev = points1.value[j_prev][1][0]
  531. pt1_prev = points2.value[j_prev][1][0]
  532. j_next = (i + 1) % (len(points1.value) - 2) + 1
  533. pt0_next = points1.value[j_next][1][0]
  534. pt1_next = points2.value[j_next][1][0]
  535. pt0 = complex(*pt0)
  536. pt1 = complex(*pt1)
  537. pt0_prev = complex(*pt0_prev)
  538. pt1_prev = complex(*pt1_prev)
  539. pt0_next = complex(*pt0_next)
  540. pt1_next = complex(*pt1_next)
  541. # Find the ratio of the distance between the points
  542. r0 = abs(pt0 - pt0_prev) / abs(pt0_next - pt0_prev)
  543. r1 = abs(pt1 - pt1_prev) / abs(pt1_next - pt1_prev)
  544. r_mid = (r0 + r1) / 2
  545. pt0 = pt0_prev + r_mid * (pt0_next - pt0_prev)
  546. pt1 = pt1_prev + r_mid * (pt1_next - pt1_prev)
  547. points1.value[j] = (
  548. points1.value[j][0],
  549. (((pt0.real, pt0.imag),) + points1.value[j][1][1:]),
  550. points1.value[j][2],
  551. )
  552. points2.value[j] = (
  553. points2.value[j][0],
  554. (((pt1.real, pt1.imag),) + points2.value[j][1][1:]),
  555. points2.value[j][2],
  556. )
  557. # Convert the point pens back to segment pens
  558. segment1 = RecordingPen()
  559. converter = PointToSegmentPen(segment1, True)
  560. points1.replay(converter)
  561. segment2 = RecordingPen()
  562. converter = PointToSegmentPen(segment2, True)
  563. points2.replay(converter)
  564. # Replace the wrong contours
  565. wrongContour1.value = segment1.value
  566. wrongContour2.value = segment2.value
  567. # Assemble
  568. fixed1 = RecordingPen()
  569. fixed2 = RecordingPen()
  570. for contour in perContourPen1.value:
  571. fixed1.value.extend(contour.value)
  572. for contour in perContourPen2.value:
  573. fixed2.value.extend(contour.value)
  574. fixed1.draw = fixed1.replay
  575. fixed2.draw = fixed2.replay
  576. overriding1[glyphname] = fixed1
  577. overriding2[glyphname] = fixed2
  578. try:
  579. midway_glyphset = LerpGlyphSet(overriding1, overriding2)
  580. self.draw_glyph(
  581. midway_glyphset,
  582. glyphname,
  583. {"type": "fixed"},
  584. None,
  585. x=x,
  586. y=y,
  587. scale=min(scales),
  588. )
  589. except ValueError:
  590. self.draw_emoticon(self.shrug, x=x, y=y)
  591. y += self.height + self.pad
  592. else:
  593. emoticon = self.shrug
  594. if "underweight" in problem_types:
  595. emoticon = self.underweight
  596. elif "overweight" in problem_types:
  597. emoticon = self.overweight
  598. elif "nothing" in problem_types:
  599. emoticon = self.yay
  600. self.draw_emoticon(emoticon, x=x, y=y)
  601. if show_page_number:
  602. self.draw_label(
  603. str(self.page_number),
  604. x=0,
  605. y=self.total_height() - self.line_height,
  606. width=self.total_width(),
  607. color=self.head_color,
  608. align=0.5,
  609. )
  610. def draw_label(
  611. self,
  612. label,
  613. *,
  614. x=0,
  615. y=0,
  616. color=(0, 0, 0),
  617. align=0,
  618. bold=False,
  619. width=None,
  620. height=None,
  621. ):
  622. if width is None:
  623. width = self.width
  624. if height is None:
  625. height = self.height
  626. cr = cairo.Context(self.surface)
  627. cr.select_font_face(
  628. "@cairo:",
  629. cairo.FONT_SLANT_NORMAL,
  630. cairo.FONT_WEIGHT_BOLD if bold else cairo.FONT_WEIGHT_NORMAL,
  631. )
  632. cr.set_font_size(self.line_height)
  633. font_extents = cr.font_extents()
  634. font_size = self.line_height * self.line_height / font_extents[2]
  635. cr.set_font_size(font_size)
  636. font_extents = cr.font_extents()
  637. cr.set_source_rgb(*color)
  638. extents = cr.text_extents(label)
  639. if extents.width > width:
  640. # Shrink
  641. font_size *= width / extents.width
  642. cr.set_font_size(font_size)
  643. font_extents = cr.font_extents()
  644. extents = cr.text_extents(label)
  645. # Center
  646. label_x = x + (width - extents.width) * align
  647. label_y = y + font_extents[0]
  648. cr.move_to(label_x, label_y)
  649. cr.show_text(label)
  650. def draw_glyph(self, glyphset, glyphname, problems, which, *, x=0, y=0, scale=None):
  651. if type(problems) not in (list, tuple):
  652. problems = [problems]
  653. midway = any(problem["type"] == "midway" for problem in problems)
  654. problem_type = problems[0]["type"]
  655. problem_types = set(problem["type"] for problem in problems)
  656. if not all(pt == problem_type for pt in problem_types):
  657. problem_type = "mixed"
  658. glyph = glyphset[glyphname]
  659. recording = RecordingPen()
  660. glyph.draw(recording)
  661. decomposedRecording = DecomposingRecordingPen(glyphset)
  662. glyph.draw(decomposedRecording)
  663. boundsPen = ControlBoundsPen(glyphset)
  664. decomposedRecording.replay(boundsPen)
  665. bounds = boundsPen.bounds
  666. if bounds is None:
  667. bounds = (0, 0, 0, 0)
  668. glyph_width = bounds[2] - bounds[0]
  669. glyph_height = bounds[3] - bounds[1]
  670. if glyph_width:
  671. if scale is None:
  672. scale = self.width / glyph_width
  673. else:
  674. scale = min(scale, self.height / glyph_height)
  675. if glyph_height:
  676. if scale is None:
  677. scale = self.height / glyph_height
  678. else:
  679. scale = min(scale, self.height / glyph_height)
  680. if scale is None:
  681. scale = 1
  682. cr = cairo.Context(self.surface)
  683. cr.translate(x, y)
  684. # Center
  685. cr.translate(
  686. (self.width - glyph_width * scale) / 2,
  687. (self.height - glyph_height * scale) / 2,
  688. )
  689. cr.scale(scale, -scale)
  690. cr.translate(-bounds[0], -bounds[3])
  691. if self.border_color:
  692. cr.set_source_rgb(*self.border_color)
  693. cr.rectangle(bounds[0], bounds[1], glyph_width, glyph_height)
  694. cr.set_line_width(self.border_width / scale)
  695. cr.stroke()
  696. if self.fill_color or self.stroke_color:
  697. pen = CairoPen(glyphset, cr)
  698. decomposedRecording.replay(pen)
  699. if self.fill_color and problem_type != "open_path":
  700. cr.set_source_rgb(*self.fill_color)
  701. cr.fill_preserve()
  702. if self.stroke_color:
  703. cr.set_source_rgb(*self.stroke_color)
  704. cr.set_line_width(self.stroke_width / scale)
  705. cr.stroke_preserve()
  706. cr.new_path()
  707. if "underweight" in problem_types or "overweight" in problem_types:
  708. perContourPen = PerContourOrComponentPen(RecordingPen, glyphset=glyphset)
  709. recording.replay(perContourPen)
  710. for problem in problems:
  711. if problem["type"] in ("underweight", "overweight"):
  712. contour = perContourPen.value[problem["contour"]]
  713. contour.replay(CairoPen(glyphset, cr))
  714. cr.set_source_rgba(*self.weight_issue_contour_color)
  715. cr.fill()
  716. if any(
  717. t in problem_types
  718. for t in {
  719. "nothing",
  720. "node_count",
  721. "node_incompatibility",
  722. }
  723. ):
  724. cr.set_line_cap(cairo.LINE_CAP_ROUND)
  725. # Oncurve nodes
  726. for segment, args in decomposedRecording.value:
  727. if not args:
  728. continue
  729. x, y = args[-1]
  730. cr.move_to(x, y)
  731. cr.line_to(x, y)
  732. cr.set_source_rgba(*self.oncurve_node_color)
  733. cr.set_line_width(self.oncurve_node_diameter / scale)
  734. cr.stroke()
  735. # Offcurve nodes
  736. for segment, args in decomposedRecording.value:
  737. if not args:
  738. continue
  739. for x, y in args[:-1]:
  740. cr.move_to(x, y)
  741. cr.line_to(x, y)
  742. cr.set_source_rgba(*self.offcurve_node_color)
  743. cr.set_line_width(self.offcurve_node_diameter / scale)
  744. cr.stroke()
  745. # Handles
  746. for segment, args in decomposedRecording.value:
  747. if not args:
  748. pass
  749. elif segment in ("moveTo", "lineTo"):
  750. cr.move_to(*args[0])
  751. elif segment == "qCurveTo":
  752. for x, y in args:
  753. cr.line_to(x, y)
  754. cr.new_sub_path()
  755. cr.move_to(*args[-1])
  756. elif segment == "curveTo":
  757. cr.line_to(*args[0])
  758. cr.new_sub_path()
  759. cr.move_to(*args[1])
  760. cr.line_to(*args[2])
  761. cr.new_sub_path()
  762. cr.move_to(*args[-1])
  763. else:
  764. continue
  765. cr.set_source_rgba(*self.handle_color)
  766. cr.set_line_width(self.handle_width / scale)
  767. cr.stroke()
  768. matching = None
  769. for problem in problems:
  770. if problem["type"] == "contour_order":
  771. matching = problem["value_2"]
  772. colors = cycle(self.contour_colors)
  773. perContourPen = PerContourOrComponentPen(
  774. RecordingPen, glyphset=glyphset
  775. )
  776. recording.replay(perContourPen)
  777. for i, contour in enumerate(perContourPen.value):
  778. if matching[i] == i:
  779. continue
  780. color = next(colors)
  781. contour.replay(CairoPen(glyphset, cr))
  782. cr.set_source_rgba(*color, self.contour_alpha)
  783. cr.fill()
  784. for problem in problems:
  785. if problem["type"] in ("nothing", "wrong_start_point"):
  786. idx = problem.get("contour")
  787. # Draw suggested point
  788. if idx is not None and which == 1 and "value_2" in problem:
  789. perContourPen = PerContourOrComponentPen(
  790. RecordingPen, glyphset=glyphset
  791. )
  792. decomposedRecording.replay(perContourPen)
  793. points = SimpleRecordingPointPen()
  794. converter = SegmentToPointPen(points, False)
  795. perContourPen.value[
  796. idx if matching is None else matching[idx]
  797. ].replay(converter)
  798. targetPoint = points.value[problem["value_2"]][0]
  799. cr.save()
  800. cr.translate(*targetPoint)
  801. cr.scale(1 / scale, 1 / scale)
  802. self.draw_dot(
  803. cr,
  804. diameter=self.corrected_start_point_size,
  805. color=self.corrected_start_point_color,
  806. )
  807. cr.restore()
  808. # Draw start-point arrow
  809. if which == 0 or not problem.get("reversed"):
  810. color = self.start_point_color
  811. else:
  812. color = self.wrong_start_point_color
  813. first_pt = None
  814. i = 0
  815. cr.save()
  816. for segment, args in decomposedRecording.value:
  817. if segment == "moveTo":
  818. first_pt = args[0]
  819. continue
  820. if first_pt is None:
  821. continue
  822. if segment == "closePath":
  823. second_pt = first_pt
  824. else:
  825. second_pt = args[0]
  826. if idx is None or i == idx:
  827. cr.save()
  828. first_pt = complex(*first_pt)
  829. second_pt = complex(*second_pt)
  830. length = abs(second_pt - first_pt)
  831. cr.translate(first_pt.real, first_pt.imag)
  832. if length:
  833. # Draw arrowhead
  834. cr.rotate(
  835. math.atan2(
  836. second_pt.imag - first_pt.imag,
  837. second_pt.real - first_pt.real,
  838. )
  839. )
  840. cr.scale(1 / scale, 1 / scale)
  841. self.draw_arrow(cr, color=color)
  842. else:
  843. # Draw circle
  844. cr.scale(1 / scale, 1 / scale)
  845. self.draw_dot(
  846. cr,
  847. diameter=self.corrected_start_point_size,
  848. color=color,
  849. )
  850. cr.restore()
  851. if idx is not None:
  852. break
  853. first_pt = None
  854. i += 1
  855. cr.restore()
  856. if problem["type"] == "kink":
  857. idx = problem.get("contour")
  858. perContourPen = PerContourOrComponentPen(
  859. RecordingPen, glyphset=glyphset
  860. )
  861. decomposedRecording.replay(perContourPen)
  862. points = SimpleRecordingPointPen()
  863. converter = SegmentToPointPen(points, False)
  864. perContourPen.value[idx if matching is None else matching[idx]].replay(
  865. converter
  866. )
  867. targetPoint = points.value[problem["value"]][0]
  868. cr.save()
  869. cr.translate(*targetPoint)
  870. cr.scale(1 / scale, 1 / scale)
  871. if midway:
  872. self.draw_circle(
  873. cr,
  874. diameter=self.kink_circle_size,
  875. stroke_width=self.kink_circle_stroke_width,
  876. color=self.kink_circle_color,
  877. )
  878. else:
  879. self.draw_dot(
  880. cr,
  881. diameter=self.kink_point_size,
  882. color=self.kink_point_color,
  883. )
  884. cr.restore()
  885. return scale
  886. def draw_dot(self, cr, *, x=0, y=0, color=(0, 0, 0), diameter=10):
  887. cr.save()
  888. cr.set_line_width(diameter)
  889. cr.set_line_cap(cairo.LINE_CAP_ROUND)
  890. cr.move_to(x, y)
  891. cr.line_to(x, y)
  892. if len(color) == 3:
  893. color = color + (1,)
  894. cr.set_source_rgba(*color)
  895. cr.stroke()
  896. cr.restore()
  897. def draw_circle(
  898. self, cr, *, x=0, y=0, color=(0, 0, 0), diameter=10, stroke_width=1
  899. ):
  900. cr.save()
  901. cr.set_line_width(stroke_width)
  902. cr.set_line_cap(cairo.LINE_CAP_SQUARE)
  903. cr.arc(x, y, diameter / 2, 0, 2 * math.pi)
  904. if len(color) == 3:
  905. color = color + (1,)
  906. cr.set_source_rgba(*color)
  907. cr.stroke()
  908. cr.restore()
  909. def draw_arrow(self, cr, *, x=0, y=0, color=(0, 0, 0)):
  910. cr.save()
  911. if len(color) == 3:
  912. color = color + (1,)
  913. cr.set_source_rgba(*color)
  914. cr.translate(self.start_arrow_length + x, y)
  915. cr.move_to(0, 0)
  916. cr.line_to(
  917. -self.start_arrow_length,
  918. -self.start_arrow_length * 0.4,
  919. )
  920. cr.line_to(
  921. -self.start_arrow_length,
  922. self.start_arrow_length * 0.4,
  923. )
  924. cr.close_path()
  925. cr.fill()
  926. cr.restore()
  927. def draw_text(self, text, *, x=0, y=0, color=(0, 0, 0), width=None, height=None):
  928. if width is None:
  929. width = self.width
  930. if height is None:
  931. height = self.height
  932. text = text.splitlines()
  933. cr = cairo.Context(self.surface)
  934. cr.set_source_rgb(*color)
  935. cr.set_font_size(self.line_height)
  936. cr.select_font_face(
  937. "@cairo:monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL
  938. )
  939. text_width = 0
  940. text_height = 0
  941. font_extents = cr.font_extents()
  942. font_line_height = font_extents[2]
  943. font_ascent = font_extents[0]
  944. for line in text:
  945. extents = cr.text_extents(line)
  946. text_width = max(text_width, extents.x_advance)
  947. text_height += font_line_height
  948. if not text_width:
  949. return
  950. cr.translate(x, y)
  951. scale = min(width / text_width, height / text_height)
  952. # center
  953. cr.translate(
  954. (width - text_width * scale) / 2, (height - text_height * scale) / 2
  955. )
  956. cr.scale(scale, scale)
  957. cr.translate(0, font_ascent)
  958. for line in text:
  959. cr.move_to(0, 0)
  960. cr.show_text(line)
  961. cr.translate(0, font_line_height)
  962. def draw_cupcake(self):
  963. self.set_size(self.total_width(), self.total_height())
  964. self.draw_label(
  965. self.no_issues_label,
  966. x=self.pad,
  967. y=self.pad,
  968. color=self.no_issues_label_color,
  969. width=self.total_width() - 2 * self.pad,
  970. align=0.5,
  971. bold=True,
  972. )
  973. self.draw_text(
  974. self.cupcake,
  975. x=self.pad,
  976. y=self.pad + self.line_height,
  977. width=self.total_width() - 2 * self.pad,
  978. height=self.total_height() - 2 * self.pad - self.line_height,
  979. color=self.cupcake_color,
  980. )
  981. def draw_emoticon(self, emoticon, x=0, y=0):
  982. self.draw_text(emoticon, x=x, y=y, color=self.emoticon_color)
  983. class InterpolatablePostscriptLike(InterpolatablePlot):
  984. @wraps(InterpolatablePlot.__init__)
  985. def __init__(self, *args, **kwargs):
  986. super().__init__(*args, **kwargs)
  987. def __exit__(self, type, value, traceback):
  988. self.surface.finish()
  989. def set_size(self, width, height):
  990. self.surface.set_size(width, height)
  991. def show_page(self):
  992. super().show_page()
  993. self.surface.show_page()
  994. class InterpolatablePS(InterpolatablePostscriptLike):
  995. def __enter__(self):
  996. self.surface = cairo.PSSurface(self.out, self.width, self.height)
  997. return self
  998. class InterpolatablePDF(InterpolatablePostscriptLike):
  999. def __enter__(self):
  1000. self.surface = cairo.PDFSurface(self.out, self.width, self.height)
  1001. self.surface.set_metadata(
  1002. cairo.PDF_METADATA_CREATOR, "fonttools varLib.interpolatable"
  1003. )
  1004. self.surface.set_metadata(cairo.PDF_METADATA_CREATE_DATE, "")
  1005. return self
  1006. class InterpolatableSVG(InterpolatablePlot):
  1007. @wraps(InterpolatablePlot.__init__)
  1008. def __init__(self, *args, **kwargs):
  1009. super().__init__(*args, **kwargs)
  1010. def __enter__(self):
  1011. self.surface = None
  1012. return self
  1013. def __exit__(self, type, value, traceback):
  1014. if self.surface is not None:
  1015. self.show_page()
  1016. def set_size(self, width, height):
  1017. self.sink = BytesIO()
  1018. self.surface = cairo.SVGSurface(self.sink, width, height)
  1019. def show_page(self):
  1020. super().show_page()
  1021. self.surface.finish()
  1022. self.out.append(self.sink.getvalue())
  1023. self.surface = None