mathshuttle 0.8.0__py3-none-any.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.
@@ -0,0 +1,325 @@
1
+ """Download the pinned pandoc release and install it for this user."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import http.client
6
+ import os
7
+ import platform
8
+ import re
9
+ import shutil
10
+ import ssl
11
+ import stat
12
+ import subprocess
13
+ import sys
14
+ import tarfile
15
+ import tempfile
16
+ import threading
17
+ import time
18
+ import urllib.error
19
+ import urllib.request
20
+ import zipfile
21
+ from contextlib import ExitStack
22
+ from pathlib import Path, PurePosixPath
23
+ from typing import BinaryIO, Callable, NamedTuple, Optional, Tuple
24
+
25
+ from .paths import local_data_dir
26
+
27
+ PANDOC_VERSION = "3.14"
28
+ _RELEASE_URL = "https://github.com/jgm/pandoc/releases/download/" + PANDOC_VERSION + "/"
29
+ _MAX_DOWNLOAD = 200_000_000
30
+ _MIN_FREE = 400_000_000
31
+ _CHUNK = 64 * 1024
32
+ _TIMEOUT = 20
33
+ _SLOW_AFTER = 60 # seconds: after that, a download below _MIN_RATE bytes per second on average stops
34
+ _MIN_RATE = 20_000
35
+ _FLAGS = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
36
+ _EXE = "pandoc.exe" if sys.platform == "win32" else "pandoc"
37
+ _Progress = Callable[[int, Optional[int]], None]
38
+
39
+
40
+ class FetchError(RuntimeError):
41
+ """The download or installation failed. The message is meant for the user."""
42
+
43
+
44
+ class FetchCancelled(FetchError):
45
+ """The user stopped the installation."""
46
+
47
+
48
+ class Asset(NamedTuple):
49
+ name: str
50
+ size: int
51
+ sha256: str
52
+
53
+
54
+ _ASSETS = {
55
+ ("win32", "x86_64"): Asset("pandoc-3.14-windows-x86_64.zip", 43614099,
56
+ "0144b96e8c7b023fd382ec5ef5bdc475e873f1019d6fa72502492df2c9a94a3b"),
57
+ ("darwin", "arm64"): Asset("pandoc-3.14-arm64-macOS.zip", 43712865,
58
+ "58d6593884fec9d4424b641b92503c316d9c36decb2891ff8d73ae74dd3b6304"),
59
+ ("darwin", "x86_64"): Asset("pandoc-3.14-x86_64-macOS.zip", 27490795,
60
+ "891708579061e7b1c1a6ce0df30ebb3cb2b6d0ca045ed3c8554ab830c1e0c270"),
61
+ ("linux", "x86_64"): Asset("pandoc-3.14-linux-amd64.tar.gz", 36635549,
62
+ "c5f4720cdefb3f7bdc5d07202ef579feef0d1370773c873804dd8fdaa8c4f1b8"),
63
+ ("linux", "arm64"): Asset("pandoc-3.14-linux-arm64.tar.gz", 39208196,
64
+ "c692f3d78a415741bbbac4cdbbbe26fa7edca1f43d2301b982fbf4009cc8cf7f"),
65
+ }
66
+
67
+
68
+ def _release_asset() -> Asset:
69
+ machine = platform.machine().lower()
70
+ arch = {"amd64": "x86_64", "aarch64": "arm64"}.get(machine, machine)
71
+ if sys.platform == "win32" and arch == "arm64":
72
+ arch = "x86_64"
73
+ asset = _ASSETS.get((sys.platform, arch))
74
+ if asset is None:
75
+ raise FetchError(f"No pandoc download is available for {sys.platform} ({machine}). "
76
+ "Install pandoc manually and set MATHSHUTTLE_PANDOC to its full path.")
77
+ return asset
78
+
79
+
80
+ def _folder() -> Path:
81
+ return Path(local_data_dir()) / "pandoc" / PANDOC_VERSION
82
+
83
+
84
+ def installed_pandoc() -> Optional[str]:
85
+ """Return the downloaded binary's path if it exists."""
86
+ path = _folder() / _EXE
87
+ return str(path) if path.is_file() else None
88
+
89
+
90
+ def _check_cancel(cancel):
91
+ if cancel is not None and cancel.is_set():
92
+ raise FetchCancelled("Pandoc installation cancelled.")
93
+
94
+
95
+ class _SecureRedirect(urllib.request.HTTPRedirectHandler):
96
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
97
+ if req.type == "https" and not newurl.lower().startswith("https://"):
98
+ fp.close()
99
+ raise FetchError("The download was redirected to an insecure address. Install pandoc manually.")
100
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
101
+
102
+
103
+ def _open_url(url):
104
+ https = urllib.request.HTTPSHandler(context=ssl.create_default_context())
105
+ return urllib.request.build_opener(https, _SecureRedirect()).open(url, timeout=_TIMEOUT)
106
+
107
+
108
+ def _system_curl() -> Optional[str]:
109
+ if sys.platform == "win32":
110
+ root = os.environ.get("SystemRoot")
111
+ path = os.path.join(root, "System32", "curl.exe") if root else ""
112
+ elif sys.platform == "darwin":
113
+ path = "/usr/bin/curl"
114
+ else:
115
+ return shutil.which("curl")
116
+ return path if os.path.isfile(path) else None
117
+
118
+
119
+ def _save_body(source: BinaryIO, path: Path, total: Optional[int], progress, cancel) -> Tuple[int, str]:
120
+ """Limit the actual bytes received, including when the server gives no size."""
121
+ too_large = "The download is too large (over 200 MB). Install pandoc manually."
122
+ if total is not None and total > _MAX_DOWNLOAD:
123
+ raise FetchError(too_large)
124
+ digest = hashlib.sha256()
125
+ done = 0
126
+ start = time.monotonic()
127
+ with path.open("wb") as output:
128
+ while True:
129
+ _check_cancel(cancel)
130
+ block = source.read1(_CHUNK)
131
+ if not block:
132
+ break
133
+ done += len(block)
134
+ if done > _MAX_DOWNLOAD:
135
+ raise FetchError(too_large)
136
+ # a connection that stops does so after _TIMEOUT; one that only trickles would go on for hours
137
+ elapsed = time.monotonic() - start
138
+ if elapsed > _SLOW_AFTER and done < _MIN_RATE * elapsed:
139
+ raise FetchError("The download is too slow (%d kB/s). Check your connection and try again, "
140
+ "or install pandoc manually." % (done / elapsed / 1000))
141
+ output.write(block)
142
+ digest.update(block)
143
+ if progress:
144
+ progress(done, total)
145
+ return done, digest.hexdigest()
146
+
147
+
148
+ def _download(url, path, progress, cancel, expected=None):
149
+ try:
150
+ response = _open_url(url)
151
+ except (urllib.error.URLError, ssl.SSLError) as exc:
152
+ reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc
153
+ if not (isinstance(reason, ssl.SSLCertVerificationError) or
154
+ getattr(reason, "reason", "") == "CERTIFICATE_VERIFY_FAILED"):
155
+ raise
156
+ _check_cancel(cancel)
157
+ curl = _system_curl()
158
+ if not curl:
159
+ raise FetchError("Python could not verify the download certificate. Update your certificates "
160
+ "or install pandoc manually.") from exc
161
+ else:
162
+ with response:
163
+ length = response.headers.get("Content-Length", "")
164
+ total = None
165
+ if re.fullmatch(r"[0-9]+", length):
166
+ digits = length.lstrip("0") or "0"
167
+ total = int(digits) if len(digits) <= len(str(_MAX_DOWNLOAD)) else _MAX_DOWNLOAD + 1
168
+ return _save_body(response, path, total, progress, cancel)
169
+
170
+ # Let the system curl use its usual certificate store. Keep the same byte limit and hash check.
171
+ args = [curl, "-q", "-fL", "--proto", "=https", "--proto-redir", "=https", "--connect-timeout",
172
+ str(_TIMEOUT), "--speed-limit", "1", "--speed-time", str(_TIMEOUT), "--", url]
173
+ with subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
174
+ creationflags=_FLAGS) as proc:
175
+ try:
176
+ result = _save_body(proc.stdout, path, expected, progress, cancel) # (curl gives no size: the release's)
177
+ if proc.wait(timeout=_TIMEOUT) != 0:
178
+ raise FetchError("The system downloader could not fetch pandoc. Check your connection "
179
+ "and certificates, or install pandoc manually.")
180
+ return result
181
+ finally:
182
+ if proc.poll() is None:
183
+ proc.kill()
184
+
185
+
186
+ def _temp_path(folder, cleanup, suffix="") -> Path:
187
+ fd, name = tempfile.mkstemp(dir=folder, suffix=suffix)
188
+ os.close(fd)
189
+ path = Path(name)
190
+ cleanup.callback(path.unlink, missing_ok=True)
191
+ return path
192
+
193
+
194
+ def _member_name(raw: str) -> Optional[str]:
195
+ parts = PurePosixPath(raw).parts
196
+ if not parts or raw.startswith("/") or "\\" in raw or ":" in raw or ".." in parts:
197
+ return None
198
+ name = parts[-1]
199
+ if name == _EXE and len(parts) <= 4:
200
+ return _EXE
201
+ if name.startswith(("COPYING", "COPYRIGHT")) and re.fullmatch(r'[^<>:"/\\|?*\x00-\x1f]+', name):
202
+ return name
203
+ return None
204
+
205
+
206
+ def _unpack(path, asset, folder, cleanup, cancel):
207
+ """Stage only the regular binary and licence files, each under a fresh local name."""
208
+ staged = {}
209
+
210
+ def stage(name, source):
211
+ with source:
212
+ if name in staged:
213
+ raise FetchError(f"The archive contains more than one {name}. Install pandoc manually.")
214
+ target = _temp_path(folder, cleanup, suffix=".exe" if name == "pandoc.exe" else "")
215
+ with target.open("wb") as output:
216
+ while True:
217
+ _check_cancel(cancel)
218
+ block = source.read(_CHUNK)
219
+ if not block:
220
+ break
221
+ output.write(block)
222
+ staged[name] = target
223
+
224
+ if asset.name.endswith(".zip"):
225
+ with zipfile.ZipFile(path) as archive:
226
+ for info in archive.infolist():
227
+ _check_cancel(cancel)
228
+ name = _member_name(info.filename)
229
+ kind = stat.S_IFMT(info.external_attr >> 16)
230
+ if name and not info.is_dir() and not info.external_attr & 0x10 and kind in (0, stat.S_IFREG):
231
+ stage(name, archive.open(info))
232
+ else:
233
+ with tarfile.open(path, "r|gz") as archive:
234
+ for info in archive:
235
+ _check_cancel(cancel)
236
+ name = _member_name(info.name)
237
+ if name and info.isreg():
238
+ stage(name, archive.extractfile(info))
239
+ if _EXE not in staged:
240
+ raise FetchError("The archive did not contain the pandoc program. Install pandoc manually.")
241
+ return staged
242
+
243
+
244
+ def _check_version(binary: Path) -> None:
245
+ if os.name != "nt":
246
+ binary.chmod(0o755)
247
+ try:
248
+ proc = subprocess.run([str(binary), "--version"], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
249
+ stderr=subprocess.DEVNULL, timeout=_TIMEOUT, creationflags=_FLAGS)
250
+ except (OSError, subprocess.TimeoutExpired) as exc:
251
+ raise FetchError("Could not start the downloaded pandoc. Install pandoc manually.") from exc
252
+ version = rb"^pandoc " + re.escape(PANDOC_VERSION.encode()) + rb"(?:\s|$)"
253
+ if proc.returncode or not re.match(version, proc.stdout):
254
+ raise FetchError(f"The program did not report pandoc {PANDOC_VERSION}. Install pandoc manually.")
255
+
256
+
257
+ def _publish(source: Path, destination: Path) -> None:
258
+ """Windows can briefly lock a file while another installer replaces it."""
259
+ for delay in (0.05, 0.1, 0.2, 0.4):
260
+ try:
261
+ os.replace(source, destination)
262
+ return
263
+ except PermissionError as exc:
264
+ if getattr(exc, "winerror", None) not in (5, 32, 33):
265
+ raise
266
+ time.sleep(delay)
267
+ os.replace(source, destination)
268
+
269
+
270
+ def _remove_stale_parts(folder: Path) -> None:
271
+ """Part files (tempfile's tmp*) that an interrupted download left behind; an hour old, so that no
272
+ install running at the same time loses its own."""
273
+ now = time.time()
274
+ for path in folder.glob("tmp*"):
275
+ try:
276
+ if path.is_file() and now - path.stat().st_mtime > 3600:
277
+ path.unlink()
278
+ except OSError:
279
+ pass
280
+
281
+
282
+ def _prune_older(folder: Path) -> None:
283
+ version = tuple(map(int, PANDOC_VERSION.split(".")))
284
+ for path in folder.parent.iterdir():
285
+ if re.fullmatch(r"[0-9]+(?:\.[0-9]+)+", path.name) and tuple(map(int, path.name.split("."))) < version:
286
+ if not path.is_symlink() and path.is_dir():
287
+ shutil.rmtree(path, ignore_errors=True)
288
+
289
+
290
+ def install(progress: Optional[_Progress] = None, cancel: Optional[threading.Event] = None,
291
+ url: Optional[str] = None, *, asset: Optional[Asset] = None) -> str:
292
+ """Download, verify and install pandoc. Progress receives bytes downloaded and the total if known."""
293
+ _check_cancel(cancel)
294
+ asset = asset or _release_asset()
295
+ folder = _folder()
296
+ try:
297
+ folder.mkdir(parents=True, exist_ok=True)
298
+ _remove_stale_parts(folder)
299
+ if shutil.disk_usage(folder).free < _MIN_FREE:
300
+ raise FetchError("Free at least 400 MB of disk space and try again.")
301
+ with ExitStack() as cleanup:
302
+ archive = _temp_path(folder, cleanup)
303
+ try:
304
+ size, digest = _download(url or _RELEASE_URL + asset.name, archive, progress, cancel, asset.size)
305
+ except (OSError, http.client.HTTPException, subprocess.TimeoutExpired) as exc:
306
+ _check_cancel(cancel)
307
+ raise FetchError(f"Could not download pandoc. Check your connection and try again. ({exc})") from exc
308
+ _check_cancel(cancel)
309
+ if size != asset.size or digest != asset.sha256:
310
+ raise FetchError("The download was not pandoc's release file. Nothing was installed. Try again.")
311
+ staged = _unpack(archive, asset, folder, cleanup, cancel)
312
+ binary = staged.pop(_EXE)
313
+ # Check our own copy before publishing. A failed or concurrent install keeps the working binary.
314
+ _check_version(binary)
315
+ _check_cancel(cancel)
316
+ for name, licence in staged.items():
317
+ _publish(licence, folder / name)
318
+ _publish(binary, folder / _EXE)
319
+ _prune_older(folder)
320
+ except (zipfile.BadZipFile, tarfile.TarError, EOFError) as exc:
321
+ raise FetchError("Could not read the pandoc archive. Download it again or install pandoc manually.") from exc
322
+ except OSError as exc:
323
+ raise FetchError(f"Could not install pandoc in {folder}. Check the folder permissions and free space. "
324
+ f"({exc})") from exc
325
+ return str(folder / _EXE)
mathshuttle/paths.py ADDED
@@ -0,0 +1,19 @@
1
+ """Per-user storage for downloaded programs."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import sys
6
+
7
+
8
+ def local_data_dir() -> str:
9
+ """The MathShuttle data folder on this computer."""
10
+ home = os.path.expanduser("~")
11
+ if sys.platform == "win32":
12
+ base = os.environ.get("LOCALAPPDATA") or os.path.join(home, "AppData", "Local")
13
+ elif sys.platform == "darwin":
14
+ base = os.path.join(home, "Library", "Application Support")
15
+ else:
16
+ base = os.environ.get("XDG_DATA_HOME", "")
17
+ if not os.path.isabs(base):
18
+ base = os.path.join(home, ".local", "share")
19
+ return os.path.join(base, "MathShuttle")
mathshuttle/preview.py ADDED
@@ -0,0 +1,232 @@
1
+ """A picture of the equation as LaTeX sets it, with the LaTeX installation found on PATH (latex + dvipng).
2
+
3
+ The preview shows what the LaTeX side looks like - the input when converting from LaTeX, the result when
4
+ converting to LaTeX - so a typo or a wrong Office -> LaTeX reading is seen before it goes into a paper.
5
+ It uses the user's macros and the usual maths packages; without a LaTeX installation there is no preview.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import os
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ import time
17
+ from typing import List, Optional, Sequence
18
+
19
+ _FLAGS = 0x08000000 if sys.platform == "win32" else 0 # CREATE_NO_WINDOW
20
+ PACKAGES = r"\usepackage{amsmath,amssymb,amsfonts,mathtools,bm}"
21
+ # packages that may be missing from a small installation: loaded only if present
22
+ OPTIONAL_PACKAGES = ("bbm", "dsfont")
23
+ # Each equation is set as $\displaystyle ...$ in the standalone class's own tight box (display maths would
24
+ # take the whole line). dvipng's tight crop loses a stretchy delimiter that is the leftmost ink (\left|),
25
+ # so every line starts and ends with an invisible white dot; the picture is on white.
26
+ TEMPLATE = r"""\documentclass[border=4pt,12pt]{standalone}
27
+ %(packages)s
28
+ \usepackage{xcolor}
29
+ \newcommand{\MathShuttleEdge}{\textcolor{white}{\rule{0.4pt}{0.4pt}}}
30
+ %(definitions)s
31
+ \begin{document}
32
+ %(body)s
33
+ \end{document}
34
+ """
35
+ _LINE = r"\MathShuttleEdge\hspace{1pt}%s\hspace{1pt}\MathShuttleEdge"
36
+
37
+ # An app started from the Finder or the Dock gets launchd's PATH (/usr/bin:/bin:/usr/sbin:/sbin), not
38
+ # the shell's: MacTeX's /Library/TeX/texbin, and Homebrew's bin for a TeX Live from there, are searched
39
+ # after PATH, and the TeX programs are run with their own directory on PATH (see _tex_env).
40
+ _MACOS_DIRS = ("/Library/TeX/texbin", "/opt/homebrew/bin", "/usr/local/bin") if sys.platform == "darwin" else ()
41
+
42
+ _tools: Optional[dict] = None
43
+
44
+
45
+ def _which(name: str) -> Optional[str]:
46
+ if not _MACOS_DIRS:
47
+ return shutil.which(name)
48
+ return shutil.which(name, path=os.pathsep.join([os.environ.get("PATH", os.defpath), *_MACOS_DIRS]))
49
+
50
+
51
+ def _tex_env(latex: str) -> Optional[dict]:
52
+ """The environment for latex, dvipng and kpsewhich: this process's own (None), but on macOS with
53
+ their directory added to PATH when it is not there. kpathsea finds mktexpk through PATH when a
54
+ font has no outlines (bbm, for \\mathbbm) and must be made; without it dvipng leaves the glyph blank."""
55
+ path = os.environ.get("PATH", os.defpath)
56
+ directory = os.path.dirname(latex)
57
+ if not _MACOS_DIRS or directory in path.split(os.pathsep):
58
+ return None
59
+ return dict(os.environ, PATH=os.pathsep.join([directory, path]))
60
+
61
+
62
+ def tools() -> Optional[dict]:
63
+ """{"latex": path, "dvipng": path, "miktex": bool, "packages": preamble, "env": for subprocess} or None
64
+ without LaTeX."""
65
+ global _tools
66
+ if _tools is None:
67
+ latex, dvipng = _which("latex"), _which("dvipng")
68
+ if not latex or not dvipng:
69
+ _tools = {}
70
+ else:
71
+ env = _tex_env(latex)
72
+ try:
73
+ version = subprocess.run([latex, "--version"], capture_output=True, timeout=20,
74
+ creationflags=_FLAGS, env=env).stdout.decode("utf-8", "replace")
75
+ except (OSError, subprocess.TimeoutExpired):
76
+ version = ""
77
+ packages = PACKAGES
78
+ kpsewhich = _which("kpsewhich")
79
+ for name in OPTIONAL_PACKAGES:
80
+ try:
81
+ found = kpsewhich and subprocess.run([kpsewhich, name + ".sty"], capture_output=True,
82
+ timeout=20, creationflags=_FLAGS, env=env).stdout.strip()
83
+ except (OSError, subprocess.TimeoutExpired):
84
+ found = False
85
+ if found:
86
+ packages += "\n\\usepackage{%s}" % name
87
+ _tools = {"latex": latex, "dvipng": dvipng, "miktex": "MiKTeX" in version, "packages": packages,
88
+ "env": env}
89
+ return _tools or None
90
+
91
+
92
+ class PreviewError(RuntimeError):
93
+ """The equation could not be set; the message is LaTeX's first error line."""
94
+
95
+
96
+ def cache_dir() -> str:
97
+ path = os.path.join(tempfile.gettempdir(), "MathShuttle-preview")
98
+ os.makedirs(path, exist_ok=True)
99
+ return path
100
+
101
+
102
+ def prune(path: Optional[str] = None, keep: int = 200) -> None:
103
+ """Keep the cache small: the `keep` newest pictures."""
104
+ path = path or cache_dir()
105
+ try:
106
+ names = sorted((os.path.join(path, n) for n in os.listdir(path)), key=os.path.getmtime, reverse=True)
107
+ except OSError:
108
+ return
109
+ pngs = [n for n in names if n.endswith(".png")]
110
+ for name in pngs[keep:]:
111
+ try:
112
+ os.remove(name)
113
+ except OSError:
114
+ pass
115
+ # leftovers of jobs that were cut off (a closed app): only old ones, a running job may be young
116
+ import time
117
+ for name in names:
118
+ if os.path.isdir(name) and time.time() - os.path.getmtime(name) > 3600:
119
+ shutil.rmtree(name, ignore_errors=True)
120
+
121
+
122
+ def _without_numbering(tex: str) -> str:
123
+ """`tex` without \\label{..}, \\tag{..}, \\tag*{..} (balanced arguments: \\tag{\\text{A}}), \\nonumber, \\notag."""
124
+ from .compat import _argument
125
+ pattern = re.compile(r"\\(?:label|tag\*?|nonumber|notag)(?![a-zA-Z@])")
126
+ while True:
127
+ m = pattern.search(tex)
128
+ if not m:
129
+ return tex
130
+ end = m.end()
131
+ if m.group().startswith(("\\label", "\\tag")):
132
+ _, end = _argument(tex, m.end())
133
+ tex = tex[:m.start()] + tex[end:]
134
+
135
+
136
+ def math_line(tex: str, display: bool) -> str:
137
+ """An equation's TeX as one line of maths: environments become their inner form (align -> aligned),
138
+ numbering commands go (LaTeX rejects \\tag in $...$)."""
139
+ from .latex_wrap import wrap
140
+ inline = wrap(_without_numbering(tex), "dollar", False) # $...$, with \begin{aligned} for an align
141
+ return "$\\displaystyle %s$" % inline[1:-1] if display else inline
142
+
143
+
144
+ def latex_command(t: dict, name: str) -> List[str]:
145
+ """The latex command line: no shell escape whatever the installation's default (MiKTeX's is
146
+ "restricted"), and no MiKTeX package-install dialog."""
147
+ args = [t["latex"], "-interaction=nonstopmode", "-halt-on-error", "-no-shell-escape"]
148
+ if t["miktex"]:
149
+ args.append("-disable-installer")
150
+ return args + [name]
151
+
152
+
153
+ _INSTALLED: dict = {}
154
+
155
+
156
+ def installed(package: str) -> bool:
157
+ """Whether the LaTeX installation has `package` (kpsewhich; remembered)."""
158
+ t = tools()
159
+ if t is None:
160
+ return False
161
+ if package not in _INSTALLED:
162
+ kpsewhich = _which("kpsewhich")
163
+ try:
164
+ _INSTALLED[package] = bool(kpsewhich and subprocess.run(
165
+ [kpsewhich, package + ".sty"], capture_output=True, timeout=20, creationflags=_FLAGS,
166
+ env=t.get("env")).stdout.strip())
167
+ except (OSError, subprocess.TimeoutExpired):
168
+ _INSTALLED[package] = False
169
+ return _INSTALLED[package]
170
+
171
+
172
+ def render(equations: Sequence, definitions: Sequence[str] = (), dpi: int = 130,
173
+ work: Optional[str] = None, packages: Sequence[str] = ()) -> str:
174
+ """A PNG of `equations` (objects with .tex and .display), one below the other, with `definitions` in
175
+ the preamble, and `packages` (physics, braket...: those the equations' commands come from) where the
176
+ installation has them. Cached by content."""
177
+ t = tools()
178
+ if t is None:
179
+ raise PreviewError("no LaTeX installation (latex and dvipng) on PATH")
180
+ work = work or cache_dir()
181
+ lines = [_LINE % math_line(eq.tex, eq.display) for eq in equations]
182
+ body = lines[0] if len(lines) == 1 else "\\begin{tabular}{@{}c@{}}%s\\end{tabular}" % "\\\\[8pt]\n".join(lines)
183
+ extra = "".join("\n\\usepackage{%s}" % p for p in packages if installed(p))
184
+ source = TEMPLATE % {"packages": t["packages"] + extra, "definitions": "\n".join(definitions), "body": body}
185
+ key = hashlib.sha1(("%d\0%s" % (dpi, source)).encode("utf-8")).hexdigest()[:20]
186
+ png = os.path.join(work, key + ".png")
187
+ if os.path.exists(png):
188
+ return png
189
+ # each job in a folder of its own (two renders of the same equation must not delete each other's
190
+ # files); the finished picture is moved into the cache in one step
191
+ job = tempfile.mkdtemp(prefix="job-", dir=work)
192
+ with open(os.path.join(job, "eq.tex"), "w", encoding="utf-8") as f:
193
+ f.write(source)
194
+ try:
195
+ p = subprocess.run(latex_command(t, "eq.tex"), cwd=job, capture_output=True, timeout=40, creationflags=_FLAGS,
196
+ env=t.get("env"))
197
+ if p.returncode:
198
+ log = p.stdout.decode("utf-8", "replace")
199
+ errors = [ln for ln in log.splitlines() if ln.startswith("!")]
200
+ context = re.search(r"^l\.\d+ (.*)$", log, re.M)
201
+ at = context.group(1) if context else ""
202
+ at = at.replace("\\MathShuttleEdge", "").replace("\\hspace{1pt}", "").replace("$\\displaystyle ", "$")
203
+ raise PreviewError("LaTeX: " + (errors[0][2:] if errors else "failed") +
204
+ (" (at: %s)" % at.strip()[-60:] if at.strip() else ""))
205
+ p = subprocess.run([t["dvipng"], "-D", str(dpi), "-T", "tight", "-bg", "White", "-q", "-o", "eq.png",
206
+ "eq.dvi"], cwd=job, capture_output=True, timeout=40, creationflags=_FLAGS, env=t.get("env"))
207
+ if p.returncode or not os.path.exists(os.path.join(job, "eq.png")):
208
+ raise PreviewError("dvipng failed: " + p.stderr.decode("utf-8", "replace").strip()[-200:])
209
+ for attempt in range(5):
210
+ try:
211
+ os.replace(os.path.join(job, "eq.png"), png)
212
+ break
213
+ except PermissionError:
214
+ # Windows: another render of the same equation put it there and the window is reading
215
+ # it (or a virus scanner holds it) - that picture is the same one
216
+ if os.path.exists(png):
217
+ break
218
+ if attempt == 4:
219
+ raise
220
+ time.sleep(0.1)
221
+ return png
222
+ except subprocess.TimeoutExpired:
223
+ raise PreviewError("LaTeX did not finish within 40 s")
224
+ except OSError as e:
225
+ raise PreviewError("Could not run LaTeX: %s" % e)
226
+ finally:
227
+ shutil.rmtree(job, ignore_errors=True)
228
+
229
+
230
+ def definitions_for(tex: str, macros) -> List[str]:
231
+ """The user's definitions an equation uses, for the preamble (as LaTeX takes them)."""
232
+ return [d.source for d in macros.needed(tex)] if macros else []