matplotlib-rs 0.0.8__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. docs/releases/0.0.1.md +268 -0
  2. docs/releases/0.0.2.md +69 -0
  3. docs/releases/0.0.3.md +80 -0
  4. docs/releases/0.0.4.md +73 -0
  5. docs/releases/0.0.5.md +24 -0
  6. docs/releases/0.0.6.md +24 -0
  7. docs/releases/0.0.7.md +24 -0
  8. docs/releases/0.0.8.md +16 -0
  9. licenses/LICENSE_CONTOURPY +29 -0
  10. licenses/LICENSE_CYCLER +27 -0
  11. licenses/LICENSE_DATEUTIL +54 -0
  12. licenses/LICENSE_KIWISOLVER +71 -0
  13. licenses/LICENSE_LIBWEBP +56 -0
  14. licenses/LICENSE_MATPLOTLIB +1253 -0
  15. licenses/LICENSE_PYPARSING +20 -0
  16. licenses/LICENSE_QHULL +39 -0
  17. licenses/LICENSE_SIX +18 -0
  18. matplotlib_rs/__init__.py +1683 -0
  19. matplotlib_rs/__main__.py +27 -0
  20. matplotlib_rs/_afm.py +500 -0
  21. matplotlib_rs/_animation_data.py +263 -0
  22. matplotlib_rs/_api/__init__.py +495 -0
  23. matplotlib_rs/_api/deprecation.py +534 -0
  24. matplotlib_rs/_axis_py.py +2991 -0
  25. matplotlib_rs/_blocking_input.py +31 -0
  26. matplotlib_rs/_cm.py +1500 -0
  27. matplotlib_rs/_cm_bivar.py +1289 -0
  28. matplotlib_rs/_cm_listed.py +2848 -0
  29. matplotlib_rs/_cm_multivar.py +167 -0
  30. matplotlib_rs/_color_data.py +1142 -0
  31. matplotlib_rs/_colormap.py +132 -0
  32. matplotlib_rs/_constrained_layout.py +825 -0
  33. matplotlib_rs/_contour.py +108 -0
  34. matplotlib_rs/_doc_cache.py +12214 -0
  35. matplotlib_rs/_docstring.py +142 -0
  36. matplotlib_rs/_enums.py +178 -0
  37. matplotlib_rs/_figure_rs.py +294 -0
  38. matplotlib_rs/_fontconfig_pattern.py +129 -0
  39. matplotlib_rs/_foreign.py +220 -0
  40. matplotlib_rs/_hook.py +94 -0
  41. matplotlib_rs/_image.py +160 -0
  42. matplotlib_rs/_imageio.py +229 -0
  43. matplotlib_rs/_internal_utils.py +65 -0
  44. matplotlib_rs/_kiwi.py +484 -0
  45. matplotlib_rs/_layoutgrid.py +549 -0
  46. matplotlib_rs/_live.py +192 -0
  47. matplotlib_rs/_mathtext.py +3103 -0
  48. matplotlib_rs/_mathtext_data.py +1811 -0
  49. matplotlib_rs/_mplrs.cp313-win_amd64.pyd +0 -0
  50. matplotlib_rs/_path.py +25 -0
  51. matplotlib_rs/_png.py +162 -0
  52. matplotlib_rs/_pylab_helpers.py +137 -0
  53. matplotlib_rs/_qhull.py +66 -0
  54. matplotlib_rs/_rcpush.py +84 -0
  55. matplotlib_rs/_spines_rs.py +108 -0
  56. matplotlib_rs/_style_helpers.py +52 -0
  57. matplotlib_rs/_text_helpers.py +51 -0
  58. matplotlib_rs/_tight_bbox.py +85 -0
  59. matplotlib_rs/_tight_layout.py +302 -0
  60. matplotlib_rs/_tri.py +140 -0
  61. matplotlib_rs/_type1font.py +1228 -0
  62. matplotlib_rs/_vendor/__init__.py +8 -0
  63. matplotlib_rs/_vendor/cycler.py +574 -0
  64. matplotlib_rs/_vendor/dateutil/__init__.py +27 -0
  65. matplotlib_rs/_vendor/dateutil/_common.py +44 -0
  66. matplotlib_rs/_vendor/dateutil/_tzdata_impl.py +148 -0
  67. matplotlib_rs/_vendor/dateutil/_version.py +5 -0
  68. matplotlib_rs/_vendor/dateutil/easter.py +90 -0
  69. matplotlib_rs/_vendor/dateutil/parser/__init__.py +62 -0
  70. matplotlib_rs/_vendor/dateutil/parser/_parser.py +1614 -0
  71. matplotlib_rs/_vendor/dateutil/parser/isoparser.py +417 -0
  72. matplotlib_rs/_vendor/dateutil/relativedelta.py +597 -0
  73. matplotlib_rs/_vendor/dateutil/rrule.py +1765 -0
  74. matplotlib_rs/_vendor/dateutil/tz/__init__.py +61 -0
  75. matplotlib_rs/_vendor/dateutil/tz/_common.py +420 -0
  76. matplotlib_rs/_vendor/dateutil/tz/_factories.py +81 -0
  77. matplotlib_rs/_vendor/dateutil/tz/_tzfile.py +1429 -0
  78. matplotlib_rs/_vendor/dateutil/tz/_tzpath.py +105 -0
  79. matplotlib_rs/_vendor/dateutil/tz/tz.py +1473 -0
  80. matplotlib_rs/_vendor/dateutil/tz/win.py +371 -0
  81. matplotlib_rs/_vendor/dateutil/tzwin.py +3 -0
  82. matplotlib_rs/_vendor/dateutil/utils.py +72 -0
  83. matplotlib_rs/_vendor/dateutil/zoneinfo/__init__.py +234 -0
  84. matplotlib_rs/_vendor/pyparsing/__init__.py +414 -0
  85. matplotlib_rs/_vendor/pyparsing/actions.py +265 -0
  86. matplotlib_rs/_vendor/pyparsing/common.py +571 -0
  87. matplotlib_rs/_vendor/pyparsing/core.py +6973 -0
  88. matplotlib_rs/_vendor/pyparsing/exceptions.py +354 -0
  89. matplotlib_rs/_vendor/pyparsing/helpers.py +1770 -0
  90. matplotlib_rs/_vendor/pyparsing/results.py +929 -0
  91. matplotlib_rs/_vendor/pyparsing/testing.py +399 -0
  92. matplotlib_rs/_vendor/pyparsing/unicode.py +357 -0
  93. matplotlib_rs/_vendor/pyparsing/util.py +515 -0
  94. matplotlib_rs/_vendor/pyparsing/warnings.py +11 -0
  95. matplotlib_rs/_vendor/six.py +1004 -0
  96. matplotlib_rs/animation.py +1843 -0
  97. matplotlib_rs/artist.py +2302 -0
  98. matplotlib_rs/axes/__init__.py +19 -0
  99. matplotlib_rs/axes/_axes.py +9402 -0
  100. matplotlib_rs/axes/_bar.py +185 -0
  101. matplotlib_rs/axes/_base.py +5236 -0
  102. matplotlib_rs/axes/_base_rs.py +727 -0
  103. matplotlib_rs/axes/_boxplot.py +391 -0
  104. matplotlib_rs/axes/_hist.py +99 -0
  105. matplotlib_rs/axes/_secondary_axes.py +357 -0
  106. matplotlib_rs/axis.py +1963 -0
  107. matplotlib_rs/backend_bases.py +3760 -0
  108. matplotlib_rs/backend_managers.py +388 -0
  109. matplotlib_rs/backend_tools.py +1002 -0
  110. matplotlib_rs/backends/__init__.py +6 -0
  111. matplotlib_rs/backends/_backend_pdf_ps.py +451 -0
  112. matplotlib_rs/backends/backend_agg.py +552 -0
  113. matplotlib_rs/backends/backend_mixed.py +123 -0
  114. matplotlib_rs/backends/backend_pdf.py +2711 -0
  115. matplotlib_rs/backends/backend_pgf.py +1031 -0
  116. matplotlib_rs/backends/backend_ps.py +1491 -0
  117. matplotlib_rs/backends/backend_svg.py +1395 -0
  118. matplotlib_rs/backends/backend_template.py +214 -0
  119. matplotlib_rs/backends/registry.py +423 -0
  120. matplotlib_rs/bezier.py +691 -0
  121. matplotlib_rs/category.py +236 -0
  122. matplotlib_rs/cbook.py +2762 -0
  123. matplotlib_rs/cm.py +251 -0
  124. matplotlib_rs/collections.py +2711 -0
  125. matplotlib_rs/colorbar.py +1586 -0
  126. matplotlib_rs/colorizer.py +909 -0
  127. matplotlib_rs/colors.py +4278 -0
  128. matplotlib_rs/container.py +256 -0
  129. matplotlib_rs/contour.py +1756 -0
  130. matplotlib_rs/dates.py +1847 -0
  131. matplotlib_rs/dviread.py +1386 -0
  132. matplotlib_rs/figure.py +3815 -0
  133. matplotlib_rs/font_manager.py +1855 -0
  134. matplotlib_rs/ft2font.py +515 -0
  135. matplotlib_rs/gridspec.py +808 -0
  136. matplotlib_rs/hatch.py +244 -0
  137. matplotlib_rs/image.py +1863 -0
  138. matplotlib_rs/inset.py +291 -0
  139. matplotlib_rs/layout_engine.py +310 -0
  140. matplotlib_rs/legend.py +1480 -0
  141. matplotlib_rs/legend_handler.py +812 -0
  142. matplotlib_rs/lines.py +1886 -0
  143. matplotlib_rs/markers.py +908 -0
  144. matplotlib_rs/mathtext.py +141 -0
  145. matplotlib_rs/mlab.py +959 -0
  146. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf +0 -0
  147. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf +0 -0
  148. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf +0 -0
  149. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans.ttf +0 -0
  150. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansDisplay.ttf +0 -0
  151. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf +0 -0
  152. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf +0 -0
  153. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf +0 -0
  154. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono.ttf +0 -0
  155. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf +0 -0
  156. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf +0 -0
  157. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf +0 -0
  158. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif.ttf +0 -0
  159. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerifDisplay.ttf +0 -0
  160. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_DEJAVU +99 -0
  161. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_STIX +124 -0
  162. matplotlib_rs/mpl-data/fonts/ttf/LastResortHE-Regular.ttf +0 -0
  163. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneral.ttf +0 -0
  164. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBol.ttf +0 -0
  165. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf +0 -0
  166. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralItalic.ttf +0 -0
  167. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUni.ttf +0 -0
  168. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBol.ttf +0 -0
  169. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf +0 -0
  170. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniIta.ttf +0 -0
  171. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf +0 -0
  172. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf +0 -0
  173. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf +0 -0
  174. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf +0 -0
  175. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf +0 -0
  176. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf +0 -0
  177. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf +0 -0
  178. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf +0 -0
  179. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf +0 -0
  180. matplotlib_rs/mpl-data/fonts/ttf/cmb10.ttf +0 -0
  181. matplotlib_rs/mpl-data/fonts/ttf/cmex10.ttf +0 -0
  182. matplotlib_rs/mpl-data/fonts/ttf/cmmi10.ttf +0 -0
  183. matplotlib_rs/mpl-data/fonts/ttf/cmr10.ttf +0 -0
  184. matplotlib_rs/mpl-data/fonts/ttf/cmss10.ttf +0 -0
  185. matplotlib_rs/mpl-data/fonts/ttf/cmsy10.ttf +0 -0
  186. matplotlib_rs/mpl-data/fonts/ttf/cmti10.ttf +0 -0
  187. matplotlib_rs/mpl-data/fonts/ttf/cmtt10.ttf +0 -0
  188. matplotlib_rs/mpl-data/images/back-symbolic.svg +46 -0
  189. matplotlib_rs/mpl-data/images/back.pdf +0 -0
  190. matplotlib_rs/mpl-data/images/back.png +0 -0
  191. matplotlib_rs/mpl-data/images/back.svg +46 -0
  192. matplotlib_rs/mpl-data/images/back_large.png +0 -0
  193. matplotlib_rs/mpl-data/images/filesave-symbolic.svg +68 -0
  194. matplotlib_rs/mpl-data/images/filesave.pdf +72 -0
  195. matplotlib_rs/mpl-data/images/filesave.png +0 -0
  196. matplotlib_rs/mpl-data/images/filesave.svg +68 -0
  197. matplotlib_rs/mpl-data/images/filesave_large.png +0 -0
  198. matplotlib_rs/mpl-data/images/forward-symbolic.svg +46 -0
  199. matplotlib_rs/mpl-data/images/forward.pdf +0 -0
  200. matplotlib_rs/mpl-data/images/forward.png +0 -0
  201. matplotlib_rs/mpl-data/images/forward.svg +46 -0
  202. matplotlib_rs/mpl-data/images/forward_large.png +0 -0
  203. matplotlib_rs/mpl-data/images/hand.pdf +0 -0
  204. matplotlib_rs/mpl-data/images/hand.png +0 -0
  205. matplotlib_rs/mpl-data/images/hand.svg +130 -0
  206. matplotlib_rs/mpl-data/images/help-symbolic.svg +52 -0
  207. matplotlib_rs/mpl-data/images/help.pdf +71 -0
  208. matplotlib_rs/mpl-data/images/help.png +0 -0
  209. matplotlib_rs/mpl-data/images/help.svg +52 -0
  210. matplotlib_rs/mpl-data/images/help_large.png +0 -0
  211. matplotlib_rs/mpl-data/images/home-symbolic.svg +59 -0
  212. matplotlib_rs/mpl-data/images/home.pdf +0 -0
  213. matplotlib_rs/mpl-data/images/home.png +0 -0
  214. matplotlib_rs/mpl-data/images/home.svg +59 -0
  215. matplotlib_rs/mpl-data/images/home_large.png +0 -0
  216. matplotlib_rs/mpl-data/images/matplotlib.pdf +0 -0
  217. matplotlib_rs/mpl-data/images/matplotlib.png +0 -0
  218. matplotlib_rs/mpl-data/images/matplotlib.svg +3171 -0
  219. matplotlib_rs/mpl-data/images/matplotlib_large.png +0 -0
  220. matplotlib_rs/mpl-data/images/move-symbolic.svg +73 -0
  221. matplotlib_rs/mpl-data/images/move.pdf +0 -0
  222. matplotlib_rs/mpl-data/images/move.png +0 -0
  223. matplotlib_rs/mpl-data/images/move.svg +73 -0
  224. matplotlib_rs/mpl-data/images/move_large.png +0 -0
  225. matplotlib_rs/mpl-data/images/qt4_editor_options.pdf +0 -0
  226. matplotlib_rs/mpl-data/images/qt4_editor_options.png +0 -0
  227. matplotlib_rs/mpl-data/images/qt4_editor_options.svg +48 -0
  228. matplotlib_rs/mpl-data/images/qt4_editor_options_large.png +0 -0
  229. matplotlib_rs/mpl-data/images/subplots-symbolic.svg +81 -0
  230. matplotlib_rs/mpl-data/images/subplots.pdf +0 -0
  231. matplotlib_rs/mpl-data/images/subplots.png +0 -0
  232. matplotlib_rs/mpl-data/images/subplots.svg +81 -0
  233. matplotlib_rs/mpl-data/images/subplots_large.png +0 -0
  234. matplotlib_rs/mpl-data/images/zoom_to_rect-symbolic.svg +40 -0
  235. matplotlib_rs/mpl-data/images/zoom_to_rect.pdf +69 -0
  236. matplotlib_rs/mpl-data/images/zoom_to_rect.png +0 -0
  237. matplotlib_rs/mpl-data/images/zoom_to_rect.svg +40 -0
  238. matplotlib_rs/mpl-data/images/zoom_to_rect_large.png +0 -0
  239. matplotlib_rs/mpl-data/kpsewhich.lua +4 -0
  240. matplotlib_rs/mpl-data/matplotlibrc +849 -0
  241. matplotlib_rs/mpl-data/plot_directive/plot_directive.css +16 -0
  242. matplotlib_rs/mpl-data/sample_data/Minduka_Present_Blue_Pack.png +0 -0
  243. matplotlib_rs/mpl-data/sample_data/README.txt +2 -0
  244. matplotlib_rs/mpl-data/sample_data/Stocks.csv +526 -0
  245. matplotlib_rs/mpl-data/sample_data/axes_grid/bivariate_normal.npy +0 -0
  246. matplotlib_rs/mpl-data/sample_data/data_x_x2_x3.csv +11 -0
  247. matplotlib_rs/mpl-data/sample_data/eeg.dat +0 -0
  248. matplotlib_rs/mpl-data/sample_data/embedding_in_wx3.xrc +65 -0
  249. matplotlib_rs/mpl-data/sample_data/goog.npz +0 -0
  250. matplotlib_rs/mpl-data/sample_data/grace_hopper.jpg +0 -0
  251. matplotlib_rs/mpl-data/sample_data/jacksboro_fault_dem.npz +0 -0
  252. matplotlib_rs/mpl-data/sample_data/logo2.png +0 -0
  253. matplotlib_rs/mpl-data/sample_data/membrane.dat +0 -0
  254. matplotlib_rs/mpl-data/sample_data/msft.csv +66 -0
  255. matplotlib_rs/mpl-data/sample_data/s1045.ima.gz +0 -0
  256. matplotlib_rs/mpl-data/sample_data/topobathy.npz +0 -0
  257. matplotlib_rs/mpl-data/stylelib/Solarize_Light2.mplstyle +53 -0
  258. matplotlib_rs/mpl-data/stylelib/_classic_test_patch.mplstyle +8 -0
  259. matplotlib_rs/mpl-data/stylelib/_mpl-gallery-nogrid.mplstyle +19 -0
  260. matplotlib_rs/mpl-data/stylelib/_mpl-gallery.mplstyle +19 -0
  261. matplotlib_rs/mpl-data/stylelib/bmh.mplstyle +27 -0
  262. matplotlib_rs/mpl-data/stylelib/classic.mplstyle +491 -0
  263. matplotlib_rs/mpl-data/stylelib/dark_background.mplstyle +26 -0
  264. matplotlib_rs/mpl-data/stylelib/fast.mplstyle +11 -0
  265. matplotlib_rs/mpl-data/stylelib/fivethirtyeight.mplstyle +37 -0
  266. matplotlib_rs/mpl-data/stylelib/ggplot.mplstyle +39 -0
  267. matplotlib_rs/mpl-data/stylelib/grayscale.mplstyle +29 -0
  268. matplotlib_rs/mpl-data/stylelib/petroff10.mplstyle +5 -0
  269. matplotlib_rs/mpl-data/stylelib/petroff6.mplstyle +5 -0
  270. matplotlib_rs/mpl-data/stylelib/petroff8.mplstyle +5 -0
  271. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-bright.mplstyle +3 -0
  272. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-colorblind.mplstyle +3 -0
  273. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark-palette.mplstyle +3 -0
  274. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark.mplstyle +30 -0
  275. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-darkgrid.mplstyle +30 -0
  276. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-deep.mplstyle +3 -0
  277. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-muted.mplstyle +3 -0
  278. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-notebook.mplstyle +21 -0
  279. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-paper.mplstyle +21 -0
  280. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-pastel.mplstyle +3 -0
  281. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-poster.mplstyle +21 -0
  282. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-talk.mplstyle +21 -0
  283. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-ticks.mplstyle +30 -0
  284. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-white.mplstyle +30 -0
  285. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-whitegrid.mplstyle +30 -0
  286. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8.mplstyle +57 -0
  287. matplotlib_rs/mpl-data/stylelib/tableau-colorblind10.mplstyle +3 -0
  288. matplotlib_rs/mpl_toolkits/__init__.py +3 -0
  289. matplotlib_rs/mpl_toolkits/axes_grid1/__init__.py +11 -0
  290. matplotlib_rs/mpl_toolkits/axes_grid1/anchored_artists.py +415 -0
  291. matplotlib_rs/mpl_toolkits/axes_grid1/axes_divider.py +619 -0
  292. matplotlib_rs/mpl_toolkits/axes_grid1/axes_grid.py +565 -0
  293. matplotlib_rs/mpl_toolkits/axes_grid1/axes_rgb.py +158 -0
  294. matplotlib_rs/mpl_toolkits/axes_grid1/axes_size.py +272 -0
  295. matplotlib_rs/mpl_toolkits/axes_grid1/inset_locator.py +525 -0
  296. matplotlib_rs/mpl_toolkits/axes_grid1/mpl_axes.py +129 -0
  297. matplotlib_rs/mpl_toolkits/axes_grid1/parasite_axes.py +261 -0
  298. matplotlib_rs/mpl_toolkits/axisartist/__init__.py +15 -0
  299. matplotlib_rs/mpl_toolkits/axisartist/angle_helper.py +396 -0
  300. matplotlib_rs/mpl_toolkits/axisartist/axes_divider.py +3 -0
  301. matplotlib_rs/mpl_toolkits/axisartist/axis_artist.py +1148 -0
  302. matplotlib_rs/mpl_toolkits/axisartist/axisline_style.py +193 -0
  303. matplotlib_rs/mpl_toolkits/axisartist/axislines.py +475 -0
  304. matplotlib_rs/mpl_toolkits/axisartist/floating_axes.py +265 -0
  305. matplotlib_rs/mpl_toolkits/axisartist/grid_finder.py +329 -0
  306. matplotlib_rs/mpl_toolkits/axisartist/grid_helper_curvelinear.py +353 -0
  307. matplotlib_rs/mpl_toolkits/axisartist/parasite_axes.py +8 -0
  308. matplotlib_rs/mpl_toolkits/mplot3d/__init__.py +4 -0
  309. matplotlib_rs/mpl_toolkits/mplot3d/art3d.py +1758 -0
  310. matplotlib_rs/mpl_toolkits/mplot3d/axes3d.py +4462 -0
  311. matplotlib_rs/mpl_toolkits/mplot3d/axis3d.py +807 -0
  312. matplotlib_rs/mpl_toolkits/mplot3d/proj3d.py +270 -0
  313. matplotlib_rs/offsetbox.py +1726 -0
  314. matplotlib_rs/patches.py +5049 -0
  315. matplotlib_rs/path.py +1147 -0
  316. matplotlib_rs/patheffects.py +512 -0
  317. matplotlib_rs/projections/__init__.py +126 -0
  318. matplotlib_rs/projections/geo.py +512 -0
  319. matplotlib_rs/projections/polar.py +1518 -0
  320. matplotlib_rs/pylab.py +68 -0
  321. matplotlib_rs/pyplot.py +4834 -0
  322. matplotlib_rs/quiver.py +1236 -0
  323. matplotlib_rs/rcsetup.py +3435 -0
  324. matplotlib_rs/sankey.py +815 -0
  325. matplotlib_rs/scale.py +1002 -0
  326. matplotlib_rs/spines.py +618 -0
  327. matplotlib_rs/stackplot.py +144 -0
  328. matplotlib_rs/streamplot.py +768 -0
  329. matplotlib_rs/style/__init__.py +269 -0
  330. matplotlib_rs/style/core.py +28 -0
  331. matplotlib_rs/table.py +860 -0
  332. matplotlib_rs/texmanager.py +375 -0
  333. matplotlib_rs/text.py +2412 -0
  334. matplotlib_rs/textpath.py +377 -0
  335. matplotlib_rs/ticker.py +3111 -0
  336. matplotlib_rs/transforms.py +3069 -0
  337. matplotlib_rs/tri/__init__.py +24 -0
  338. matplotlib_rs/tri/_triangulation.py +248 -0
  339. matplotlib_rs/tri/_tricontour.py +271 -0
  340. matplotlib_rs/tri/_trifinder.py +97 -0
  341. matplotlib_rs/tri/_triinterpolate.py +1575 -0
  342. matplotlib_rs/tri/_tripcolor.py +170 -0
  343. matplotlib_rs/tri/_triplot.py +87 -0
  344. matplotlib_rs/tri/_trirefine.py +308 -0
  345. matplotlib_rs/tri/_tritools.py +264 -0
  346. matplotlib_rs/typing.py +597 -0
  347. matplotlib_rs/units.py +196 -0
  348. matplotlib_rs/widgets.py +4455 -0
  349. matplotlib_rs-0.0.8.dist-info/METADATA +392 -0
  350. matplotlib_rs-0.0.8.dist-info/RECORD +352 -0
  351. matplotlib_rs-0.0.8.dist-info/WHEEL +4 -0
  352. matplotlib_rs-0.0.8.dist-info/sboms/matplotlib-rs.cyclonedx.json +4390 -0
