preview.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import os
  2. from os.path import join
  3. import shutil
  4. import tempfile
  5. try:
  6. from subprocess import STDOUT, CalledProcessError, check_output
  7. except ImportError:
  8. pass
  9. from sympy.utilities.decorator import doctest_depends_on
  10. from sympy.utilities.misc import debug
  11. from .latex import latex
  12. __doctest_requires__ = {('preview',): ['pyglet']}
  13. def _check_output_no_window(*args, **kwargs):
  14. # Avoid showing a cmd.exe window when running this
  15. # on Windows
  16. if os.name == 'nt':
  17. creation_flag = 0x08000000 # CREATE_NO_WINDOW
  18. else:
  19. creation_flag = 0 # Default value
  20. return check_output(*args, creationflags=creation_flag, **kwargs)
  21. def system_default_viewer(fname, fmt):
  22. """ Open fname with the default system viewer.
  23. In practice, it is impossible for python to know when the system viewer is
  24. done. For this reason, we ensure the passed file will not be deleted under
  25. it, and this function does not attempt to block.
  26. """
  27. # copy to a new temporary file that will not be deleted
  28. with tempfile.NamedTemporaryFile(prefix='sympy-preview-',
  29. suffix=os.path.splitext(fname)[1],
  30. delete=False) as temp_f:
  31. with open(fname, 'rb') as f:
  32. shutil.copyfileobj(f, temp_f)
  33. import platform
  34. if platform.system() == 'Darwin':
  35. import subprocess
  36. subprocess.call(('open', temp_f.name))
  37. elif platform.system() == 'Windows':
  38. os.startfile(temp_f.name)
  39. else:
  40. import subprocess
  41. subprocess.call(('xdg-open', temp_f.name))
  42. def pyglet_viewer(fname, fmt):
  43. try:
  44. from pyglet import window, image, gl
  45. from pyglet.window import key
  46. from pyglet.image.codecs import ImageDecodeException
  47. except ImportError:
  48. raise ImportError("pyglet is required for preview.\n visit https://pyglet.org/")
  49. try:
  50. img = image.load(fname)
  51. except ImageDecodeException:
  52. raise ValueError("pyglet preview does not work for '{}' files.".format(fmt))
  53. offset = 25
  54. config = gl.Config(double_buffer=False)
  55. win = window.Window(
  56. width=img.width + 2*offset,
  57. height=img.height + 2*offset,
  58. caption="SymPy",
  59. resizable=False,
  60. config=config
  61. )
  62. win.set_vsync(False)
  63. try:
  64. def on_close():
  65. win.has_exit = True
  66. win.on_close = on_close
  67. def on_key_press(symbol, modifiers):
  68. if symbol in [key.Q, key.ESCAPE]:
  69. on_close()
  70. win.on_key_press = on_key_press
  71. def on_expose():
  72. gl.glClearColor(1.0, 1.0, 1.0, 1.0)
  73. gl.glClear(gl.GL_COLOR_BUFFER_BIT)
  74. img.blit(
  75. (win.width - img.width) / 2,
  76. (win.height - img.height) / 2
  77. )
  78. win.on_expose = on_expose
  79. while not win.has_exit:
  80. win.dispatch_events()
  81. win.flip()
  82. except KeyboardInterrupt:
  83. pass
  84. win.close()
  85. def _get_latex_main(expr, *, preamble=None, packages=(), extra_preamble=None,
  86. euler=True, fontsize=None, **latex_settings):
  87. """
  88. Generate string of a LaTeX document rendering ``expr``.
  89. """
  90. if preamble is None:
  91. actual_packages = packages + ("amsmath", "amsfonts")
  92. if euler:
  93. actual_packages += ("euler",)
  94. package_includes = "\n" + "\n".join(["\\usepackage{%s}" % p
  95. for p in actual_packages])
  96. if extra_preamble:
  97. package_includes += extra_preamble
  98. if not fontsize:
  99. fontsize = "12pt"
  100. elif isinstance(fontsize, int):
  101. fontsize = "{}pt".format(fontsize)
  102. preamble = r"""\documentclass[varwidth,%s]{standalone}
  103. %s
  104. \begin{document}
  105. """ % (fontsize, package_includes)
  106. else:
  107. if packages or extra_preamble:
  108. raise ValueError("The \"packages\" or \"extra_preamble\" keywords"
  109. "must not be set if a "
  110. "custom LaTeX preamble was specified")
  111. if isinstance(expr, str):
  112. latex_string = expr
  113. else:
  114. latex_string = ('$\\displaystyle ' +
  115. latex(expr, mode='plain', **latex_settings) +
  116. '$')
  117. return preamble + '\n' + latex_string + '\n\n' + r"\end{document}"
  118. @doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',),
  119. disable_viewers=('evince', 'gimp', 'superior-dvi-viewer'))
  120. def preview(expr, output='png', viewer=None, euler=True, packages=(),
  121. filename=None, outputbuffer=None, preamble=None, dvioptions=None,
  122. outputTexFile=None, extra_preamble=None, fontsize=None,
  123. **latex_settings):
  124. r"""
  125. View expression or LaTeX markup in PNG, DVI, PostScript or PDF form.
  126. If the expr argument is an expression, it will be exported to LaTeX and
  127. then compiled using the available TeX distribution. The first argument,
  128. 'expr', may also be a LaTeX string. The function will then run the
  129. appropriate viewer for the given output format or use the user defined
  130. one. By default png output is generated.
  131. By default pretty Euler fonts are used for typesetting (they were used to
  132. typeset the well known "Concrete Mathematics" book). For that to work, you
  133. need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the
  134. texlive-fonts-extra package). If you prefer default AMS fonts or your
  135. system lacks 'eulervm' LaTeX package then unset the 'euler' keyword
  136. argument.
  137. To use viewer auto-detection, lets say for 'png' output, issue
  138. >>> from sympy import symbols, preview, Symbol
  139. >>> x, y = symbols("x,y")
  140. >>> preview(x + y, output='png')
  141. This will choose 'pyglet' by default. To select a different one, do
  142. >>> preview(x + y, output='png', viewer='gimp')
  143. The 'png' format is considered special. For all other formats the rules
  144. are slightly different. As an example we will take 'dvi' output format. If
  145. you would run
  146. >>> preview(x + y, output='dvi')
  147. then 'view' will look for available 'dvi' viewers on your system
  148. (predefined in the function, so it will try evince, first, then kdvi and
  149. xdvi). If nothing is found, it will fall back to using a system file
  150. association (via ``open`` and ``xdg-open``). To always use your system file
  151. association without searching for the above readers, use
  152. >>> from sympy.printing.preview import system_default_viewer
  153. >>> preview(x + y, output='dvi', viewer=system_default_viewer)
  154. If this still does not find the viewer you want, it can be set explicitly.
  155. >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')
  156. This will skip auto-detection and will run user specified
  157. 'superior-dvi-viewer'. If ``view`` fails to find it on your system it will
  158. gracefully raise an exception.
  159. You may also enter ``'file'`` for the viewer argument. Doing so will cause
  160. this function to return a file object in read-only mode, if ``filename``
  161. is unset. However, if it was set, then 'preview' writes the generated
  162. file to this filename instead.
  163. There is also support for writing to a ``io.BytesIO`` like object, which
  164. needs to be passed to the ``outputbuffer`` argument.
  165. >>> from io import BytesIO
  166. >>> obj = BytesIO()
  167. >>> preview(x + y, output='png', viewer='BytesIO',
  168. ... outputbuffer=obj)
  169. The LaTeX preamble can be customized by setting the 'preamble' keyword
  170. argument. This can be used, e.g., to set a different font size, use a
  171. custom documentclass or import certain set of LaTeX packages.
  172. >>> preamble = "\\documentclass[10pt]{article}\n" \
  173. ... "\\usepackage{amsmath,amsfonts}\\begin{document}"
  174. >>> preview(x + y, output='png', preamble=preamble)
  175. It is also possible to use the standard preamble and provide additional
  176. information to the preamble using the ``extra_preamble`` keyword argument.
  177. >>> from sympy import sin
  178. >>> extra_preamble = "\\renewcommand{\\sin}{\\cos}"
  179. >>> preview(sin(x), output='png', extra_preamble=extra_preamble)
  180. If the value of 'output' is different from 'dvi' then command line
  181. options can be set ('dvioptions' argument) for the execution of the
  182. 'dvi'+output conversion tool. These options have to be in the form of a
  183. list of strings (see ``subprocess.Popen``).
  184. Additional keyword args will be passed to the :func:`~sympy.printing.latex.latex` call,
  185. e.g., the ``symbol_names`` flag.
  186. >>> phidd = Symbol('phidd')
  187. >>> preview(phidd, symbol_names={phidd: r'\ddot{\varphi}'})
  188. For post-processing the generated TeX File can be written to a file by
  189. passing the desired filename to the 'outputTexFile' keyword
  190. argument. To write the TeX code to a file named
  191. ``"sample.tex"`` and run the default png viewer to display the resulting
  192. bitmap, do
  193. >>> preview(x + y, outputTexFile="sample.tex")
  194. """
  195. # pyglet is the default for png
  196. if viewer is None and output == "png":
  197. try:
  198. import pyglet # noqa: F401
  199. except ImportError:
  200. pass
  201. else:
  202. viewer = pyglet_viewer
  203. # look up a known application
  204. if viewer is None:
  205. # sorted in order from most pretty to most ugly
  206. # very discussable, but indeed 'gv' looks awful :)
  207. candidates = {
  208. "dvi": [ "evince", "okular", "kdvi", "xdvi" ],
  209. "ps": [ "evince", "okular", "gsview", "gv" ],
  210. "pdf": [ "evince", "okular", "kpdf", "acroread", "xpdf", "gv" ],
  211. }
  212. for candidate in candidates.get(output, []):
  213. path = shutil.which(candidate)
  214. if path is not None:
  215. viewer = path
  216. break
  217. # otherwise, use the system default for file association
  218. if viewer is None:
  219. viewer = system_default_viewer
  220. if viewer == "file":
  221. if filename is None:
  222. raise ValueError("filename has to be specified if viewer=\"file\"")
  223. elif viewer == "BytesIO":
  224. if outputbuffer is None:
  225. raise ValueError("outputbuffer has to be a BytesIO "
  226. "compatible object if viewer=\"BytesIO\"")
  227. elif not callable(viewer) and not shutil.which(viewer):
  228. raise OSError("Unrecognized viewer: %s" % viewer)
  229. latex_main = _get_latex_main(expr, preamble=preamble, packages=packages,
  230. euler=euler, extra_preamble=extra_preamble,
  231. fontsize=fontsize, **latex_settings)
  232. debug("Latex code:")
  233. debug(latex_main)
  234. with tempfile.TemporaryDirectory() as workdir:
  235. with open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh:
  236. fh.write(latex_main)
  237. if outputTexFile is not None:
  238. shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile)
  239. if not shutil.which('latex'):
  240. raise RuntimeError("latex program is not installed")
  241. try:
  242. _check_output_no_window(
  243. ['latex', '-halt-on-error', '-interaction=nonstopmode',
  244. 'texput.tex'],
  245. cwd=workdir,
  246. stderr=STDOUT)
  247. except CalledProcessError as e:
  248. raise RuntimeError(
  249. "'latex' exited abnormally with the following output:\n%s" %
  250. e.output)
  251. src = "texput.%s" % (output)
  252. if output != "dvi":
  253. # in order of preference
  254. commandnames = {
  255. "ps": ["dvips"],
  256. "pdf": ["dvipdfmx", "dvipdfm", "dvipdf"],
  257. "png": ["dvipng"],
  258. "svg": ["dvisvgm"],
  259. }
  260. try:
  261. cmd_variants = commandnames[output]
  262. except KeyError:
  263. raise ValueError("Invalid output format: %s" % output) from None
  264. # find an appropriate command
  265. for cmd_variant in cmd_variants:
  266. cmd_path = shutil.which(cmd_variant)
  267. if cmd_path:
  268. cmd = [cmd_path]
  269. break
  270. else:
  271. if len(cmd_variants) > 1:
  272. raise RuntimeError("None of %s are installed" % ", ".join(cmd_variants))
  273. else:
  274. raise RuntimeError("%s is not installed" % cmd_variants[0])
  275. defaultoptions = {
  276. "dvipng": ["-T", "tight", "-z", "9", "--truecolor"],
  277. "dvisvgm": ["--no-fonts"],
  278. }
  279. commandend = {
  280. "dvips": ["-o", src, "texput.dvi"],
  281. "dvipdf": ["texput.dvi", src],
  282. "dvipdfm": ["-o", src, "texput.dvi"],
  283. "dvipdfmx": ["-o", src, "texput.dvi"],
  284. "dvipng": ["-o", src, "texput.dvi"],
  285. "dvisvgm": ["-o", src, "texput.dvi"],
  286. }
  287. if dvioptions is not None:
  288. cmd.extend(dvioptions)
  289. else:
  290. cmd.extend(defaultoptions.get(cmd_variant, []))
  291. cmd.extend(commandend[cmd_variant])
  292. try:
  293. _check_output_no_window(cmd, cwd=workdir, stderr=STDOUT)
  294. except CalledProcessError as e:
  295. raise RuntimeError(
  296. "'%s' exited abnormally with the following output:\n%s" %
  297. (' '.join(cmd), e.output))
  298. if viewer == "file":
  299. shutil.move(join(workdir, src), filename)
  300. elif viewer == "BytesIO":
  301. with open(join(workdir, src), 'rb') as fh:
  302. outputbuffer.write(fh.read())
  303. elif callable(viewer):
  304. viewer(join(workdir, src), fmt=output)
  305. else:
  306. try:
  307. _check_output_no_window(
  308. [viewer, src], cwd=workdir, stderr=STDOUT)
  309. except CalledProcessError as e:
  310. raise RuntimeError(
  311. "'%s %s' exited abnormally with the following output:\n%s" %
  312. (viewer, src, e.output))