@@ -0,0 +1,2711 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ A PDF Matplotlib backend.
4
+
5
+ Author: Jouni K Seppänen <jks@iki.fi> and others.
6
+ """
7
+
8
+ import codecs
9
+ from datetime import timezone
10
+ from datetime import datetime
11
+ from enum import Enum
12
+ from functools import total_ordering
13
+ from io import BytesIO
14
+ import itertools
15
+ import logging
16
+ import math
17
+ import os
18
+ import string
19
+ import struct
20
+ import sys
21
+ import time
22
+ import types
23
+ import zlib
24
+
25
+ import numpy as np
26
+
27
+ import matplotlib_rs as mpl
28
+ from matplotlib_rs import _api, _mplrs, _text_helpers, _type1font, cbook, dviread
29
+ from matplotlib_rs._pylab_helpers import Gcf
30
+ from matplotlib_rs.backend_bases import (
31
+ _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
32
+ RendererBase)
33
+ from matplotlib_rs.backends.backend_mixed import MixedModeRenderer
34
+ from matplotlib_rs.figure import Figure
35
+ from matplotlib_rs.font_manager import FontPath, get_font, fontManager as _fontManager
36
+ from matplotlib_rs._afm import AFM
37
+ from matplotlib_rs.ft2font import FT2Font, FaceFlags, LoadFlags, StyleFlags
38
+ from matplotlib_rs.transforms import Affine2D, BboxBase
39
+ from matplotlib_rs.path import Path
40
+ from matplotlib_rs.dates import UTC
41
+ from matplotlib_rs import _path
42
+ from . import _backend_pdf_ps
43
+
44
+ _log = logging.getLogger(__name__)
45
+
46
+ # Overview
47
+ #
48
+ # The low-level knowledge about pdf syntax lies mainly in the pdfRepr
49
+ # function and the classes Reference, Name, Operator, and Stream. The
50
+ # PdfFile class knows about the overall structure of pdf documents.
51
+ # It provides a "write" method for writing arbitrary strings in the
52
+ # file, and an "output" method that passes objects through the pdfRepr
53
+ # function before writing them in the file. The output method is
54
+ # called by the RendererPdf class, which contains the various draw_foo
55
+ # methods. RendererPdf contains a GraphicsContextPdf instance, and
56
+ # each draw_foo calls self.check_gc before outputting commands. This
57
+ # method checks whether the pdf graphics state needs to be modified
58
+ # and outputs the necessary commands. GraphicsContextPdf represents
59
+ # the graphics state, and its "delta" method returns the commands that
60
+ # modify the state.
61
+
62
+ # Add "pdf.use14corefonts: True" in your configuration file to use only
63
+ # the 14 PDF core fonts. These fonts do not need to be embedded; every
64
+ # PDF viewing application is required to have them. This results in very
65
+ # light PDF files you can use directly in LaTeX or ConTeXt documents
66
+ # generated with pdfTeX, without any conversion.
67
+
68
+ # These fonts are: Helvetica, Helvetica-Bold, Helvetica-Oblique,
69
+ # Helvetica-BoldOblique, Courier, Courier-Bold, Courier-Oblique,
70
+ # Courier-BoldOblique, Times-Roman, Times-Bold, Times-Italic,
71
+ # Times-BoldItalic, Symbol, ZapfDingbats.
72
+ #
73
+ # Some tricky points:
74
+ #
75
+ # 1. The clip path can only be widened by popping from the state
76
+ # stack. Thus the state must be pushed onto the stack before narrowing
77
+ # the clip path. This is taken care of by GraphicsContextPdf.
78
+ #
79
+ # 2. Sometimes it is necessary to refer to something (e.g., font,
80
+ # image, or extended graphics state, which contains the alpha value)
81
+ # in the page stream by a name that needs to be defined outside the
82
+ # stream. PdfFile provides the methods fontName, imageObject, and
83
+ # alphaState for this purpose. The implementations of these methods
84
+ # should perhaps be generalized.
85
+
86
+ # TODOs:
87
+ #
88
+ # * encoding of fonts, including mathtext fonts and Unicode support
89
+ # * TTF support has lots of small TODOs, e.g., how do you know if a font
90
+ # is serif/sans-serif, or symbolic/non-symbolic?
91
+ # * draw_quad_mesh
92
+
93
+
94
+ def _fill(strings, linelen=75):
95
+ """
96
+ Make one string from sequence of strings, with whitespace in between.
97
+
98
+ The whitespace is chosen to form lines of at most *linelen* characters,
99
+ if possible.
100
+ """
101
+ currpos = 0
102
+ lasti = 0
103
+ result = []
104
+ for i, s in enumerate(strings):
105
+ length = len(s)
106
+ if currpos + length < linelen:
107
+ currpos += length + 1
108
+ else:
109
+ result.append(b' '.join(strings[lasti:i]))
110
+ lasti = i
111
+ currpos = length
112
+ result.append(b' '.join(strings[lasti:]))
113
+ return b'\n'.join(result)
114
+
115
+
116
+ def _create_pdf_info_dict(backend, metadata):
117
+ """
118
+ Create a PDF infoDict based on user-supplied metadata.
119
+
120
+ A default ``Creator``, ``Producer``, and ``CreationDate`` are added, though
121
+ the user metadata may override it. The date may be the current time, or a
122
+ time set by the ``SOURCE_DATE_EPOCH`` environment variable.
123
+
124
+ Metadata is verified to have the correct keys and their expected types. Any
125
+ unknown keys/types will raise a warning.
126
+
127
+ Parameters
128
+ ----------
129
+ backend : str
130
+ The name of the backend to use in the Producer value.
131
+
132
+ metadata : dict[str, Union[str, datetime, Name]]
133
+ A dictionary of metadata supplied by the user with information
134
+ following the PDF specification, also defined in
135
+ `~.backend_pdf.PdfPages` below.
136
+
137
+ If any value is *None*, then the key will be removed. This can be used
138
+ to remove any pre-defined values.
139
+
140
+ Returns
141
+ -------
142
+ dict[str, Union[str, datetime, Name]]
143
+ A validated dictionary of metadata.
144
+ """
145
+
146
+ # get source date from SOURCE_DATE_EPOCH, if set
147
+ # See https://reproducible-builds.org/specs/source-date-epoch/
148
+ source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
149
+ if source_date_epoch:
150
+ source_date = datetime.fromtimestamp(int(source_date_epoch), timezone.utc)
151
+ source_date = source_date.replace(tzinfo=UTC)
152
+ else:
153
+ source_date = datetime.today()
154
+
155
+ info = {
156
+ 'Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org',
157
+ 'Producer': f'Matplotlib {backend} backend v{mpl.__version__}',
158
+ 'CreationDate': source_date,
159
+ **metadata
160
+ }
161
+ info = {k: v for (k, v) in info.items() if v is not None}
162
+
163
+ def is_string_like(x):
164
+ return isinstance(x, str)
165
+ is_string_like.text_for_warning = "an instance of str"
166
+
167
+ def is_date(x):
168
+ return isinstance(x, datetime)
169
+ is_date.text_for_warning = "an instance of datetime.datetime"
170
+
171
+ def check_trapped(x):
172
+ if isinstance(x, Name):
173
+ return x.name in (b'True', b'False', b'Unknown')
174
+ else:
175
+ return x in ('True', 'False', 'Unknown')
176
+ check_trapped.text_for_warning = 'one of {"True", "False", "Unknown"}'
177
+
178
+ keywords = {
179
+ 'Title': is_string_like,
180
+ 'Author': is_string_like,
181
+ 'Subject': is_string_like,
182
+ 'Keywords': is_string_like,
183
+ 'Creator': is_string_like,
184
+ 'Producer': is_string_like,
185
+ 'CreationDate': is_date,
186
+ 'ModDate': is_date,
187
+ 'Trapped': check_trapped,
188
+ }
189
+ for k in info:
190
+ if k not in keywords:
191
+ _api.warn_external(f'Unknown infodict keyword: {k!r}. '
192
+ f'Must be one of {set(keywords)!r}.')
193
+ elif not keywords[k](info[k]):
194
+ _api.warn_external(f'Bad value for infodict keyword {k}. '
195
+ f'Got {info[k]!r} which is not '
196
+ f'{keywords[k].text_for_warning}.')
197
+ if 'Trapped' in info:
198
+ info['Trapped'] = Name(info['Trapped'])
199
+
200
+ return info
201
+
202
+
203
+ def _datetime_to_pdf(d):
204
+ """
205
+ Convert a datetime to a PDF string representing it.
206
+
207
+ Used for PDF and PGF.
208
+ """
209
+ r = d.strftime('D:%Y%m%d%H%M%S')
210
+ z = d.utcoffset()
211
+ if z is not None:
212
+ z = z.seconds
213
+ else:
214
+ if time.daylight:
215
+ z = time.altzone
216
+ else:
217
+ z = time.timezone
218
+ if z == 0:
219
+ r += 'Z'
220
+ elif z < 0:
221
+ r += "+%02d'%02d'" % ((-z) // 3600, (-z) % 3600)
222
+ else:
223
+ r += "-%02d'%02d'" % (z // 3600, z % 3600)
224
+ return r
225
+
226
+
227
+ def _calculate_quad_point_coordinates(x, y, width, height, angle=0):
228
+ """
229
+ Calculate the coordinates of rectangle when rotated by angle around x, y
230
+ """
231
+
232
+ angle = math.radians(-angle)
233
+ sin_angle = math.sin(angle)
234
+ cos_angle = math.cos(angle)
235
+ a = x + height * sin_angle
236
+ b = y + height * cos_angle
237
+ c = x + width * cos_angle + height * sin_angle
238
+ d = y - width * sin_angle + height * cos_angle
239
+ e = x + width * cos_angle
240
+ f = y - width * sin_angle
241
+ return ((x, y), (e, f), (c, d), (a, b))
242
+
243
+
244
+ def _get_coordinates_of_block(x, y, width, height, angle=0):
245
+ """
246
+ Get the coordinates of rotated rectangle and rectangle that covers the
247
+ rotated rectangle.
248
+ """
249
+
250
+ vertices = _calculate_quad_point_coordinates(x, y, width,
251
+ height, angle)
252
+
253
+ # Find min and max values for rectangle
254
+ # adjust so that QuadPoints is inside Rect
255
+ # PDF docs says that QuadPoints should be ignored if any point lies
256
+ # outside Rect, but for Acrobat it is enough that QuadPoints is on the
257
+ # border of Rect.
258
+
259
+ pad = 0.00001 if angle % 90 else 0
260
+ min_x = min(v[0] for v in vertices) - pad
261
+ min_y = min(v[1] for v in vertices) - pad
262
+ max_x = max(v[0] for v in vertices) + pad
263
+ max_y = max(v[1] for v in vertices) + pad
264
+ return (tuple(itertools.chain.from_iterable(vertices)),
265
+ (min_x, min_y, max_x, max_y))
266
+
267
+
268
+ def _get_link_annotation(gc, x, y, width, height, angle=0):
269
+ """
270
+ Create a link annotation object for embedding URLs.
271
+ """
272
+ quadpoints, rect = _get_coordinates_of_block(x, y, width, height, angle)
273
+ link_annotation = {
274
+ 'Type': Name('Annot'),
275
+ 'Subtype': Name('Link'),
276
+ 'Rect': rect,
277
+ 'Border': [0, 0, 0],
278
+ 'A': {
279
+ 'S': Name('URI'),
280
+ 'URI': gc.get_url(),
281
+ },
282
+ }
283
+ if angle % 90:
284
+ # Add QuadPoints
285
+ link_annotation['QuadPoints'] = quadpoints
286
+ return link_annotation
287
+
288
+
289
+ # PDF strings are supposed to be able to include any eight-bit data, except
290
+ # that unbalanced parens and backslashes must be escaped by a backslash.
291
+ # However, sf bug #2708559 shows that the carriage return character may get
292
+ # read as a newline; these characters correspond to \gamma and \Omega in TeX's
293
+ # math font encoding. Escaping them fixes the bug.
294
+ _str_escapes = str.maketrans({
295
+ '\\': '\\\\', '(': '\\(', ')': '\\)', '\n': '\\n', '\r': '\\r'})
296
+
297
+
298
+ def pdfRepr(obj):
299
+ """Map Python objects to PDF syntax."""
300
+
301
+ # Some objects defined later have their own pdfRepr method.
302
+ if hasattr(obj, 'pdfRepr'):
303
+ return obj.pdfRepr()
304
+
305
+ # Floats. PDF does not have exponential notation (1.0e-10) so we
306
+ # need to use %f with some precision. Perhaps the precision
307
+ # should adapt to the magnitude of the number?
308
+ elif isinstance(obj, (float, np.floating)):
309
+ if not np.isfinite(obj):
310
+ raise ValueError("Can only output finite numbers in PDF")
311
+ r = b"%.10f" % obj
312
+ return r.rstrip(b'0').rstrip(b'.')
313
+
314
+ # Booleans. Needs to be tested before integers since
315
+ # isinstance(True, int) is true.
316
+ elif isinstance(obj, bool):
317
+ return [b'false', b'true'][obj]
318
+
319
+ # Integers are written as such.
320
+ elif isinstance(obj, (int, np.integer)):
321
+ return b"%d" % obj
322
+
323
+ # Non-ASCII Unicode strings are encoded in UTF-16BE with byte-order mark.
324
+ elif isinstance(obj, str):
325
+ return pdfRepr(obj.encode('ascii') if obj.isascii()
326
+ else codecs.BOM_UTF16_BE + obj.encode('UTF-16BE'))
327
+
328
+ # Strings are written in parentheses, with backslashes and parens
329
+ # escaped. Actually balanced parens are allowed, but it is
330
+ # simpler to escape them all. TODO: cut long strings into lines;
331
+ # I believe there is some maximum line length in PDF.
332
+ # Despite the extra decode/encode, translate is faster than regex.
333
+ elif isinstance(obj, bytes):
334
+ return (
335
+ b'(' +
336
+ obj.decode('latin-1').translate(_str_escapes).encode('latin-1')
337
+ + b')')
338
+
339
+ # Dictionaries. The keys must be PDF names, so if we find strings
340
+ # there, we make Name objects from them. The values may be
341
+ # anything, so the caller must ensure that PDF names are
342
+ # represented as Name objects.
343
+ elif isinstance(obj, dict):
344
+ return _fill([
345
+ b"<<",
346
+ *[Name(k).pdfRepr() + b" " + pdfRepr(v) for k, v in obj.items()],
347
+ b">>",
348
+ ])
349
+
350
+ # Lists.
351
+ elif isinstance(obj, (list, tuple)):
352
+ return _fill([b"[", *[pdfRepr(val) for val in obj], b"]"])
353
+
354
+ # The null keyword.
355
+ elif obj is None:
356
+ return b'null'
357
+
358
+ # A date.
359
+ elif isinstance(obj, datetime):
360
+ return pdfRepr(_datetime_to_pdf(obj))
361
+
362
+ # A bounding box
363
+ elif isinstance(obj, BboxBase):
364
+ return _fill([pdfRepr(val) for val in obj.bounds])
365
+
366
+ else:
367
+ raise TypeError(f"Don't know a PDF representation for {type(obj)} "
368
+ "objects")
369
+
370
+
371
+ class Reference:
372
+ """
373
+ PDF reference object.
374
+
375
+ Use PdfFile.reserveObject() to create References.
376
+ """
377
+
378
+ def __init__(self, id):
379
+ self.id = id
380
+
381
+ def __repr__(self):
382
+ return "<Reference %d>" % self.id
383
+
384
+ def pdfRepr(self):
385
+ return b"%d 0 R" % self.id
386
+
387
+ def write(self, contents, file):
388
+ write = file.write
389
+ write(b"%d 0 obj\n" % self.id)
390
+ write(pdfRepr(contents))
391
+ write(b"\nendobj\n")
392
+
393
+
394
+ @total_ordering
395
+ class Name:
396
+ """PDF name object."""
397
+ __slots__ = ('name',)
398
+ _hexify = {c: '#%02x' % c
399
+ for c in {*range(256)} - {*range(ord('!'), ord('~') + 1)}}
400
+
401
+ def __init__(self, name):
402
+ if isinstance(name, Name):
403
+ self.name = name.name
404
+ else:
405
+ if isinstance(name, bytes):
406
+ name = name.decode('ascii')
407
+ self.name = name.translate(self._hexify).encode('ascii')
408
+
409
+ def __repr__(self):
410
+ return "<Name %s>" % self.name
411
+
412
+ def __str__(self):
413
+ return '/' + self.name.decode('ascii')
414
+
415
+ def __eq__(self, other):
416
+ return isinstance(other, Name) and self.name == other.name
417
+
418
+ def __lt__(self, other):
419
+ return isinstance(other, Name) and self.name < other.name
420
+
421
+ def __hash__(self):
422
+ return hash(self.name)
423
+
424
+ def pdfRepr(self):
425
+ return b'/' + self.name
426
+
427
+
428
+ class Verbatim:
429
+ """Store verbatim PDF command content for later inclusion in the stream."""
430
+ def __init__(self, x):
431
+ self._x = x
432
+
433
+ def pdfRepr(self):
434
+ return self._x
435
+
436
+
437
+ class Op(Enum):
438
+ """PDF operators (not an exhaustive list)."""
439
+
440
+ close_fill_stroke = b'b'
441
+ fill_stroke = b'B'
442
+ fill = b'f'
443
+ closepath = b'h'
444
+ close_stroke = b's'
445
+ stroke = b'S'
446
+ endpath = b'n'
447
+ begin_text = b'BT'
448
+ end_text = b'ET'
449
+ curveto = b'c'
450
+ rectangle = b're'
451
+ lineto = b'l'
452
+ moveto = b'm'
453
+ concat_matrix = b'cm'
454
+ use_xobject = b'Do'
455
+ setgray_stroke = b'G'
456
+ setgray_nonstroke = b'g'
457
+ setrgb_stroke = b'RG'
458
+ setrgb_nonstroke = b'rg'
459
+ setcolorspace_stroke = b'CS'
460
+ setcolorspace_nonstroke = b'cs'
461
+ setcolor_stroke = b'SCN'
462
+ setcolor_nonstroke = b'scn'
463
+ setdash = b'd'
464
+ setlinejoin = b'j'
465
+ setlinecap = b'J'
466
+ setgstate = b'gs'
467
+ gsave = b'q'
468
+ grestore = b'Q'
469
+ textpos = b'Td'
470
+ selectfont = b'Tf'
471
+ textmatrix = b'Tm'
472
+ textrise = b'Ts'
473
+ show = b'Tj'
474
+ showkern = b'TJ'
475
+ setlinewidth = b'w'
476
+ clip = b'W'
477
+ shading = b'sh'
478
+
479
+ def pdfRepr(self):
480
+ return self.value
481
+
482
+ @classmethod
483
+ def paint_path(cls, fill, stroke):
484
+ """
485
+ Return the PDF operator to paint a path.
486
+
487
+ Parameters
488
+ ----------
489
+ fill : bool
490
+ Fill the path with the fill color.
491
+ stroke : bool
492
+ Stroke the outline of the path with the line color.
493
+ """
494
+ if stroke:
495
+ if fill:
496
+ return cls.fill_stroke
497
+ else:
498
+ return cls.stroke
499
+ else:
500
+ if fill:
501
+ return cls.fill
502
+ else:
503
+ return cls.endpath
504
+
505
+
506
+ class Stream:
507
+ """
508
+ PDF stream object.
509
+
510
+ This has no pdfRepr method. Instead, call begin(), then output the
511
+ contents of the stream by calling write(), and finally call end().
512
+ """
513
+ __slots__ = ('id', 'len', 'pdfFile', 'file', 'compressobj', 'extra', 'pos')
514
+
515
+ def __init__(self, id, len, file, extra=None, png=None):
516
+ """
517
+ Parameters
518
+ ----------
519
+ id : int
520
+ Object id of the stream.
521
+ len : Reference or None
522
+ An unused Reference object for the length of the stream;
523
+ None means to use a memory buffer so the length can be inlined.
524
+ file : PdfFile
525
+ The underlying object to write the stream to.
526
+ extra : dict from Name to anything, or None
527
+ Extra key-value pairs to include in the stream header.
528
+ png : dict or None
529
+ If the data is already png encoded, the decode parameters.
530
+ """
531
+ self.id = id # object id
532
+ self.len = len # id of length object
533
+ self.pdfFile = file
534
+ self.file = file.fh # file to which the stream is written
535
+ self.compressobj = None # compression object
536
+ if extra is None:
537
+ self.extra = dict()
538
+ else:
539
+ self.extra = extra.copy()
540
+ if png is not None:
541
+ self.extra.update({'Filter': Name('FlateDecode'),
542
+ 'DecodeParms': png})
543
+
544
+ self.pdfFile.recordXref(self.id)
545
+ if mpl.rcParams['pdf.compression'] and not png:
546
+ self.compressobj = zlib.compressobj(
547
+ mpl.rcParams['pdf.compression'])
548
+ if self.len is None:
549
+ self.file = BytesIO()
550
+ else:
551
+ self._writeHeader()
552
+ self.pos = self.file.tell()
553
+
554
+ def _writeHeader(self):
555
+ write = self.file.write
556
+ write(b"%d 0 obj\n" % self.id)
557
+ dict = self.extra
558
+ dict['Length'] = self.len
559
+ if mpl.rcParams['pdf.compression']:
560
+ dict['Filter'] = Name('FlateDecode')
561
+
562
+ write(pdfRepr(dict))
563
+ write(b"\nstream\n")
564
+
565
+ def end(self):
566
+ """Finalize stream."""
567
+
568
+ self._flush()
569
+ if self.len is None:
570
+ contents = self.file.getvalue()
571
+ self.len = len(contents)
572
+ self.file = self.pdfFile.fh
573
+ self._writeHeader()
574
+ self.file.write(contents)
575
+ self.file.write(b"\nendstream\nendobj\n")
576
+ else:
577
+ length = self.file.tell() - self.pos
578
+ self.file.write(b"\nendstream\nendobj\n")
579
+ self.pdfFile.writeObject(self.len, length)
580
+
581
+ def write(self, data):
582
+ """Write some data on the stream."""
583
+
584
+ if self.compressobj is None:
585
+ self.file.write(data)
586
+ else:
587
+ compressed = self.compressobj.compress(data)
588
+ self.file.write(compressed)
589
+
590
+ def _flush(self):
591
+ """Flush the compression object."""
592
+
593
+ if self.compressobj is not None:
594
+ compressed = self.compressobj.flush()
595
+ self.file.write(compressed)
596
+ self.compressobj = None
597
+
598
+
599
+ def _get_pdf_charprocs(font_path, glyph_indices):
600
+ font = get_font(font_path)
601
+ conv = 1000 / font.units_per_EM # Conversion to PS units (1/1000's).
602
+ procs = {}
603
+ for glyph_index in glyph_indices:
604
+ g = font.load_glyph(glyph_index, LoadFlags.NO_SCALE)
605
+ d1 = [
606
+ round(g.horiAdvance * conv), 0,
607
+ # Round bbox corners *outwards*, so that they indeed bound the glyph.
608
+ math.floor(g.bbox[0] * conv), math.floor(g.bbox[1] * conv),
609
+ math.ceil(g.bbox[2] * conv), math.ceil(g.bbox[3] * conv),
610
+ ]
611
+ v, c = font.get_path()
612
+ v = (v * 64 * conv).round() # Back to TrueType's internal units (1/64's).
613
+ procs[font.get_glyph_name(glyph_index)] = (
614
+ " ".join(map(str, d1)).encode("ascii") + b" d1\n"
615
+ + _path.convert_to_string(
616
+ Path(v, c), None, None, False, None, 0,
617
+ # no code for quad Beziers triggers auto-conversion to cubics.
618
+ [b"m", b"l", b"", b"c", b"h"], True)
619
+ + b"f")
620
+ return procs
621
+
622
+
623
+ def _pack_bits(values, bits):
624
+ """Rows of the (h, w) uint8 *values* packed *bits* (1, 2, 4 or 8) per sample."""
625
+ if bits == 8:
626
+ return values
627
+ height, width = values.shape
628
+ per = 8 // bits
629
+ padded = np.zeros((height, -(-width // per) * per), np.uint8)
630
+ padded[:, :width] = values
631
+ shifts = (8 - bits * np.arange(1, per + 1)).astype(np.uint8)
632
+ return np.bitwise_or.reduce(padded.reshape(height, -1, per) << shifts, axis=2)
633
+
634
+
635
+ class PdfFile:
636
+ """PDF file object."""
637
+
638
+ def __init__(self, filename, metadata=None):
639
+ """
640
+ Parameters
641
+ ----------
642
+ filename : str or path-like or file-like
643
+ Output target; if a string, a file will be opened for writing.
644
+
645
+ metadata : dict from strings to strings and dates
646
+ Information dictionary object (see PDF reference section 10.2.1
647
+ 'Document Information Dictionary'), e.g.:
648
+ ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.
649
+
650
+ The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
651
+ 'Creator', 'Producer', 'CreationDate', 'ModDate', and
652
+ 'Trapped'. Values have been predefined for 'Creator', 'Producer'
653
+ and 'CreationDate'. They can be removed by setting them to `None`.
654
+ """
655
+ super().__init__()
656
+
657
+ self._object_seq = itertools.count(1) # consumed by reserveObject
658
+ self.xrefTable = [[0, 65535, 'the zero object']]
659
+ self.passed_in_file_object = False
660
+ self.original_file_like = None
661
+ self.tell_base = 0
662
+ fh, opened = cbook.to_filehandle(filename, "wb", return_opened=True)
663
+ if not opened:
664
+ try:
665
+ self.tell_base = filename.tell()
666
+ except OSError:
667
+ fh = BytesIO()
668
+ self.original_file_like = filename
669
+ else:
670
+ fh = filename
671
+ self.passed_in_file_object = True
672
+
673
+ self.fh = fh
674
+ self.currentstream = None # stream object to write to, if any
675
+ fh.write(b"%PDF-1.4\n") # 1.4 is the first version to have alpha
676
+ # Output some eight-bit chars as a comment so various utilities
677
+ # recognize the file as binary by looking at the first few
678
+ # lines (see note in section 3.4.1 of the PDF reference).
679
+ fh.write(b"%\254\334 \253\272\n")
680
+
681
+ self.rootObject = self.reserveObject('root')
682
+ self.pagesObject = self.reserveObject('pages')
683
+ self.pageList = []
684
+ self.fontObject = self.reserveObject('fonts')
685
+ self._extGStateObject = self.reserveObject('extended graphics states')
686
+ self.hatchObject = self.reserveObject('tiling patterns')
687
+ self.gouraudObject = self.reserveObject('Gouraud triangles')
688
+ self.XObjectObject = self.reserveObject('external objects')
689
+ self.resourceObject = self.reserveObject('resources')
690
+
691
+ root = {'Type': Name('Catalog'),
692
+ 'Pages': self.pagesObject}
693
+ self.writeObject(self.rootObject, root)
694
+
695
+ self.infoDict = _create_pdf_info_dict('pdf', metadata or {})
696
+
697
+ self._internal_font_seq = (Name(f'F{i}') for i in itertools.count(1))
698
+ self._fontNames = {} # maps filenames to internal font names
699
+ self._dviFontInfo = {} # maps pdf names to dvifonts
700
+ self._character_tracker = _backend_pdf_ps.CharacterTracker(
701
+ _backend_pdf_ps._FONT_MAX_GLYPH.get(mpl.rcParams['ps.fonttype'], 0))
702
+
703
+ self.alphaStates = {} # maps alpha values to graphics state objects
704
+ self._alpha_state_seq = (Name(f'A{i}') for i in itertools.count(1))
705
+ self._soft_mask_states = {}
706
+ self._soft_mask_seq = (Name(f'SM{i}') for i in itertools.count(1))
707
+ self._soft_mask_groups = []
708
+ self._hatch_patterns = {}
709
+ self._hatch_pattern_seq = (Name(f'H{i}') for i in itertools.count(1))
710
+ self.gouraudTriangles = []
711
+
712
+ self._images = {}
713
+ self._image_seq = (Name(f'I{i}') for i in itertools.count(1))
714
+
715
+ self.markers = {}
716
+
717
+ self.paths = []
718
+
719
+ # A list of annotations for each page. Each entry is a tuple of the
720
+ # overall Annots object reference that's inserted into the page object,
721
+ # followed by a list of the actual annotations.
722
+ self._annotations = []
723
+ # For annotations added before a page is created; mostly for the
724
+ # purpose of newTextnote.
725
+ self.pageAnnotations = []
726
+
727
+ # The PDF spec recommends to include every procset
728
+ procsets = [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()]
729
+
730
+ # Write resource dictionary.
731
+ # Possibly TODO: more general ExtGState (graphics state dictionaries)
732
+ # ColorSpace Pattern Shading Properties
733
+ resources = {'Font': self.fontObject,
734
+ 'XObject': self.XObjectObject,
735
+ 'ExtGState': self._extGStateObject,
736
+ 'Pattern': self.hatchObject,
737
+ 'Shading': self.gouraudObject,
738
+ 'ProcSet': procsets}
739
+ self.writeObject(self.resourceObject, resources)
740
+
741
+ fontNames = _api.deprecated("3.11")(property(lambda self: self._fontNames))
742
+ multi_byte_charprocs = _api.deprecated("3.11")(property(lambda _: {}))
743
+ type1Descriptors = _api.deprecated("3.11")(property(lambda _: {}))
744
+
745
+ @_api.deprecated("3.11")
746
+ @property
747
+ def dviFontInfo(self):
748
+ d = {}
749
+ tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map'))
750
+ for pdfname, dvifont in self._dviFontInfo.items():
751
+ psfont = tex_font_map[dvifont.texname]
752
+ if psfont.filename is None:
753
+ raise ValueError(
754
+ "No usable font file found for {} (TeX: {}); "
755
+ "the font may lack a Type-1 version"
756
+ .format(psfont.psname, dvifont.texname))
757
+ d[dvifont.texname] = types.SimpleNamespace(
758
+ dvifont=dvifont,
759
+ pdfname=pdfname,
760
+ fontfile=psfont.filename,
761
+ basefont=psfont.psname,
762
+ encodingfile=psfont.encoding,
763
+ effects=psfont.effects,
764
+ )
765
+ return d
766
+
767
+ def newPage(self, width, height):
768
+ self.endStream()
769
+
770
+ self.width, self.height = width, height
771
+ contentObject = self.reserveObject('page contents')
772
+ annotsObject = self.reserveObject('annotations')
773
+ thePage = {'Type': Name('Page'),
774
+ 'Parent': self.pagesObject,
775
+ 'Resources': self.resourceObject,
776
+ 'MediaBox': [0, 0, 72 * width, 72 * height],
777
+ 'Contents': contentObject,
778
+ 'Annots': annotsObject,
779
+ }
780
+ pageObject = self.reserveObject('page')
781
+ self.writeObject(pageObject, thePage)
782
+ self.pageList.append(pageObject)
783
+ self._annotations.append((annotsObject, self.pageAnnotations))
784
+
785
+ self.beginStream(contentObject.id,
786
+ self.reserveObject('length of content stream'))
787
+ # Initialize the pdf graphics state to match the default Matplotlib
788
+ # graphics context (colorspace and joinstyle).
789
+ self.output(Name('DeviceRGB'), Op.setcolorspace_stroke)
790
+ self.output(Name('DeviceRGB'), Op.setcolorspace_nonstroke)
791
+ self.output(GraphicsContextPdf.joinstyles['round'], Op.setlinejoin)
792
+
793
+ # Clear the list of annotations for the next page
794
+ self.pageAnnotations = []
795
+
796
+ def newTextnote(self, text, positionRect=[-100, -100, 0, 0]):
797
+ # Create a new annotation of type text
798
+ theNote = {'Type': Name('Annot'),
799
+ 'Subtype': Name('Text'),
800
+ 'Contents': text,
801
+ 'Rect': positionRect,
802
+ }
803
+ self.pageAnnotations.append(theNote)
804
+
805
+ @staticmethod
806
+ def _get_subset_prefix(charset):
807
+ """
808
+ Get a prefix for a subsetted font name.
809
+
810
+ The prefix is six uppercase letters followed by a plus sign;
811
+ see PDF reference section 5.5.3 Font Subsets.
812
+ """
813
+ def toStr(n, base):
814
+ if n < base:
815
+ return string.ascii_uppercase[n]
816
+ else:
817
+ return (
818
+ toStr(n // base, base) + string.ascii_uppercase[n % base]
819
+ )
820
+
821
+ # encode to string using base 26
822
+ hashed = hash(charset) % ((sys.maxsize + 1) * 2)
823
+ prefix = toStr(hashed, 26)
824
+
825
+ # get first 6 characters from prefix
826
+ return prefix[:6] + "+"
827
+
828
+ @staticmethod
829
+ def _get_subsetted_psname(ps_name, charmap):
830
+ return PdfFile._get_subset_prefix(frozenset(charmap.values())) + ps_name
831
+
832
+ def finalize(self):
833
+ """Write out the various deferred objects and the pdf end matter."""
834
+
835
+ self.endStream()
836
+ self._write_annotations()
837
+ self.writeFonts()
838
+ self.writeExtGSTates()
839
+ self._write_soft_mask_groups()
840
+ self.writeHatches()
841
+ self.writeGouraudTriangles()
842
+ xobjects = {
843
+ name: ob for image, name, ob in self._images.values()}
844
+ for tup in self.markers.values():
845
+ xobjects[tup[0]] = tup[1]
846
+ for name, path, trans, ob, join, cap, padding, filled, stroked \
847
+ in self.paths:
848
+ xobjects[name] = ob
849
+ self.writeObject(self.XObjectObject, xobjects)
850
+ self.writeImages()
851
+ self.writeMarkers()
852
+ self.writePathCollectionTemplates()
853
+ self.writeObject(self.pagesObject,
854
+ {'Type': Name('Pages'),
855
+ 'Kids': self.pageList,
856
+ 'Count': len(self.pageList)})
857
+ self.writeInfoDict()
858
+
859
+ # Finalize the file
860
+ self.writeXref()
861
+ self.writeTrailer()
862
+
863
+ def close(self):
864
+ """Flush all buffers and free all resources."""
865
+
866
+ self.endStream()
867
+ if self.passed_in_file_object:
868
+ self.fh.flush()
869
+ else:
870
+ if self.original_file_like is not None:
871
+ self.original_file_like.write(self.fh.getvalue())
872
+ self.fh.close()
873
+
874
+ def write(self, data):
875
+ if self.currentstream is None:
876
+ self.fh.write(data)
877
+ else:
878
+ self.currentstream.write(data)
879
+
880
+ def output(self, *data):
881
+ self.write(_fill([pdfRepr(x) for x in data]))
882
+ self.write(b'\n')
883
+
884
+ def beginStream(self, id, len, extra=None, png=None):
885
+ assert self.currentstream is None
886
+ self.currentstream = Stream(id, len, self, extra, png)
887
+
888
+ def endStream(self):
889
+ if self.currentstream is not None:
890
+ self.currentstream.end()
891
+ self.currentstream = None
892
+
893
+ def outputStream(self, ref, data, *, extra=None):
894
+ self.beginStream(ref.id, None, extra)
895
+ self.currentstream.write(data)
896
+ self.endStream()
897
+
898
+ def _write_annotations(self):
899
+ for annotsObject, annotations in self._annotations:
900
+ self.writeObject(annotsObject, annotations)
901
+
902
+ def fontName(self, fontprop, subset=0):
903
+ """
904
+ Select a font based on fontprop and return a name suitable for
905
+ ``Op.selectfont``. If fontprop is a string, it will be interpreted
906
+ as the filename of the font.
907
+ """
908
+
909
+ if isinstance(fontprop, FontPath):
910
+ filenames = [fontprop]
911
+ elif isinstance(fontprop, str):
912
+ filenames = [FontPath(fontprop, 0)]
913
+ elif mpl.rcParams['pdf.use14corefonts']:
914
+ filenames = _fontManager._find_fonts_by_props(
915
+ fontprop, fontext='afm', directory=RendererPdf._afm_font_dir
916
+ )
917
+ else:
918
+ filenames = _fontManager._find_fonts_by_props(fontprop)
919
+ first_Fx = None
920
+ for fname in filenames:
921
+ Fx = self._fontNames.get((fname, subset))
922
+ if not first_Fx:
923
+ first_Fx = Fx
924
+ if Fx is None:
925
+ Fx = next(self._internal_font_seq)
926
+ self._fontNames[(fname, subset)] = Fx
927
+ _log.debug('Assigning font %s (subset %d) = %r', Fx, subset, fname)
928
+ if not first_Fx:
929
+ first_Fx = Fx
930
+
931
+ # find_fontsprop's first value always adheres to
932
+ # findfont's value, so technically no behaviour change
933
+ return first_Fx
934
+
935
+ def dviFontName(self, dvifont):
936
+ """
937
+ Given a dvi font object, return a name suitable for Op.selectfont.
938
+
939
+ Register the font internally (in ``_dviFontInfo``) if not yet registered.
940
+ """
941
+ pdfname = Name(f"F-{dvifont.texname.decode('ascii')}")
942
+ _log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname)
943
+ self._dviFontInfo[pdfname] = dvifont
944
+ return Name(pdfname)
945
+
946
+ def writeFonts(self):
947
+ fonts = {}
948
+ for pdfname, dvifont in sorted(self._dviFontInfo.items()):
949
+ _log.debug('Embedding Type-1 font %s from dvi.', dvifont.texname)
950
+ fonts[pdfname] = self._embedTeXFont(dvifont)
951
+ for (filename, subset), Fx in sorted(self._fontNames.items()):
952
+ _log.debug('Embedding font %r:%d.', filename, subset)
953
+ if filename.endswith('.afm'):
954
+ # from pdf.use14corefonts
955
+ _log.debug('Writing AFM font.')
956
+ fonts[Fx] = self._write_afm_font(filename)
957
+ else:
958
+ # a normal TrueType font
959
+ _log.debug('Writing TrueType font.')
960
+ charmap = self._character_tracker.used[filename][subset]
961
+ fonts[Fx] = self.embedTTF(filename, subset, charmap)
962
+ self.writeObject(self.fontObject, fonts)
963
+
964
+ def _write_afm_font(self, filename):
965
+ with open(filename, 'rb') as fh:
966
+ font = AFM(fh)
967
+ fontname = font.get_fontname()
968
+ fontdict = {'Type': Name('Font'),
969
+ 'Subtype': Name('Type1'),
970
+ 'BaseFont': Name(fontname),
971
+ 'Encoding': Name('WinAnsiEncoding')}
972
+ fontdictObject = self.reserveObject('font dictionary')
973
+ self.writeObject(fontdictObject, fontdict)
974
+ return fontdictObject
975
+
976
+ def _embedTeXFont(self, dvifont):
977
+ tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map'))
978
+ psfont = tex_font_map[dvifont.texname]
979
+ if psfont.filename is None:
980
+ raise ValueError(
981
+ "No usable font file found for {} (TeX: {}); "
982
+ "the font may lack a Type-1 version"
983
+ .format(psfont.psname, dvifont.texname))
984
+
985
+ # The font dictionary is the top-level object describing a font
986
+ fontdictObject = self.reserveObject('font dictionary')
987
+ fontdict = {
988
+ 'Type': Name('Font'),
989
+ 'Subtype': Name('Type1'),
990
+ }
991
+
992
+ # Read the font file and apply any encoding changes and effects
993
+ t1font = _type1font.Type1Font(psfont.filename)
994
+ if psfont.encoding is not None:
995
+ t1font = t1font.with_encoding(
996
+ {i: c for i, c in enumerate(dviread._parse_enc(psfont.encoding))}
997
+ )
998
+ if psfont.effects:
999
+ t1font = t1font.transform(psfont.effects)
1000
+
1001
+ # Reduce the font to only the glyphs used in the document, get the encoding
1002
+ # for that subset, and compute various properties based on the encoding.
1003
+ font_path = FontPath(dvifont.fname, dvifont.face_index)
1004
+ charmap = self._character_tracker.used[font_path][0]
1005
+ chars = {
1006
+ # DVI type 1 fonts always map single glyph to single character.
1007
+ ord(self._character_tracker.subset_to_unicode(font_path, 0, ccode))
1008
+ for ccode in charmap
1009
+ }
1010
+ t1font = t1font.subset(chars, self._get_subset_prefix(charmap.values()))
1011
+ fontdict['BaseFont'] = Name(t1font.prop['FontName'])
1012
+ # createType1Descriptor writes the font data as a side effect
1013
+ fontdict['FontDescriptor'] = self.createType1Descriptor(t1font)
1014
+ encoding = t1font.prop['Encoding']
1015
+ fontdict['Encoding'] = self._generate_encoding(encoding)
1016
+ fc = fontdict['FirstChar'] = min(encoding.keys(), default=0)
1017
+ lc = fontdict['LastChar'] = max(encoding.keys(), default=255)
1018
+ # Convert glyph widths from TeX 12.20 fixed point to 1/1000 text space units
1019
+ font_metrics = dvifont._metrics
1020
+ widths = [(1000 * glyph_metrics.tex_width) >> 20
1021
+ if (glyph_metrics := font_metrics.get_metrics(char)) else 0
1022
+ for char in range(fc, lc + 1)]
1023
+ fontdict['Widths'] = widthsObject = self.reserveObject('glyph widths')
1024
+ self.writeObject(widthsObject, widths)
1025
+ self.writeObject(fontdictObject, fontdict)
1026
+ return fontdictObject
1027
+
1028
+ def _generate_encoding(self, encoding):
1029
+ prev = -2
1030
+ result = []
1031
+ for code, name in sorted(encoding.items()):
1032
+ if code != prev + 1:
1033
+ result.append(code)
1034
+ prev = code
1035
+ result.append(Name(name))
1036
+ return {
1037
+ 'Type': Name('Encoding'),
1038
+ 'Differences': result
1039
+ }
1040
+
1041
+ @_api.delete_parameter("3.11", "fontfile")
1042
+ def createType1Descriptor(self, t1font, fontfile=None):
1043
+ # Create and write the font descriptor and the font file
1044
+ # of a Type-1 font
1045
+ fontdescObject = self.reserveObject('font descriptor')
1046
+ fontfileObject = self.reserveObject('font file')
1047
+
1048
+ italic_angle = t1font.prop['ItalicAngle']
1049
+ fixed_pitch = t1font.prop['isFixedPitch']
1050
+
1051
+ flags = 0
1052
+ # fixed width
1053
+ if fixed_pitch:
1054
+ flags |= 1 << 0
1055
+ # TODO: serif
1056
+ if 0:
1057
+ flags |= 1 << 1
1058
+ # TODO: symbolic (most TeX fonts are)
1059
+ if 1:
1060
+ flags |= 1 << 2
1061
+ # non-symbolic
1062
+ else:
1063
+ flags |= 1 << 5
1064
+ # italic
1065
+ if italic_angle:
1066
+ flags |= 1 << 6
1067
+ # TODO: all caps
1068
+ if 0:
1069
+ flags |= 1 << 16
1070
+ # TODO: small caps
1071
+ if 0:
1072
+ flags |= 1 << 17
1073
+ # TODO: force bold
1074
+ if 0:
1075
+ flags |= 1 << 18
1076
+
1077
+ encoding = t1font.prop['Encoding']
1078
+ charset = ''.join(
1079
+ sorted(
1080
+ f'/{c}' for c in encoding.values()
1081
+ if c != '.notdef'
1082
+ )
1083
+ )
1084
+
1085
+ descriptor = {
1086
+ 'Type': Name('FontDescriptor'),
1087
+ 'FontName': Name(t1font.prop['FontName']),
1088
+ 'Flags': flags,
1089
+ 'FontBBox': t1font.prop['FontBBox'],
1090
+ 'ItalicAngle': italic_angle,
1091
+ 'Ascent': t1font.prop['FontBBox'][3],
1092
+ 'Descent': t1font.prop['FontBBox'][1],
1093
+ 'CapHeight': 1000, # TODO: find this out
1094
+ 'XHeight': 500, # TODO: this one too
1095
+ 'FontFile': fontfileObject,
1096
+ 'FontFamily': t1font.prop['FamilyName'],
1097
+ 'StemV': 50, # TODO
1098
+ 'CharSet': charset,
1099
+ # (see also revision 3874; but not all TeX distros have AFM files!)
1100
+ # 'FontWeight': a number where 400 = Regular, 700 = Bold
1101
+ }
1102
+
1103
+ self.writeObject(fontdescObject, descriptor)
1104
+
1105
+ self.outputStream(fontfileObject, b"".join(t1font.parts[:2]),
1106
+ extra={'Length1': len(t1font.parts[0]),
1107
+ 'Length2': len(t1font.parts[1]),
1108
+ 'Length3': 0})
1109
+
1110
+ return fontdescObject
1111
+
1112
+ _identityToUnicodeCMap = b"""/CIDInit /ProcSet findresource begin
1113
+ 12 dict begin
1114
+ begincmap
1115
+ /CIDSystemInfo
1116
+ << /Registry (Adobe)
1117
+ /Ordering (UCS)
1118
+ /Supplement 0
1119
+ >> def
1120
+ /CMapName /Adobe-Identity-UCS def
1121
+ /CMapType 2 def
1122
+ 1 begincodespacerange
1123
+ <0000> <ffff>
1124
+ endcodespacerange
1125
+ %d beginbfrange
1126
+ %s
1127
+ endbfrange
1128
+ endcmap
1129
+ CMapName currentdict /CMap defineresource pop
1130
+ end
1131
+ end"""
1132
+
1133
+ def embedTTF(self, filename, subset_index, charmap):
1134
+ """Embed the TTF font from the named file into the document."""
1135
+ font = get_font(filename)
1136
+ fonttype = mpl.rcParams['pdf.fonttype']
1137
+
1138
+ def cvt(length, upe=font.units_per_EM, nearest=True):
1139
+ """Convert font coordinates to PDF glyph coordinates."""
1140
+ value = length / upe * 1000
1141
+ if nearest:
1142
+ return round(value)
1143
+ # Best(?) to round away from zero for bounding boxes and the like.
1144
+ if value < 0:
1145
+ return math.floor(value)
1146
+ else:
1147
+ return math.ceil(value)
1148
+
1149
+ def generate_unicode_cmap(subset_index, charmap):
1150
+ # Make the ToUnicode CMap.
1151
+ last_ccode = -2
1152
+ unicode_groups = []
1153
+ for ccode in sorted(charmap.keys()):
1154
+ if ccode != last_ccode + 1:
1155
+ unicode_groups.append([ccode, ccode])
1156
+ else:
1157
+ unicode_groups[-1][1] = ccode
1158
+ last_ccode = ccode
1159
+
1160
+ def _to_unicode(ccode):
1161
+ chars = self._character_tracker.subset_to_unicode(
1162
+ filename, subset_index, ccode)
1163
+ hexstr = chars.encode('utf-16be').hex()
1164
+ return f'<{hexstr}>'
1165
+
1166
+ width = 2 if fonttype == 3 else 4
1167
+ unicode_bfrange = []
1168
+ for start, end in unicode_groups:
1169
+ real_values = ' '.join(_to_unicode(x) for x in range(start, end+1))
1170
+ unicode_bfrange.append(
1171
+ f'<{start:0{width}x}> <{end:0{width}x}> [{real_values}]')
1172
+ unicode_cmap = (self._identityToUnicodeCMap %
1173
+ (len(unicode_groups),
1174
+ '\n'.join(unicode_bfrange).encode('ascii')))
1175
+
1176
+ return unicode_cmap
1177
+
1178
+ def embedTTFType3(font, subset_index, charmap, descriptor):
1179
+ """The Type 3-specific part of embedding a Truetype font"""
1180
+ widthsObject = self.reserveObject('font widths')
1181
+ fontdescObject = self.reserveObject('font descriptor')
1182
+ fontdictObject = self.reserveObject('font dictionary')
1183
+ charprocsObject = self.reserveObject('character procs')
1184
+ toUnicodeMapObject = self.reserveObject('ToUnicode map')
1185
+ differencesArray = []
1186
+ firstchar, lastchar = min(charmap), max(charmap)
1187
+ bbox = [cvt(x, nearest=False) for x in font.bbox]
1188
+
1189
+ fontdict = {
1190
+ 'Type': Name('Font'),
1191
+ 'BaseFont': ps_name,
1192
+ 'FirstChar': firstchar,
1193
+ 'LastChar': lastchar,
1194
+ 'FontDescriptor': fontdescObject,
1195
+ 'Subtype': Name('Type3'),
1196
+ 'Name': descriptor['FontName'],
1197
+ 'FontBBox': bbox,
1198
+ 'FontMatrix': [.001, 0, 0, .001, 0, 0],
1199
+ 'CharProcs': charprocsObject,
1200
+ 'Encoding': {
1201
+ 'Type': Name('Encoding'),
1202
+ 'Differences': differencesArray},
1203
+ 'Widths': widthsObject,
1204
+ 'ToUnicode': toUnicodeMapObject,
1205
+ }
1206
+
1207
+ # Make the "Widths" array
1208
+ def get_char_width(charcode):
1209
+ width = font.load_glyph(
1210
+ charmap.get(charcode, 0),
1211
+ flags=LoadFlags.NO_SCALE | LoadFlags.NO_HINTING).horiAdvance
1212
+ return cvt(width)
1213
+ widths = [get_char_width(charcode)
1214
+ for charcode in range(firstchar, lastchar+1)]
1215
+ descriptor['MaxWidth'] = max(widths)
1216
+
1217
+ # Make the "Differences" array with the whole set of character codes that we
1218
+ # need from this font.
1219
+ differences = sorted([
1220
+ (ccode, font.get_glyph_name(gind)) for ccode, gind in charmap.items()
1221
+ ])
1222
+ last_c = -2
1223
+ for c, name in differences:
1224
+ if c != last_c + 1:
1225
+ differencesArray.append(c)
1226
+ differencesArray.append(Name(name))
1227
+ last_c = c
1228
+
1229
+ # Make the charprocs array.
1230
+ rawcharprocs = _get_pdf_charprocs(filename, charmap.values())
1231
+ charprocs = {}
1232
+ for charname in sorted(rawcharprocs):
1233
+ stream = rawcharprocs[charname]
1234
+ charprocObject = self.reserveObject('charProc')
1235
+ self.outputStream(charprocObject, stream)
1236
+ charprocs[charname] = charprocObject
1237
+
1238
+ unicode_cmap = generate_unicode_cmap(subset_index, charmap)
1239
+
1240
+ # Write everything out
1241
+ self.writeObject(fontdictObject, fontdict)
1242
+ self.writeObject(fontdescObject, descriptor)
1243
+ self.writeObject(widthsObject, widths)
1244
+ self.writeObject(charprocsObject, charprocs)
1245
+ self.outputStream(toUnicodeMapObject, unicode_cmap)
1246
+
1247
+ return fontdictObject
1248
+
1249
+ def embedTTFType42(font, subset_index, charmap, descriptor):
1250
+ """The Type 42-specific part of embedding a Truetype font"""
1251
+ fontdescObject = self.reserveObject('font descriptor')
1252
+ cidFontDictObject = self.reserveObject('CID font dictionary')
1253
+ type0FontDictObject = self.reserveObject('Type 0 font dictionary')
1254
+ cidToGidMapObject = self.reserveObject('CIDToGIDMap stream')
1255
+ fontfileObject = self.reserveObject('font file stream')
1256
+ wObject = self.reserveObject('Type 0 widths')
1257
+ toUnicodeMapObject = self.reserveObject('ToUnicode map')
1258
+
1259
+ _log.debug("SUBSET %r:%d characters: %s", filename, subset_index, charmap)
1260
+ with _backend_pdf_ps.get_glyphs_subset(filename,
1261
+ charmap.values()) as subset:
1262
+ fontdata = _backend_pdf_ps.font_as_file(subset.font)
1263
+ _log.debug(
1264
+ "SUBSET %r:%d %d -> %d", filename, subset_index,
1265
+ os.stat(filename).st_size, fontdata.getbuffer().nbytes
1266
+ )
1267
+
1268
+ # reload the font object from the subset
1269
+ # (all the necessary data could probably be obtained directly
1270
+ # using fontLib.ttLib)
1271
+ font = FT2Font(fontdata)
1272
+
1273
+ cidFontDict = {
1274
+ 'Type': Name('Font'),
1275
+ 'Subtype': Name('CIDFontType2'),
1276
+ 'BaseFont': ps_name,
1277
+ 'CIDSystemInfo': {
1278
+ 'Registry': 'Adobe',
1279
+ 'Ordering': 'Identity',
1280
+ 'Supplement': 0},
1281
+ 'FontDescriptor': fontdescObject,
1282
+ 'W': wObject,
1283
+ 'CIDToGIDMap': cidToGidMapObject
1284
+ }
1285
+
1286
+ type0FontDict = {
1287
+ 'Type': Name('Font'),
1288
+ 'Subtype': Name('Type0'),
1289
+ 'BaseFont': ps_name,
1290
+ 'Encoding': Name('Identity-H'),
1291
+ 'DescendantFonts': [cidFontDictObject],
1292
+ 'ToUnicode': toUnicodeMapObject
1293
+ }
1294
+
1295
+ # Make fontfile stream
1296
+ descriptor['FontFile2'] = fontfileObject
1297
+ self.outputStream(
1298
+ fontfileObject, fontdata.getvalue(),
1299
+ extra={'Length1': fontdata.getbuffer().nbytes})
1300
+
1301
+ # Make the 'W' (Widths) array and CidToGidMap at the same time.
1302
+ cid_to_gid_map = ['\0'] * 65536
1303
+ widths = []
1304
+ max_ccode = 0
1305
+ for ccode, orig_glyph_index in charmap.items():
1306
+ gind = subset.glyph_index_map[orig_glyph_index]
1307
+ glyph = font.load_glyph(gind,
1308
+ flags=LoadFlags.NO_SCALE | LoadFlags.NO_HINTING)
1309
+ widths.append((ccode, cvt(glyph.horiAdvance)))
1310
+ cid_to_gid_map[ccode] = chr(gind)
1311
+ max_ccode = max(ccode, max_ccode)
1312
+ widths.sort()
1313
+ cid_to_gid_map = cid_to_gid_map[:max_ccode + 1]
1314
+
1315
+ last_ccode = -2
1316
+ w = []
1317
+ max_width = 0
1318
+ for ccode, width in widths:
1319
+ if ccode != last_ccode + 1:
1320
+ w.append(ccode)
1321
+ w.append([width])
1322
+ else:
1323
+ w[-1].append(width)
1324
+ max_width = max(max_width, width)
1325
+ last_ccode = ccode
1326
+
1327
+ # CIDToGIDMap stream
1328
+ cid_to_gid_map = "".join(cid_to_gid_map).encode("utf-16be")
1329
+ self.outputStream(cidToGidMapObject, cid_to_gid_map)
1330
+
1331
+ # ToUnicode CMap
1332
+ unicode_cmap = generate_unicode_cmap(subset_index, charmap)
1333
+ self.outputStream(toUnicodeMapObject, unicode_cmap)
1334
+
1335
+ descriptor['MaxWidth'] = max_width
1336
+
1337
+ # Write everything out
1338
+ self.writeObject(cidFontDictObject, cidFontDict)
1339
+ self.writeObject(type0FontDictObject, type0FontDict)
1340
+ self.writeObject(fontdescObject, descriptor)
1341
+ self.writeObject(wObject, w)
1342
+
1343
+ return type0FontDictObject
1344
+
1345
+ # Beginning of main embedTTF function...
1346
+
1347
+ ps_name = self._get_subsetted_psname(font.postscript_name, charmap)
1348
+ ps_name = ps_name.encode('ascii', 'replace')
1349
+ ps_name = Name(ps_name)
1350
+ pclt = font.get_sfnt_table('pclt') or {'capHeight': 0, 'xHeight': 0}
1351
+ post = font.get_sfnt_table('post') or {'italicAngle': (0, 0)}
1352
+ ff = font.face_flags
1353
+ sf = font.style_flags
1354
+
1355
+ flags = 0
1356
+ symbolic = False # ps_name.name in ('Cmsy10', 'Cmmi10', 'Cmex10')
1357
+ if FaceFlags.FIXED_WIDTH in ff:
1358
+ flags |= 1 << 0
1359
+ if 0: # TODO: serif
1360
+ flags |= 1 << 1
1361
+ if symbolic:
1362
+ flags |= 1 << 2
1363
+ else:
1364
+ flags |= 1 << 5
1365
+ if StyleFlags.ITALIC in sf:
1366
+ flags |= 1 << 6
1367
+ if 0: # TODO: all caps
1368
+ flags |= 1 << 16
1369
+ if 0: # TODO: small caps
1370
+ flags |= 1 << 17
1371
+ if 0: # TODO: force bold
1372
+ flags |= 1 << 18
1373
+
1374
+ descriptor = {
1375
+ 'Type': Name('FontDescriptor'),
1376
+ 'FontName': ps_name,
1377
+ 'Flags': flags,
1378
+ 'FontBBox': [cvt(x, nearest=False) for x in font.bbox],
1379
+ 'Ascent': cvt(font.ascender, nearest=False),
1380
+ 'Descent': cvt(font.descender, nearest=False),
1381
+ 'CapHeight': cvt(pclt['capHeight'], nearest=False),
1382
+ 'XHeight': cvt(pclt['xHeight']),
1383
+ 'ItalicAngle': post['italicAngle'][1], # ???
1384
+ 'StemV': 0 # ???
1385
+ }
1386
+
1387
+ if fonttype == 3:
1388
+ return embedTTFType3(font, subset_index, charmap, descriptor)
1389
+ elif fonttype == 42:
1390
+ return embedTTFType42(font, subset_index, charmap, descriptor)
1391
+
1392
+ def alphaState(self, alpha):
1393
+ """Return name of an ExtGState that sets alpha to the given value."""
1394
+
1395
+ state = self.alphaStates.get(alpha, None)
1396
+ if state is not None:
1397
+ return state[0]
1398
+
1399
+ name = next(self._alpha_state_seq)
1400
+ self.alphaStates[alpha] = \
1401
+ (name, {'Type': Name('ExtGState'),
1402
+ 'CA': alpha[0], 'ca': alpha[1]})
1403
+ return name
1404
+
1405
+ def _soft_mask_state(self, smask):
1406
+ """
1407
+ Return an ExtGState that sets the soft mask to the given shading.
1408
+
1409
+ Parameters
1410
+ ----------
1411
+ smask : Reference
1412
+ Reference to a shading in DeviceGray color space, whose luminosity
1413
+ is to be used as the alpha channel.
1414
+
1415
+ Returns
1416
+ -------
1417
+ Name
1418
+ """
1419
+
1420
+ state = self._soft_mask_states.get(smask, None)
1421
+ if state is not None:
1422
+ return state[0]
1423
+
1424
+ name = next(self._soft_mask_seq)
1425
+ groupOb = self.reserveObject('transparency group for soft mask')
1426
+ self._soft_mask_states[smask] = (
1427
+ name,
1428
+ {
1429
+ 'Type': Name('ExtGState'),
1430
+ 'AIS': False,
1431
+ 'SMask': {
1432
+ 'Type': Name('Mask'),
1433
+ 'S': Name('Luminosity'),
1434
+ 'BC': [1],
1435
+ 'G': groupOb
1436
+ }
1437
+ }
1438
+ )
1439
+ self._soft_mask_groups.append((
1440
+ groupOb,
1441
+ {
1442
+ 'Type': Name('XObject'),
1443
+ 'Subtype': Name('Form'),
1444
+ 'FormType': 1,
1445
+ 'Group': {
1446
+ 'S': Name('Transparency'),
1447
+ 'CS': Name('DeviceGray')
1448
+ },
1449
+ 'Matrix': [1, 0, 0, 1, 0, 0],
1450
+ 'Resources': {'Shading': {'S': smask}},
1451
+ 'BBox': [0, 0, 1, 1]
1452
+ },
1453
+ [Name('S'), Op.shading]
1454
+ ))
1455
+ return name
1456
+
1457
+ def writeExtGSTates(self):
1458
+ self.writeObject(
1459
+ self._extGStateObject,
1460
+ dict([
1461
+ *self.alphaStates.values(),
1462
+ *self._soft_mask_states.values()
1463
+ ])
1464
+ )
1465
+
1466
+ def _write_soft_mask_groups(self):
1467
+ for ob, attributes, content in self._soft_mask_groups:
1468
+ self.beginStream(ob.id, None, attributes)
1469
+ self.output(*content)
1470
+ self.endStream()
1471
+
1472
+ def hatchPattern(self, hatch_style):
1473
+ # The colors may come in as numpy arrays, which aren't hashable
1474
+ edge, face, hatch, lw = hatch_style
1475
+ if edge is not None:
1476
+ edge = tuple(edge)
1477
+ if face is not None:
1478
+ face = tuple(face)
1479
+ hatch_style = (edge, face, hatch, lw)
1480
+
1481
+ pattern = self._hatch_patterns.get(hatch_style, None)
1482
+ if pattern is not None:
1483
+ return pattern
1484
+
1485
+ name = next(self._hatch_pattern_seq)
1486
+ self._hatch_patterns[hatch_style] = name
1487
+ return name
1488
+
1489
+ hatchPatterns = _api.deprecated("3.10")(property(lambda self: {
1490
+ k: (e, f, h) for k, (e, f, h, l) in self._hatch_patterns.items()
1491
+ }))
1492
+
1493
+ def writeHatches(self):
1494
+ hatchDict = dict()
1495
+ sidelen = 72.0
1496
+ for hatch_style, name in self._hatch_patterns.items():
1497
+ ob = self.reserveObject('hatch pattern')
1498
+ hatchDict[name] = ob
1499
+ res = {'Procsets':
1500
+ [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()]}
1501
+ self.beginStream(
1502
+ ob.id, None,
1503
+ {'Type': Name('Pattern'),
1504
+ 'PatternType': 1, 'PaintType': 1, 'TilingType': 1,
1505
+ 'BBox': [0, 0, sidelen, sidelen],
1506
+ 'XStep': sidelen, 'YStep': sidelen,
1507
+ 'Resources': res,
1508
+ # Change origin to match Agg at top-left.
1509
+ 'Matrix': [1, 0, 0, 1, 0, self.height * 72]})
1510
+
1511
+ stroke_rgb, fill_rgb, hatch, lw = hatch_style
1512
+ self.output(stroke_rgb[0], stroke_rgb[1], stroke_rgb[2],
1513
+ Op.setrgb_stroke)
1514
+ if fill_rgb is not None:
1515
+ self.output(fill_rgb[0], fill_rgb[1], fill_rgb[2],
1516
+ Op.setrgb_nonstroke,
1517
+ 0, 0, sidelen, sidelen, Op.rectangle,
1518
+ Op.fill)
1519
+ self.output(stroke_rgb[0], stroke_rgb[1], stroke_rgb[2],
1520
+ Op.setrgb_nonstroke)
1521
+
1522
+ self.output(lw, Op.setlinewidth)
1523
+
1524
+ self.output(*self.pathOperations(
1525
+ Path.hatch(hatch),
1526
+ Affine2D().scale(sidelen),
1527
+ simplify=False))
1528
+ self.output(Op.fill_stroke)
1529
+
1530
+ self.endStream()
1531
+ self.writeObject(self.hatchObject, hatchDict)
1532
+
1533
+ def addGouraudTriangles(self, points, colors):
1534
+ """
1535
+ Add a Gouraud triangle shading.
1536
+
1537
+ Parameters
1538
+ ----------
1539
+ points : np.ndarray
1540
+ Triangle vertices, shape (n, 3, 2)
1541
+ where n = number of triangles, 3 = vertices, 2 = x, y.
1542
+ colors : np.ndarray
1543
+ Vertex colors, shape (n, 3, 1) or (n, 3, 4)
1544
+ as with points, but last dimension is either (gray,)
1545
+ or (r, g, b, alpha).
1546
+
1547
+ Returns
1548
+ -------
1549
+ Name, Reference
1550
+ """
1551
+ name = Name('GT%d' % len(self.gouraudTriangles))
1552
+ ob = self.reserveObject(f'Gouraud triangle {name}')
1553
+ self.gouraudTriangles.append((name, ob, points, colors))
1554
+ return name, ob
1555
+
1556
+ def writeGouraudTriangles(self):
1557
+ gouraudDict = dict()
1558
+ for name, ob, points, colors in self.gouraudTriangles:
1559
+ gouraudDict[name] = ob
1560
+ shape = points.shape
1561
+ flat_points = points.reshape((shape[0] * shape[1], 2))
1562
+ colordim = colors.shape[2]
1563
+ assert colordim in (1, 4)
1564
+ flat_colors = colors.reshape((shape[0] * shape[1], colordim))
1565
+ if colordim == 4:
1566
+ # strip the alpha channel
1567
+ colordim = 3
1568
+ points_min = np.min(flat_points, axis=0) - (1 << 8)
1569
+ points_max = np.max(flat_points, axis=0) + (1 << 8)
1570
+ factor = 0xffffffff / (points_max - points_min)
1571
+
1572
+ self.beginStream(
1573
+ ob.id, None,
1574
+ {'ShadingType': 4,
1575
+ 'BitsPerCoordinate': 32,
1576
+ 'BitsPerComponent': 8,
1577
+ 'BitsPerFlag': 8,
1578
+ 'ColorSpace': Name(
1579
+ 'DeviceRGB' if colordim == 3 else 'DeviceGray'
1580
+ ),
1581
+ 'AntiAlias': False,
1582
+ 'Decode': ([points_min[0], points_max[0],
1583
+ points_min[1], points_max[1]]
1584
+ + [0, 1] * colordim),
1585
+ })
1586
+
1587
+ streamarr = np.empty(
1588
+ (shape[0] * shape[1],),
1589
+ dtype=[('flags', 'u1'),
1590
+ ('points', '>u4', (2,)),
1591
+ ('colors', 'u1', (colordim,))])
1592
+ streamarr['flags'] = 0
1593
+ streamarr['points'] = (flat_points - points_min) * factor
1594
+ streamarr['colors'] = flat_colors[:, :colordim] * 255.0
1595
+
1596
+ self.write(streamarr.tobytes())
1597
+ self.endStream()
1598
+ self.writeObject(self.gouraudObject, gouraudDict)
1599
+
1600
+ def imageObject(self, image):
1601
+ """Return name of an image XObject representing the given image."""
1602
+
1603
+ entry = self._images.get(id(image), None)
1604
+ if entry is not None:
1605
+ return entry[1]
1606
+
1607
+ name = next(self._image_seq)
1608
+ ob = self.reserveObject(f'image {name}')
1609
+ self._images[id(image)] = (image, name, ob)
1610
+ return name
1611
+
1612
+ def _unpack(self, im):
1613
+ """
1614
+ Unpack image array *im* into ``(data, alpha)``, which have shape
1615
+ ``(height, width, 3)`` (RGB) or ``(height, width, 1)`` (grayscale or
1616
+ alpha), except that alpha is None if the image is fully opaque.
1617
+ """
1618
+ im = im[::-1]
1619
+ if im.ndim == 2:
1620
+ return im, None
1621
+ else:
1622
+ rgb = im[:, :, :3]
1623
+ rgb = np.array(rgb, order='C')
1624
+ # PDF needs a separate alpha image
1625
+ if im.shape[2] == 4:
1626
+ alpha = im[:, :, 3][..., None]
1627
+ if np.all(alpha == 255):
1628
+ alpha = None
1629
+ else:
1630
+ alpha = np.array(alpha, order='C')
1631
+ else:
1632
+ alpha = None
1633
+ return rgb, alpha
1634
+
1635
+ def _writeImg(self, data, id, smask=None):
1636
+ """
1637
+ Write the image *data*, of shape ``(height, width, 1)`` (grayscale) or
1638
+ ``(height, width, 3)`` (RGB), as pdf object *id* and with the soft mask
1639
+ (alpha channel) *smask*, which should be either None or a ``(height,
1640
+ width, 1)`` array.
1641
+ """
1642
+ height, width, color_channels = data.shape
1643
+ obj = {'Type': Name('XObject'),
1644
+ 'Subtype': Name('Image'),
1645
+ 'Width': width,
1646
+ 'Height': height,
1647
+ 'ColorSpace': Name({1: 'DeviceGray', 3: 'DeviceRGB'}[color_channels]),
1648
+ 'BitsPerComponent': 8}
1649
+ if smask:
1650
+ obj['SMask'] = smask
1651
+ if mpl.rcParams['pdf.compression']:
1652
+ # Rows with PNG predictors (the best filter of each row), deflated
1653
+ # by the Rust core; as matplotlib does with Pillow, RGB images of
1654
+ # at most 256 colors are written with an indexed color space.
1655
+ png = {'Predictor': 10, 'Colors': color_channels, 'Columns': width}
1656
+ data = np.ascontiguousarray(data, np.uint8)
1657
+ indexed = _mplrs.indexed_colors(data) if color_channels == 3 else None
1658
+ if indexed is not None:
1659
+ palette, indices = indexed
1660
+ num_colors = len(palette) // 3
1661
+ # Pillow's bit depth for a palette of this many colors.
1662
+ bit_depth = next(b for b in (1, 2, 4, 8) if num_colors <= 1 << b)
1663
+ png_data = _mplrs.zlib_png_rows(_pack_bits(indices, bit_depth), 1)
1664
+ obj['ColorSpace'] = [Name('Indexed'), Name('DeviceRGB'),
1665
+ num_colors - 1, palette]
1666
+ obj['BitsPerComponent'] = bit_depth
1667
+ png['Colors'] = 1
1668
+ png['BitsPerComponent'] = bit_depth
1669
+ else:
1670
+ png_data = _mplrs.zlib_png_rows(data.reshape(height, -1), color_channels)
1671
+ else:
1672
+ png = None
1673
+ self.beginStream(
1674
+ id,
1675
+ self.reserveObject('length of image stream'),
1676
+ obj,
1677
+ png=png
1678
+ )
1679
+ if png:
1680
+ self.currentstream.write(png_data)
1681
+ else:
1682
+ self.currentstream.write(data.tobytes())
1683
+ self.endStream()
1684
+
1685
+ def writeImages(self):
1686
+ for img, name, ob in self._images.values():
1687
+ data, adata = self._unpack(img)
1688
+ if adata is not None:
1689
+ smaskObject = self.reserveObject("smask")
1690
+ self._writeImg(adata, smaskObject.id)
1691
+ else:
1692
+ smaskObject = None
1693
+ self._writeImg(data, ob.id, smaskObject)
1694
+
1695
+ def markerObject(self, path, trans, fill, stroke, lw, joinstyle,
1696
+ capstyle):
1697
+ """Return name of a marker XObject representing the given path."""
1698
+ # self.markers used by markerObject, writeMarkers, close:
1699
+ # mapping from (path operations, fill?, stroke?) to
1700
+ # [name, object reference, bounding box, linewidth]
1701
+ # This enables different draw_markers calls to share the XObject
1702
+ # if the gc is sufficiently similar: colors etc can vary, but
1703
+ # the choices of whether to fill and whether to stroke cannot.
1704
+ # We need a bounding box enclosing all of the XObject path,
1705
+ # but since line width may vary, we store the maximum of all
1706
+ # occurring line widths in self.markers.
1707
+ # close() is somewhat tightly coupled in that it expects the
1708
+ # first two components of each value in self.markers to be the
1709
+ # name and object reference.
1710
+ pathops = self.pathOperations(path, trans, simplify=False)
1711
+ key = (tuple(pathops), bool(fill), bool(stroke), joinstyle, capstyle)
1712
+ result = self.markers.get(key)
1713
+ if result is None:
1714
+ name = Name('M%d' % len(self.markers))
1715
+ ob = self.reserveObject('marker %d' % len(self.markers))
1716
+ bbox = path.get_extents(trans)
1717
+ self.markers[key] = [name, ob, bbox, lw]
1718
+ else:
1719
+ if result[-1] < lw:
1720
+ result[-1] = lw
1721
+ name = result[0]
1722
+ return name
1723
+
1724
+ def writeMarkers(self):
1725
+ for ((pathops, fill, stroke, joinstyle, capstyle),
1726
+ (name, ob, bbox, lw)) in self.markers.items():
1727
+ # bbox wraps the exact limits of the control points, so half a line
1728
+ # will appear outside it. If the join style is miter and the line
1729
+ # is not parallel to the edge, then the line will extend even
1730
+ # further. From the PDF specification, Section 8.4.3.5, the miter
1731
+ # limit is miterLength / lineWidth and from Table 52, the default
1732
+ # is 10. With half the miter length outside, that works out to the
1733
+ # following padding:
1734
+ bbox = bbox.padded(lw * 5)
1735
+ self.beginStream(
1736
+ ob.id, None,
1737
+ {'Type': Name('XObject'), 'Subtype': Name('Form'),
1738
+ 'BBox': list(bbox.extents)})
1739
+ self.output(GraphicsContextPdf.joinstyles[joinstyle],
1740
+ Op.setlinejoin)
1741
+ self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap)
1742
+ self.output(*pathops)
1743
+ self.output(Op.paint_path(fill, stroke))
1744
+ self.endStream()
1745
+
1746
+ def pathCollectionObject(self, gc, path, trans, padding, filled, stroked):
1747
+ name = Name('P%d' % len(self.paths))
1748
+ ob = self.reserveObject('path %d' % len(self.paths))
1749
+ self.paths.append(
1750
+ (name, path, trans, ob, gc.get_joinstyle(), gc.get_capstyle(),
1751
+ padding, filled, stroked))
1752
+ return name
1753
+
1754
+ def writePathCollectionTemplates(self):
1755
+ for (name, path, trans, ob, joinstyle, capstyle, padding, filled,
1756
+ stroked) in self.paths:
1757
+ pathops = self.pathOperations(path, trans, simplify=False)
1758
+ bbox = path.get_extents(trans)
1759
+ if not np.all(np.isfinite(bbox.extents)):
1760
+ extents = [0, 0, 0, 0]
1761
+ else:
1762
+ bbox = bbox.padded(padding)
1763
+ extents = list(bbox.extents)
1764
+ self.beginStream(
1765
+ ob.id, None,
1766
+ {'Type': Name('XObject'), 'Subtype': Name('Form'),
1767
+ 'BBox': extents})
1768
+ self.output(GraphicsContextPdf.joinstyles[joinstyle],
1769
+ Op.setlinejoin)
1770
+ self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap)
1771
+ self.output(*pathops)
1772
+ self.output(Op.paint_path(filled, stroked))
1773
+ self.endStream()
1774
+
1775
+ @staticmethod
1776
+ def pathOperations(path, transform, clip=None, simplify=None, sketch=None):
1777
+ return [Verbatim(_path.convert_to_string(
1778
+ path, transform, clip, simplify, sketch,
1779
+ 6,
1780
+ [Op.moveto.value, Op.lineto.value, b'', Op.curveto.value,
1781
+ Op.closepath.value],
1782
+ True))]
1783
+
1784
+ def writePath(self, path, transform, clip=False, sketch=None):
1785
+ if clip:
1786
+ clip = (0.0, 0.0, self.width * 72, self.height * 72)
1787
+ simplify = path.should_simplify
1788
+ else:
1789
+ clip = None
1790
+ simplify = False
1791
+ cmds = self.pathOperations(path, transform, clip, simplify=simplify,
1792
+ sketch=sketch)
1793
+ self.output(*cmds)
1794
+
1795
+ def reserveObject(self, name=''):
1796
+ """
1797
+ Reserve an ID for an indirect object.
1798
+
1799
+ The name is used for debugging in case we forget to print out
1800
+ the object with writeObject.
1801
+ """
1802
+ id = next(self._object_seq)
1803
+ self.xrefTable.append([None, 0, name])
1804
+ return Reference(id)
1805
+
1806
+ def recordXref(self, id):
1807
+ self.xrefTable[id][0] = self.fh.tell() - self.tell_base
1808
+
1809
+ def writeObject(self, object, contents):
1810
+ self.recordXref(object.id)
1811
+ object.write(contents, self)
1812
+
1813
+ def writeXref(self):
1814
+ """Write out the xref table."""
1815
+ self.startxref = self.fh.tell() - self.tell_base
1816
+ self.write(b"xref\n0 %d\n" % len(self.xrefTable))
1817
+ for i, (offset, generation, name) in enumerate(self.xrefTable):
1818
+ if offset is None:
1819
+ raise AssertionError(
1820
+ 'No offset for object %d (%s)' % (i, name))
1821
+ else:
1822
+ key = b"f" if name == 'the zero object' else b"n"
1823
+ text = b"%010d %05d %b \n" % (offset, generation, key)
1824
+ self.write(text)
1825
+
1826
+ def writeInfoDict(self):
1827
+ """Write out the info dictionary, checking it for good form"""
1828
+
1829
+ self.infoObject = self.reserveObject('info')
1830
+ self.writeObject(self.infoObject, self.infoDict)
1831
+
1832
+ def writeTrailer(self):
1833
+ """Write out the PDF trailer."""
1834
+
1835
+ self.write(b"trailer\n")
1836
+ self.write(pdfRepr(
1837
+ {'Size': len(self.xrefTable),
1838
+ 'Root': self.rootObject,
1839
+ 'Info': self.infoObject}))
1840
+ # Could add 'ID'
1841
+ self.write(b"\nstartxref\n%d\n%%%%EOF\n" % self.startxref)
1842
+
1843
+
1844
+ class RendererPdf(_backend_pdf_ps.RendererPDFPSBase):
1845
+
1846
+ _afm_font_dir = cbook._get_data_path("fonts/pdfcorefonts")
1847
+ _use_afm_rc_name = "pdf.use14corefonts"
1848
+
1849
+ def __init__(self, file, image_dpi, height, width):
1850
+ super().__init__(width, height)
1851
+ self.file = file
1852
+ self.gc = self.new_gc()
1853
+ self.image_dpi = image_dpi
1854
+
1855
+ def finalize(self):
1856
+ self.file.output(*self.gc.finalize())
1857
+
1858
+ def check_gc(self, gc, fillcolor=None):
1859
+ orig_fill = getattr(gc, '_fillcolor', (0., 0., 0.))
1860
+ gc._fillcolor = fillcolor
1861
+
1862
+ orig_alphas = getattr(gc, '_effective_alphas', (1.0, 1.0))
1863
+
1864
+ if gc.get_rgb() is None:
1865
+ # It should not matter what color here since linewidth should be
1866
+ # 0 unless affected by global settings in rcParams, hence setting
1867
+ # zero alpha just in case.
1868
+ gc.set_foreground((0, 0, 0, 0), isRGBA=True)
1869
+
1870
+ if gc._forced_alpha:
1871
+ gc._effective_alphas = (gc._alpha, gc._alpha)
1872
+ elif fillcolor is None or len(fillcolor) < 4:
1873
+ gc._effective_alphas = (gc._rgb[3], 1.0)
1874
+ else:
1875
+ gc._effective_alphas = (gc._rgb[3], fillcolor[3])
1876
+
1877
+ delta = self.gc.delta(gc)
1878
+ if delta:
1879
+ self.file.output(*delta)
1880
+
1881
+ # Restore gc to avoid unwanted side effects
1882
+ gc._fillcolor = orig_fill
1883
+ gc._effective_alphas = orig_alphas
1884
+
1885
+ def get_image_magnification(self):
1886
+ return self.image_dpi/72.0
1887
+
1888
+ def draw_image(self, gc, x, y, im, transform=None):
1889
+ # docstring inherited
1890
+
1891
+ h, w = im.shape[:2]
1892
+ if w == 0 or h == 0:
1893
+ return
1894
+
1895
+ if transform is None:
1896
+ # If there's no transform, alpha has already been applied
1897
+ gc.set_alpha(1.0)
1898
+
1899
+ self.check_gc(gc)
1900
+
1901
+ w = 72.0 * w / self.image_dpi
1902
+ h = 72.0 * h / self.image_dpi
1903
+
1904
+ imob = self.file.imageObject(im)
1905
+
1906
+ if transform is None:
1907
+ self.file.output(Op.gsave,
1908
+ w, 0, 0, h, x, y, Op.concat_matrix,
1909
+ imob, Op.use_xobject, Op.grestore)
1910
+ else:
1911
+ tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values()
1912
+
1913
+ self.file.output(Op.gsave,
1914
+ 1, 0, 0, 1, x, y, Op.concat_matrix,
1915
+ tr1, tr2, tr3, tr4, tr5, tr6, Op.concat_matrix,
1916
+ imob, Op.use_xobject, Op.grestore)
1917
+
1918
+ def draw_path(self, gc, path, transform, rgbFace=None):
1919
+ # docstring inherited
1920
+ self.check_gc(gc, rgbFace)
1921
+ self.file.writePath(
1922
+ path, transform,
1923
+ rgbFace is None and gc.get_hatch_path() is None,
1924
+ gc.get_sketch_params())
1925
+ self.file.output(self.gc.paint())
1926
+
1927
+ def draw_path_collection(self, gc, master_transform, paths, all_transforms,
1928
+ offsets, offset_trans, facecolors, edgecolors,
1929
+ linewidths, linestyles, antialiaseds, urls,
1930
+ offset_position, *, hatchcolors=None):
1931
+ # We can only reuse the objects if the presence of fill and
1932
+ # stroke (and the amount of alpha for each) is the same for
1933
+ # all of them
1934
+ can_do_optimization = True
1935
+ facecolors = np.asarray(facecolors)
1936
+ edgecolors = np.asarray(edgecolors)
1937
+
1938
+ if hatchcolors is None:
1939
+ hatchcolors = []
1940
+
1941
+ if not len(facecolors):
1942
+ filled = False
1943
+ can_do_optimization = not gc.get_hatch()
1944
+ else:
1945
+ if np.all(facecolors[:, 3] == facecolors[0, 3]):
1946
+ filled = facecolors[0, 3] != 0.0
1947
+ else:
1948
+ can_do_optimization = False
1949
+
1950
+ if not len(edgecolors):
1951
+ stroked = False
1952
+ else:
1953
+ if np.all(np.asarray(linewidths) == 0.0):
1954
+ stroked = False
1955
+ elif np.all(edgecolors[:, 3] == edgecolors[0, 3]):
1956
+ stroked = edgecolors[0, 3] != 0.0
1957
+ else:
1958
+ can_do_optimization = False
1959
+
1960
+ # Is the optimization worth it? Rough calculation:
1961
+ # cost of emitting a path in-line is len_path * uses_per_path
1962
+ # cost of XObject is len_path + 5 for the definition,
1963
+ # uses_per_path for the uses
1964
+ len_path = len(paths[0].vertices) if len(paths) > 0 else 0
1965
+ uses_per_path = self._iter_collection_uses_per_path(
1966
+ paths, all_transforms, offsets, facecolors, edgecolors)
1967
+ should_do_optimization = \
1968
+ len_path + uses_per_path + 5 < len_path * uses_per_path
1969
+
1970
+ if (not can_do_optimization) or (not should_do_optimization):
1971
+ return RendererBase.draw_path_collection(
1972
+ self, gc, master_transform, paths, all_transforms,
1973
+ offsets, offset_trans, facecolors, edgecolors,
1974
+ linewidths, linestyles, antialiaseds, urls,
1975
+ offset_position, hatchcolors=hatchcolors)
1976
+
1977
+ padding = np.max(linewidths)
1978
+ path_codes = []
1979
+ path_extents = []
1980
+ for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
1981
+ master_transform, paths, all_transforms)):
1982
+ name = self.file.pathCollectionObject(
1983
+ gc, path, transform, padding, filled, stroked)
1984
+ path_codes.append(name)
1985
+ # Compute each transformed path's exact bounds for per-marker
1986
+ # canvas checks. Offsets are not necessarily full canvas-space
1987
+ # centers, e.g. for collections using AffineDeltaTransform, so
1988
+ # cull based on the final path bounds translated by the offset.
1989
+ path_extents.append(path.get_extents(transform).frozen())
1990
+
1991
+ # Create a mapping from path_id to extent for efficient lookup
1992
+ path_extent_map = dict(zip(path_codes, path_extents))
1993
+
1994
+ canvas_width = self.file.width * 72
1995
+ canvas_height = self.file.height * 72
1996
+
1997
+ output = self.file.output
1998
+ output(*self.gc.push())
1999
+ lastx, lasty = 0, 0
2000
+ for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
2001
+ gc, path_codes, offsets, offset_trans,
2002
+ facecolors, edgecolors, linewidths, linestyles,
2003
+ antialiaseds, urls, offset_position, hatchcolors=hatchcolors):
2004
+
2005
+ # Skip markers completely outside the canvas to reduce PDF size.
2006
+ # Use the translated path bounds, not the offset alone: the offset
2007
+ # need not be the marker center in canvas coordinates.
2008
+ bbox = path_extent_map[path_id]
2009
+ if (bbox.x1 + xo < 0 or bbox.x0 + xo > canvas_width
2010
+ or bbox.y1 + yo < 0 or bbox.y0 + yo > canvas_height):
2011
+ continue
2012
+
2013
+ self.check_gc(gc0, rgbFace)
2014
+ dx, dy = xo - lastx, yo - lasty
2015
+ output(1, 0, 0, 1, dx, dy, Op.concat_matrix, path_id,
2016
+ Op.use_xobject)
2017
+ lastx, lasty = xo, yo
2018
+ output(*self.gc.pop())
2019
+
2020
+ def draw_markers(self, gc, marker_path, marker_trans, path, trans,
2021
+ rgbFace=None):
2022
+ # docstring inherited
2023
+
2024
+ # Same logic as in draw_path_collection
2025
+ len_marker_path = len(marker_path)
2026
+ uses = len(path)
2027
+ if len_marker_path * uses < len_marker_path + uses + 5:
2028
+ RendererBase.draw_markers(self, gc, marker_path, marker_trans,
2029
+ path, trans, rgbFace)
2030
+ return
2031
+
2032
+ self.check_gc(gc, rgbFace)
2033
+ fill = gc.fill(rgbFace)
2034
+ stroke = gc.stroke()
2035
+
2036
+ output = self.file.output
2037
+ marker = self.file.markerObject(
2038
+ marker_path, marker_trans, fill, stroke, self.gc._linewidth,
2039
+ gc.get_joinstyle(), gc.get_capstyle())
2040
+
2041
+ output(Op.gsave)
2042
+ lastx, lasty = 0, 0
2043
+ for vertices, code in path.iter_segments(
2044
+ trans,
2045
+ clip=(0, 0, self.file.width*72, self.file.height*72),
2046
+ simplify=False):
2047
+ if len(vertices):
2048
+ x, y = vertices[-2:]
2049
+ if not (0 <= x <= self.file.width * 72
2050
+ and 0 <= y <= self.file.height * 72):
2051
+ continue
2052
+ dx, dy = x - lastx, y - lasty
2053
+ output(1, 0, 0, 1, dx, dy, Op.concat_matrix,
2054
+ marker, Op.use_xobject)
2055
+ lastx, lasty = x, y
2056
+ output(Op.grestore)
2057
+
2058
+ def draw_gouraud_triangles(self, gc, points, colors, trans):
2059
+ assert len(points) == len(colors)
2060
+ if len(points) == 0:
2061
+ return
2062
+ assert points.ndim == 3
2063
+ assert points.shape[1] == 3
2064
+ assert points.shape[2] == 2
2065
+ assert colors.ndim == 3
2066
+ assert colors.shape[1] == 3
2067
+ assert colors.shape[2] in (1, 4)
2068
+
2069
+ shape = points.shape
2070
+ points = points.reshape((shape[0] * shape[1], 2))
2071
+ tpoints = trans.transform(points)
2072
+ tpoints = tpoints.reshape(shape)
2073
+ name, _ = self.file.addGouraudTriangles(tpoints, colors)
2074
+ output = self.file.output
2075
+
2076
+ if colors.shape[2] == 1:
2077
+ # grayscale
2078
+ gc.set_alpha(1.0)
2079
+ self.check_gc(gc)
2080
+ output(name, Op.shading)
2081
+ return
2082
+
2083
+ alpha = colors[0, 0, 3]
2084
+ if np.allclose(alpha, colors[:, :, 3]):
2085
+ # single alpha value
2086
+ gc.set_alpha(alpha)
2087
+ self.check_gc(gc)
2088
+ output(name, Op.shading)
2089
+ else:
2090
+ # varying alpha: use a soft mask
2091
+ alpha = colors[:, :, 3][:, :, None]
2092
+ _, smask_ob = self.file.addGouraudTriangles(tpoints, alpha)
2093
+ gstate = self.file._soft_mask_state(smask_ob)
2094
+ output(Op.gsave, gstate, Op.setgstate,
2095
+ name, Op.shading,
2096
+ Op.grestore)
2097
+
2098
+ def _setup_textpos(self, x, y, angle, oldx=0, oldy=0, oldangle=0):
2099
+ if angle == oldangle == 0:
2100
+ self.file.output(x - oldx, y - oldy, Op.textpos)
2101
+ else:
2102
+ angle = math.radians(angle)
2103
+ self.file.output(math.cos(angle), math.sin(angle),
2104
+ -math.sin(angle), math.cos(angle),
2105
+ x, y, Op.textmatrix)
2106
+ self.file.output(0, 0, Op.textpos)
2107
+
2108
+ def draw_mathtext(self, gc, x, y, s, prop, angle):
2109
+ # TODO: fix positioning and encoding
2110
+ width, height, descent, glyphs, rects = \
2111
+ self._text2path.mathtext_parser.parse(s, 72, prop)
2112
+
2113
+ if gc.get_url() is not None:
2114
+ self.file._annotations[-1][1].append(_get_link_annotation(
2115
+ gc, x, y, width, height, angle))
2116
+
2117
+ fonttype = mpl.rcParams['pdf.fonttype']
2118
+
2119
+ # Set up a global transformation matrix for the whole math expression
2120
+ a = math.radians(angle)
2121
+ self.file.output(Op.gsave)
2122
+ self.file.output(math.cos(a), math.sin(a),
2123
+ -math.sin(a), math.cos(a),
2124
+ x, y, Op.concat_matrix)
2125
+
2126
+ self.check_gc(gc, gc._rgb)
2127
+ prev_font = None, None
2128
+ oldx, oldy = 0, 0
2129
+
2130
+ self.file.output(Op.begin_text)
2131
+ for font, fontsize, ccode, glyph_index, ox, oy in glyphs:
2132
+ subset_index, subset_charcode = self.file._character_tracker.track_glyph(
2133
+ font, ccode, glyph_index)
2134
+ font_path = FontPath(font.fname, font.face_index)
2135
+ self._setup_textpos(ox, oy, 0, oldx, oldy)
2136
+ oldx, oldy = ox, oy
2137
+ if (font_path, subset_index, fontsize) != prev_font:
2138
+ self.file.output(self.file.fontName(font_path, subset_index), fontsize,
2139
+ Op.selectfont)
2140
+ prev_font = font_path, subset_index, fontsize
2141
+ self.file.output(self._encode_glyphs([subset_charcode], fonttype),
2142
+ Op.show)
2143
+ self.file.output(Op.end_text)
2144
+
2145
+ # Draw any horizontal lines in the math layout
2146
+ for ox, oy, width, height in rects:
2147
+ self.file.output(Op.gsave, ox, oy, width, height,
2148
+ Op.rectangle, Op.fill, Op.grestore)
2149
+
2150
+ # Pop off the global transformation
2151
+ self.file.output(Op.grestore)
2152
+
2153
+ def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
2154
+ # docstring inherited
2155
+ texmanager = self.get_texmanager()
2156
+ fontsize = prop.get_size_in_points()
2157
+ dvifile = texmanager.make_dvi(s, fontsize)
2158
+ with dviread.Dvi(dvifile, 72) as dvi:
2159
+ page, = dvi
2160
+
2161
+ if gc.get_url() is not None:
2162
+ self.file._annotations[-1][1].append(_get_link_annotation(
2163
+ gc, x, y, page.width, page.height, angle))
2164
+
2165
+ # Gather font information and do some setup for combining
2166
+ # characters into strings. The variable seq will contain a
2167
+ # sequence of font and text entries. A font entry is a list
2168
+ # ['font', name, size] where name is a Name object for the
2169
+ # font. A text entry is ['text', x, y, glyphs, x+w] where x
2170
+ # and y are the starting coordinates, w is the width, and
2171
+ # glyphs is a list; in this phase it will always contain just
2172
+ # one single-character string, but later it may have longer
2173
+ # strings interspersed with kern amounts.
2174
+ oldfont, seq = None, []
2175
+ for text in page.text:
2176
+ if text.font != oldfont:
2177
+ pdfname = self.file.dviFontName(text.font)
2178
+ seq += [['font', pdfname, text.font.size]]
2179
+ oldfont = text.font
2180
+ seq += [['text', text.x, text.y, [bytes([text.glyph])], text.x+text.width]]
2181
+ self.file._character_tracker.track_glyph(text.font, text.glyph, text.index)
2182
+
2183
+ # Find consecutive text strings with constant y coordinate and
2184
+ # combine into a sequence of strings and kerns, or just one
2185
+ # string (if any kerns would be less than 0.1 points).
2186
+ i, curx, fontsize = 0, 0, None
2187
+ while i < len(seq)-1:
2188
+ elt, nxt = seq[i:i+2]
2189
+ if elt[0] == 'font':
2190
+ fontsize = elt[2]
2191
+ elif elt[0] == nxt[0] == 'text' and elt[2] == nxt[2]:
2192
+ offset = elt[4] - nxt[1]
2193
+ if abs(offset) < 0.1:
2194
+ elt[3][-1] += nxt[3][0]
2195
+ elt[4] += nxt[4]-nxt[1]
2196
+ else:
2197
+ elt[3] += [offset*1000.0/fontsize, nxt[3][0]]
2198
+ elt[4] = nxt[4]
2199
+ del seq[i+1]
2200
+ continue
2201
+ i += 1
2202
+
2203
+ # Create a transform to map the dvi contents to the canvas.
2204
+ mytrans = Affine2D().rotate_deg(angle).translate(x, y)
2205
+
2206
+ # Output the text.
2207
+ self.check_gc(gc, gc._rgb)
2208
+ self.file.output(Op.begin_text)
2209
+ curx, cury, oldx, oldy = 0, 0, 0, 0
2210
+ for elt in seq:
2211
+ if elt[0] == 'font':
2212
+ self.file.output(elt[1], elt[2], Op.selectfont)
2213
+ elif elt[0] == 'text':
2214
+ curx, cury = mytrans.transform((elt[1], elt[2]))
2215
+ self._setup_textpos(curx, cury, angle, oldx, oldy)
2216
+ oldx, oldy = curx, cury
2217
+ if len(elt[3]) == 1:
2218
+ self.file.output(elt[3][0], Op.show)
2219
+ else:
2220
+ self.file.output(elt[3], Op.showkern)
2221
+ else:
2222
+ assert False
2223
+ self.file.output(Op.end_text)
2224
+
2225
+ # Then output the boxes (e.g., variable-length lines of square
2226
+ # roots).
2227
+ boxgc = self.new_gc()
2228
+ boxgc.copy_properties(gc)
2229
+ boxgc.set_linewidth(0)
2230
+ pathops = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,
2231
+ Path.CLOSEPOLY]
2232
+ for x1, y1, h, w in page.boxes:
2233
+ path = Path([[x1, y1], [x1+w, y1], [x1+w, y1+h], [x1, y1+h],
2234
+ [0, 0]], pathops)
2235
+ self.draw_path(boxgc, path, mytrans, gc._rgb)
2236
+
2237
+ def _encode_glyphs(self, subset, fonttype):
2238
+ if fonttype in (1, 3):
2239
+ return bytes(subset)
2240
+ return b''.join(glyph.to_bytes(2, 'big') for glyph in subset)
2241
+
2242
+ def encode_string(self, s, fonttype):
2243
+ encoding = {1: 'cp1252', 3: 'latin-1', 42: 'utf-16be'}[fonttype]
2244
+ return s.encode(encoding, 'replace')
2245
+
2246
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
2247
+ # docstring inherited
2248
+
2249
+ # TODO: combine consecutive texts into one BT/ET delimited section
2250
+
2251
+ self.check_gc(gc, gc._rgb)
2252
+ if ismath:
2253
+ return self.draw_mathtext(gc, x, y, s, prop, angle)
2254
+
2255
+ fontsize = prop.get_size_in_points()
2256
+ if mtext is not None:
2257
+ features = mtext.get_fontfeatures()
2258
+ language = mtext.get_language()
2259
+ else:
2260
+ features = language = None
2261
+
2262
+ # For Type-1 fonts, emit the whole string at once without manual kerning.
2263
+ if mpl.rcParams['pdf.use14corefonts']:
2264
+ font = self._get_font_afm(prop)
2265
+ self.file.output(Op.begin_text,
2266
+ self.file.fontName(prop), fontsize, Op.selectfont)
2267
+ self._setup_textpos(x, y, angle)
2268
+ self.file.output(self.encode_string(s, fonttype=1),
2269
+ Op.show, Op.end_text)
2270
+
2271
+ # A sequence of characters is broken into multiple chunks. The chunking
2272
+ # serves two purposes:
2273
+ # - For Type 3 fonts, there is no way to access multibyte characters, as they
2274
+ # cannot have a CIDMap. Therefore, in this case we break the string into
2275
+ # chunks, where each chunk contains a string of consecutive 1-byte
2276
+ # characters in a 256-character subset of the font. A distinct version of
2277
+ # the original font is created for each 256-character subset.
2278
+ # - A sequence of characters is split into chunks to allow for kerning
2279
+ # adjustments between consecutive chunks.
2280
+ #
2281
+ # Each chunk is emitted with the regular text show command (TJ) with appropriate
2282
+ # kerning between chunks.
2283
+ else:
2284
+ font = self._get_font_ttf(prop)
2285
+ fonttype = mpl.rcParams['pdf.fonttype']
2286
+
2287
+ def output_singlebyte_chunk(kerns_or_chars):
2288
+ if not kerns_or_chars:
2289
+ return
2290
+ self.file.output(
2291
+ # See pdf spec "Text space details" for the 1000/fontsize
2292
+ # (aka. 1000/T_fs) factor.
2293
+ [(-1000 * next(group) / fontsize) if tp == float # a kern
2294
+ else self._encode_glyphs(group, fonttype)
2295
+ for tp, group in itertools.groupby(kerns_or_chars, type)],
2296
+ Op.showkern)
2297
+ kerns_or_chars.clear()
2298
+ # Do the rotation and global translation as a single matrix
2299
+ # concatenation up front
2300
+ self.file.output(Op.gsave)
2301
+ a = math.radians(angle)
2302
+ self.file.output(math.cos(a), math.sin(a),
2303
+ -math.sin(a), math.cos(a),
2304
+ x, y, Op.concat_matrix)
2305
+ # List of [prev_kern, char, char, ...] w/o zero kerns.
2306
+ singlebyte_chunk = []
2307
+ prev_font = None
2308
+ prev_start_x = 0
2309
+ # Emit all the characters in a BT/ET group.
2310
+ self.file.output(Op.begin_text)
2311
+ for item in _text_helpers.layout(s, font, features=features,
2312
+ language=language):
2313
+ subset, charcode = self.file._character_tracker.track_glyph(
2314
+ item.ft_object, item.char, item.glyph_index)
2315
+ if (item.ft_object, subset) != prev_font:
2316
+ output_singlebyte_chunk(singlebyte_chunk)
2317
+ font_path = FontPath(item.ft_object.fname,
2318
+ item.ft_object.face_index)
2319
+ ft_name = self.file.fontName(font_path, subset)
2320
+ self.file.output(ft_name, fontsize, Op.selectfont)
2321
+ self._setup_textpos(item.x, 0, 0, prev_start_x, 0, 0)
2322
+ prev_font = (item.ft_object, subset)
2323
+ prev_start_x = item.x
2324
+ if item.y:
2325
+ output_singlebyte_chunk(singlebyte_chunk)
2326
+ self.file.output(item.y, Op.textrise)
2327
+ if item.prev_kern:
2328
+ singlebyte_chunk.append(item.prev_kern)
2329
+ singlebyte_chunk.append(charcode)
2330
+ if item.y:
2331
+ output_singlebyte_chunk(singlebyte_chunk)
2332
+ self.file.output(0, Op.textrise)
2333
+ output_singlebyte_chunk(singlebyte_chunk)
2334
+ self.file.output(Op.end_text)
2335
+ self.file.output(Op.grestore)
2336
+
2337
+ if gc.get_url() is not None:
2338
+ font.set_text(s, features=features, language=language)
2339
+ width, height = font.get_width_height()
2340
+ self.file._annotations[-1][1].append(_get_link_annotation(
2341
+ gc, x, y, width / 64, height / 64, angle))
2342
+
2343
+ def new_gc(self):
2344
+ # docstring inherited
2345
+ return GraphicsContextPdf(self.file)
2346
+
2347
+
2348
+ class GraphicsContextPdf(GraphicsContextBase):
2349
+
2350
+ def __init__(self, file):
2351
+ super().__init__()
2352
+ self._fillcolor = (0.0, 0.0, 0.0)
2353
+ self._effective_alphas = (1.0, 1.0)
2354
+ self.file = file
2355
+ self.parent = None
2356
+
2357
+ def __repr__(self):
2358
+ d = dict(self.__dict__)
2359
+ del d['file']
2360
+ del d['parent']
2361
+ return repr(d)
2362
+
2363
+ def stroke(self):
2364
+ """
2365
+ Predicate: does the path need to be stroked (its outline drawn)?
2366
+ This tests for the various conditions that disable stroking
2367
+ the path, in which case it would presumably be filled.
2368
+ """
2369
+ # _linewidth > 0: in pdf a line of width 0 is drawn at minimum
2370
+ # possible device width, but e.g., agg doesn't draw at all
2371
+ return (self._linewidth > 0 and self._alpha > 0 and
2372
+ (len(self._rgb) <= 3 or self._rgb[3] != 0.0))
2373
+
2374
+ def fill(self, *args):
2375
+ """
2376
+ Predicate: does the path need to be filled?
2377
+
2378
+ An optional argument can be used to specify an alternative
2379
+ _fillcolor, as needed by RendererPdf.draw_markers.
2380
+ """
2381
+ if len(args):
2382
+ _fillcolor = args[0]
2383
+ else:
2384
+ _fillcolor = self._fillcolor
2385
+ return (self._hatch or
2386
+ (_fillcolor is not None and
2387
+ (len(_fillcolor) <= 3 or _fillcolor[3] != 0.0)))
2388
+
2389
+ def paint(self):
2390
+ """
2391
+ Return the appropriate pdf operator to cause the path to be
2392
+ stroked, filled, or both.
2393
+ """
2394
+ return Op.paint_path(self.fill(), self.stroke())
2395
+
2396
+ capstyles = {'butt': 0, 'round': 1, 'projecting': 2}
2397
+ joinstyles = {'miter': 0, 'round': 1, 'bevel': 2}
2398
+
2399
+ def capstyle_cmd(self, style):
2400
+ return [self.capstyles[style], Op.setlinecap]
2401
+
2402
+ def joinstyle_cmd(self, style):
2403
+ return [self.joinstyles[style], Op.setlinejoin]
2404
+
2405
+ def linewidth_cmd(self, width):
2406
+ return [width, Op.setlinewidth]
2407
+
2408
+ def dash_cmd(self, dashes):
2409
+ offset, dash = dashes
2410
+ if dash is None:
2411
+ dash = []
2412
+ offset = 0
2413
+ return [list(dash), offset, Op.setdash]
2414
+
2415
+ def alpha_cmd(self, alpha, forced, effective_alphas):
2416
+ name = self.file.alphaState(effective_alphas)
2417
+ return [name, Op.setgstate]
2418
+
2419
+ def hatch_cmd(self, hatch, hatch_color, hatch_linewidth):
2420
+ if not hatch:
2421
+ if self._fillcolor is not None:
2422
+ return self.fillcolor_cmd(self._fillcolor)
2423
+ else:
2424
+ return [Name('DeviceRGB'), Op.setcolorspace_nonstroke]
2425
+ else:
2426
+ hatch_style = (hatch_color, self._fillcolor, hatch, hatch_linewidth)
2427
+ name = self.file.hatchPattern(hatch_style)
2428
+ return [Name('Pattern'), Op.setcolorspace_nonstroke,
2429
+ name, Op.setcolor_nonstroke]
2430
+
2431
+ def rgb_cmd(self, rgb):
2432
+ if mpl.rcParams['pdf.inheritcolor']:
2433
+ return []
2434
+ if rgb[0] == rgb[1] == rgb[2]:
2435
+ return [rgb[0], Op.setgray_stroke]
2436
+ else:
2437
+ return [*rgb[:3], Op.setrgb_stroke]
2438
+
2439
+ def fillcolor_cmd(self, rgb):
2440
+ if rgb is None or mpl.rcParams['pdf.inheritcolor']:
2441
+ return []
2442
+ elif rgb[0] == rgb[1] == rgb[2]:
2443
+ return [rgb[0], Op.setgray_nonstroke]
2444
+ else:
2445
+ return [*rgb[:3], Op.setrgb_nonstroke]
2446
+
2447
+ def push(self):
2448
+ parent = GraphicsContextPdf(self.file)
2449
+ parent.copy_properties(self)
2450
+ parent.parent = self.parent
2451
+ self.parent = parent
2452
+ return [Op.gsave]
2453
+
2454
+ def pop(self):
2455
+ assert self.parent is not None
2456
+ self.copy_properties(self.parent)
2457
+ self.parent = self.parent.parent
2458
+ return [Op.grestore]
2459
+
2460
+ def clip_cmd(self, cliprect, clippath):
2461
+ """Set clip rectangle. Calls `.pop()` and `.push()`."""
2462
+ cmds = []
2463
+ # Pop graphics state until we hit the right one or the stack is empty
2464
+ while ((self._cliprect, self._clippath) != (cliprect, clippath)
2465
+ and self.parent is not None):
2466
+ cmds.extend(self.pop())
2467
+ # Unless we hit the right one, set the clip polygon
2468
+ if ((self._cliprect, self._clippath) != (cliprect, clippath) or
2469
+ self.parent is None):
2470
+ cmds.extend(self.push())
2471
+ if self._cliprect != cliprect:
2472
+ cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath])
2473
+ if self._clippath != clippath:
2474
+ path, affine = clippath.get_transformed_path_and_affine()
2475
+ cmds.extend(
2476
+ PdfFile.pathOperations(path, affine, simplify=False) +
2477
+ [Op.clip, Op.endpath])
2478
+ return cmds
2479
+
2480
+ commands = (
2481
+ # must come first since may pop
2482
+ (('_cliprect', '_clippath'), clip_cmd),
2483
+ (('_alpha', '_forced_alpha', '_effective_alphas'), alpha_cmd),
2484
+ (('_capstyle',), capstyle_cmd),
2485
+ (('_fillcolor',), fillcolor_cmd),
2486
+ (('_joinstyle',), joinstyle_cmd),
2487
+ (('_linewidth',), linewidth_cmd),
2488
+ (('_dashes',), dash_cmd),
2489
+ (('_rgb',), rgb_cmd),
2490
+ # must come after fillcolor and rgb
2491
+ (('_hatch', '_hatch_color', '_hatch_linewidth'), hatch_cmd),
2492
+ )
2493
+
2494
+ def delta(self, other):
2495
+ """
2496
+ Copy properties of other into self and return PDF commands
2497
+ needed to transform *self* into *other*.
2498
+ """
2499
+ cmds = []
2500
+ fill_performed = False
2501
+ for params, cmd in self.commands:
2502
+ different = False
2503
+ for p in params:
2504
+ ours = getattr(self, p)
2505
+ theirs = getattr(other, p)
2506
+ try:
2507
+ if ours is None or theirs is None:
2508
+ different = ours is not theirs
2509
+ else:
2510
+ different = bool(ours != theirs)
2511
+ except ValueError:
2512
+ ours = np.asarray(ours)
2513
+ theirs = np.asarray(theirs)
2514
+ different = (ours.shape != theirs.shape or
2515
+ np.any(ours != theirs))
2516
+ if different:
2517
+ break
2518
+
2519
+ # Need to update hatching if we also updated fillcolor
2520
+ if cmd.__name__ == 'hatch_cmd' and fill_performed:
2521
+ different = True
2522
+
2523
+ if different:
2524
+ if cmd.__name__ == 'fillcolor_cmd':
2525
+ fill_performed = True
2526
+ theirs = [getattr(other, p) for p in params]
2527
+ cmds.extend(cmd(self, *theirs))
2528
+ for p in params:
2529
+ setattr(self, p, getattr(other, p))
2530
+ return cmds
2531
+
2532
+ def copy_properties(self, other):
2533
+ """
2534
+ Copy properties of other into self.
2535
+ """
2536
+ super().copy_properties(other)
2537
+ fillcolor = getattr(other, '_fillcolor', self._fillcolor)
2538
+ effective_alphas = getattr(other, '_effective_alphas',
2539
+ self._effective_alphas)
2540
+ self._fillcolor = fillcolor
2541
+ self._effective_alphas = effective_alphas
2542
+
2543
+ def finalize(self):
2544
+ """
2545
+ Make sure every pushed graphics state is popped.
2546
+ """
2547
+ cmds = []
2548
+ while self.parent is not None:
2549
+ cmds.extend(self.pop())
2550
+ return cmds
2551
+
2552
+
2553
+ class PdfPages:
2554
+ """
2555
+ A multi-page PDF file.
2556
+
2557
+ Examples
2558
+ --------
2559
+ >>> import matplotlib.pyplot as plt
2560
+ >>> # Initialize:
2561
+ >>> with PdfPages('foo.pdf') as pdf:
2562
+ ... # As many times as you like, create a figure fig and save it:
2563
+ ... fig = plt.figure()
2564
+ ... pdf.savefig(fig)
2565
+ ... # When no figure is specified the current figure is saved
2566
+ ... pdf.savefig()
2567
+
2568
+ Notes
2569
+ -----
2570
+ In reality `PdfPages` is a thin wrapper around `PdfFile`, in order to avoid
2571
+ confusion when using `~.pyplot.savefig` and forgetting the format argument.
2572
+ """
2573
+
2574
+ @_api.delete_parameter("3.10", "keep_empty",
2575
+ addendum="This parameter does nothing.")
2576
+ def __init__(self, filename, keep_empty=None, metadata=None):
2577
+ """
2578
+ Create a new PdfPages object.
2579
+
2580
+ Parameters
2581
+ ----------
2582
+ filename : str or path-like or file-like
2583
+ Plots using `PdfPages.savefig` will be written to a file at this location.
2584
+ The file is opened when a figure is saved for the first time (overwriting
2585
+ any older file with the same name).
2586
+
2587
+ metadata : dict, optional
2588
+ Information dictionary object (see PDF reference section 10.2.1
2589
+ 'Document Information Dictionary'), e.g.:
2590
+ ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.
2591
+
2592
+ The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
2593
+ 'Creator', 'Producer', 'CreationDate', 'ModDate', and
2594
+ 'Trapped'. Values have been predefined for 'Creator', 'Producer'
2595
+ and 'CreationDate'. They can be removed by setting them to `None`.
2596
+ """
2597
+ self._filename = filename
2598
+ self._metadata = metadata
2599
+ self._file = None
2600
+
2601
+ def __enter__(self):
2602
+ return self
2603
+
2604
+ def __exit__(self, exc_type, exc_val, exc_tb):
2605
+ self.close()
2606
+
2607
+ def _ensure_file(self):
2608
+ if self._file is None:
2609
+ self._file = PdfFile(self._filename, metadata=self._metadata) # init.
2610
+ return self._file
2611
+
2612
+ def close(self):
2613
+ """
2614
+ Finalize this object, making the underlying file a complete
2615
+ PDF file.
2616
+ """
2617
+ if self._file is not None:
2618
+ self._file.finalize()
2619
+ self._file.close()
2620
+ self._file = None
2621
+
2622
+ def infodict(self):
2623
+ """
2624
+ Return a modifiable information dictionary object
2625
+ (see PDF reference section 10.2.1 'Document Information
2626
+ Dictionary').
2627
+ """
2628
+ return self._ensure_file().infoDict
2629
+
2630
+ def savefig(self, figure=None, **kwargs):
2631
+ """
2632
+ Save a `.Figure` to this file as a new page.
2633
+
2634
+ Any other keyword arguments are passed to `~.Figure.savefig`.
2635
+
2636
+ Parameters
2637
+ ----------
2638
+ figure : `.Figure` or int, default: the active figure
2639
+ The figure, or index of the figure, that is saved to the file.
2640
+ """
2641
+ if not isinstance(figure, Figure):
2642
+ if figure is None:
2643
+ manager = Gcf.get_active()
2644
+ else:
2645
+ manager = Gcf.get_fig_manager(figure)
2646
+ if manager is None:
2647
+ raise ValueError(f"No figure {figure}")
2648
+ figure = manager.canvas.figure
2649
+ # Force use of pdf backend, as PdfPages is tightly coupled with it.
2650
+ figure.savefig(self, format="pdf", backend="pdf", **kwargs)
2651
+
2652
+ def get_pagecount(self):
2653
+ """Return the current number of pages in the multipage pdf file."""
2654
+ return len(self._ensure_file().pageList)
2655
+
2656
+ def attach_note(self, text, positionRect=[-100, -100, 0, 0]):
2657
+ """
2658
+ Add a new text note to the page to be saved next. The optional
2659
+ positionRect specifies the position of the new note on the
2660
+ page. It is outside the page per default to make sure it is
2661
+ invisible on printouts.
2662
+ """
2663
+ self._ensure_file().newTextnote(text, positionRect)
2664
+
2665
+
2666
+ class FigureCanvasPdf(FigureCanvasBase):
2667
+ # docstring inherited
2668
+
2669
+ fixed_dpi = 72
2670
+ filetypes = {'pdf': 'Portable Document Format'}
2671
+
2672
+ def get_default_filetype(self):
2673
+ return 'pdf'
2674
+
2675
+ def print_pdf(self, filename, *,
2676
+ bbox_inches_restore=None, metadata=None):
2677
+
2678
+ dpi = self.figure.dpi
2679
+ self.figure.dpi = 72 # there are 72 pdf points to an inch
2680
+ width, height = self.figure.get_size_inches()
2681
+ if isinstance(filename, PdfPages):
2682
+ file = filename._ensure_file()
2683
+ else:
2684
+ file = PdfFile(filename, metadata=metadata)
2685
+ try:
2686
+ file.newPage(width, height)
2687
+ renderer = MixedModeRenderer(
2688
+ self.figure, width, height, dpi,
2689
+ RendererPdf(file, dpi, height, width),
2690
+ bbox_inches_restore=bbox_inches_restore)
2691
+ self.figure.draw(renderer)
2692
+ renderer.finalize()
2693
+ if not isinstance(filename, PdfPages):
2694
+ file.finalize()
2695
+ finally:
2696
+ if isinstance(filename, PdfPages): # finish off this page
2697
+ file.endStream()
2698
+ else: # we opened the file above; now finish it off
2699
+ file.close()
2700
+
2701
+ def draw(self):
2702
+ self.figure.draw_without_rendering()
2703
+ return super().draw()
2704
+
2705
+
2706
+ FigureManagerPdf = FigureManagerBase
2707
+
2708
+
2709
+ @_Backend.export
2710
+ class _BackendPdf(_Backend):
2711
+ FigureCanvas = FigureCanvasPdf