The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Unify text layout caching and bundled font defaults
Sina Atalaye4222af4ef72
diff --git a/rust/engine/src/typeset.rs b/rust/engine/src/typeset.rsindex c05226da..6f3f7aec 100644--- a/rust/engine/src/typeset.rs+++ b/rust/engine/src/typeset.rs@@ -8,7 +8,7 @@//! y up. Python scales points to scene units.use std::collections::HashMap;-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex, OnceLock};use typst::diag::{FileError, FileResult, Severity, SourceDiagnostic};@@ -110,6 +110,18 @@ type Cached = (PathBuf, u32, String, FontVariant, FontFlags, Vec<FontAxis>, Cove/// What made a cached scan, in its file's name: bump it with Typst, or when `Cached` changes.const SCAN: &str = "typst-0.15.1";+/// MANIMGX_CACHE_DIR when set, otherwise the current user's native cache or the browser+/// runtime's private filesystem. A missing native root disables disk reuse, with no shared-temp fallback.+pub fn cache_directory() -> Option<PathBuf> {+ if let Some(root) = std::env::var_os("MANIMGX_CACHE_DIR").filter(|root| !root.is_empty()) {+ return Some(root.into());+ }+ #[cfg(target_os = "emscripten")]+ return Some(std::env::temp_dir().join("manimgx"));+ #[cfg(not(target_os = "emscripten"))]+ dirs::cache_dir().map(|root| root.join("manimgx"))+}+/// The fonts under `dirs`, as Typst finds them (`find`: typst-kit's scan of them), read from a/// cache on disk while no file under them has changed: scanning parses every font (~50 ms for the/// system's, ~15 ms for a CJK collection); checking the files' sizes and times costs a few@@ -121,10 +133,13 @@ fn cached_scan(if dirs.is_empty() {return Vec::new();}- let dir = std::env::temp_dir().join("manimgx-fonts");let key = fingerprint(dirs);- let cache = dir.join(format!("{SCAN}-{key:016x}.bin"));- let entries: Vec<Cached> = match std::fs::read(&cache).ok().and_then(|b| bincode::deserialize(&b).ok()) {+ let cache = cache_directory().map(|root| root.join("fonts").join(format!("{SCAN}-{key:016x}.bin")));+ read_scan(cache.as_deref(), find)+}++fn read_scan(cache: Option<&Path>, find: impl FnOnce() -> Vec<(FontPath, FontInfo)>) -> Vec<(Mapped, FontInfo)> {+ let entries: Vec<Cached> = match cache.and_then(|path| std::fs::read(path).ok()).and_then(|b| bincode::deserialize(&b).ok()) {Some(entries) => entries,None => {let entries: Vec<Cached> = find()@@ -134,12 +149,14 @@ fn cached_scan((path.path, path.index, family, variant, flags, axes, coverage)}).collect();- if let Ok(bytes) = bincode::serialize(&entries) {+ if let Some(cache) = cache+ && let Ok(bytes) = bincode::serialize(&entries)+ {// written whole, then renamed: a reader never sees half a file- let partial = dir.join(format!("{SCAN}-{key:016x}.{}.tmp", std::process::id()));- let _ = std::fs::create_dir_all(&dir)+ let partial = cache.with_extension(format!("{}.tmp", std::process::id()));+ let _ = std::fs::create_dir_all(cache.parent().expect("cache directory")).and_then(|()| std::fs::write(&partial, bytes))- .and_then(|()| std::fs::rename(&partial, &cache));+ .and_then(|()| std::fs::rename(&partial, cache));}entries}@@ -734,3 +751,18 @@ pub fn mitex_math(latex: &str) -> Result<String, String> {pub fn mitex_text(latex: &str) -> Result<String, String> {mitex::convert_text(latex, None)}++#[cfg(test)]+mod tests {+ #[test]+ fn unavailable_cache_root_scans_each_time() {+ let calls = std::cell::Cell::new(0);+ for _ in 0..2 {+ assert!(super::read_scan(None, || {+ calls.set(calls.get() + 1);+ Vec::new()+ }).is_empty());+ }+ assert_eq!(calls.get(), 2);+ }+}diff --git a/src/manimgx/drawing/typesetting.py b/src/manimgx/drawing/typesetting.pyindex 07929285..d92a3b20 100644--- a/src/manimgx/drawing/typesetting.py+++ b/src/manimgx/drawing/typesetting.py@@ -74,7 +74,11 @@ class Layout:# Reuse under disjoint native (<2^48) or content (>=2^52) keys. The bound counts# aliases; either can be forgotten independently. Live layouts own their records._GLYPHS: Memo[int, Glyph] = Memo(1 << 12)-_CACHE = Path(tempfile.gettempdir()) / "manimgx-layouts"+_CACHE = (+ Path(directory) / "layouts"+ if (directory := _engine.cache_directory()) is not None+ else None+)# what made a layout, part of its key: the entry's format, and the engine's own file (a rebuilt# engine never reads a layout an older one made)_ENGINE = Path(_engine.__file__).stat()@@ -118,9 +122,9 @@ def typeset(The document is set in the fonts manimgx ships (Typst's own and the Noto faces),after those in `font_paths`; a system font is read only for a family the document- names that none of them has. A layout is kept on disk, under the system's temporary- directory (`manimgx-layouts`): the same document, with the same fonts and packages,- is read back, not typeset again, in any process.+ names that none of them has. A layout is kept in the current user's cache directory+ (the browser's private filesystem in a page): the same document, with the same fonts+ and packages, is read back, not typeset again, in any process.Args:body: The document's body: Typst markup.@@ -137,11 +141,12 @@ def typeset(packages = None if package_path is None else str(package_path)depends = _files(fonts if packages is None else (*fonts, packages))key = _engine.digest(_VERSION, b"\0", source.encode(), b"\0", depends)- path = _CACHE / f"{key:016x}.layout"- stored = _read(path)+ path = None if _CACHE is None else _CACHE / f"{key:016x}.layout"+ stored = None if path is None else _read(path)if stored is None:stored = _typeset(source, fonts, packages)- _write(path, stored)+ if path is not None:+ _write(path, stored)rows, shapes, labels, _, glyphs = storedrecords = {key: _glyph(key, points, carets) for key, (points, carets) in glyphs.items()@@ -190,11 +195,12 @@ def _read(path: Path) -> Stored | None:def _write(path: Path, stored: Stored) -> None:"""Store a layout: written whole, then renamed, so a reader never sees half of one."""- partial = path.with_suffix(f".{os.getpid()}.tmp")try:- _CACHE.mkdir(parents=True, exist_ok=True)- partial.write_bytes(pickle.dumps(stored, protocol=5))- os.replace(partial, path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(dir=path.parent) as own:+ partial = Path(own) / "layout"+ partial.write_bytes(pickle.dumps(stored, protocol=5))+ os.replace(partial, path)except OSError:passdiff --git a/src/manimgx/mobjects/code.py b/src/manimgx/mobjects/code.pyindex 0ccb5e6f..e08d5344 100644--- a/src/manimgx/mobjects/code.py+++ b/src/manimgx/mobjects/code.py@@ -1,6 +1,6 @@-"""Code: a highlighted listing laid out as CE lays it out, set by Typst's `raw` (its grammars-find the tokens; a theme colors each scope as the pygments style colors the token there; each-advance is rounded to a whole Pango unit, as Pango places glyphs)."""+"""Code: a highlighted listing set by Typst's `raw`. Its grammars find the tokens; a theme+colors each scope as the pygments style colors the token there. With a monospaced font and+one glyph per character, column advances are rounded to whole Pango units."""import mathimport re@@ -8,7 +8,9 @@ from collections.abc import Mappingfrom dataclasses import dataclassfrom functools import cachefrom pathlib import Path-from typing import ClassVar, Literal, TypedDict+from typing import ClassVar, Literal++from typing_extensions import TypedDictfrom manimgx.caches import forgetsfrom manimgx.constants import LEFT, ORIGIN, RIGHT, SCALE_FACTOR_PER_FONT_POINT, UP@@ -31,8 +33,6 @@ _SCENE_PER_UNIT = 0.05_POINT = _SCENE_PER_UNIT / SCALE_FACTOR_PER_FONT_POINT_LINE_SPACING = 0.3 # CE's Text's, for a line_spacing of -1-# CE's "Monospace", as Pango finds it: Menlo on macOS; elsewhere DejaVu Sans Mono, Typst's own-_MONOSPACE = ("Menlo", "DejaVu Sans Mono")_PYTHON = frozenset({"python", "py", "python3", "py3"})_LINE = "line" # a line's label: "line1" the first# pygments' Python lexer: these are builtins wherever they stand, parameters too@@ -109,9 +109,8 @@ class CodeText(TypedDict, total=False):keywords that apply to a listing."""font: str- """The font family: "Monospace", the default, is Menlo where the system has it, and- elsewhere DejaVu Sans Mono, which manimgx ships; any other family is one manimgx- ships, or else the system's."""+ """The font family: "Monospace", the default, is the bundled DejaVu Sans Mono on+ every platform; any other family is one manimgx ships, or else the system's."""font_size: float"""The size of the text: an em is `font_size / 72` scene units (default 24)."""line_spacing: float@@ -154,8 +153,8 @@ def _typeset(language: str | None = None,suffix: str = "",) -> list[VGroup]:- """Each line's glyphs as Pango sets them (advances rounded to whole units, a fixed pitch- between baselines), highlighted in `style` if given; `suffix` closes the first and last lines.+ """Each line's glyphs, with fixed baseline spacing and adjusted monospaced columns,+ highlighted in `style` if given; `suffix` closes the first and last lines."""size = text.get("font_size", 24)spacing = text.get("line_spacing", -1)@@ -163,10 +162,8 @@ def _typeset(pitch = size * (1 + (_LINE_SPACING if spacing == -1 else spacing))pitch *= _PANGO_PER_FONT_SIZEfont = text.get("font", "Monospace")- fonts = "".join(- f"{typst_string(f)}, " for f in (_MONOSPACE if font == "Monospace" else (font,))- )- face = f"font: ({fonts}), size: {em}pt"+ family = "DejaVu Sans Mono" if font == "Monospace" else font+ face = f"font: {typst_string(family)}, size: {em}pt"ligatures = "false" if text.get("disable_ligatures", True) else "true"closing = (f"; if it.number in (1, it.count) {{ {typst_string(suffix)} }}"@@ -228,11 +225,11 @@ class Code(VMobject):r"""A listing of source code, highlighted: its lines, their numbers, and a rectangleor a window behind them.- The code is highlighted by Typst's grammars, in the colors of `formatter_style`, and- set on a fixed grid, each character a column. The parts are+ The code is highlighted by Typst's grammars, in the colors of `formatter_style`, with+ a monospaced font by default. The parts are[background][manimgx.Code.background], [line_numbers][manimgx.Code.line_numbers] (ifthe lines are numbered) and [code_lines][manimgx.Code.code_lines], whose i-th part is- the i-th line, a group of its glyphs, spaces excluded. Tabs are expanded, and blank+ the i-th line, a group of its glyphs, spaces excluded. Tabs are expanded, and emptylines at the start and at the end are dropped.Args:@@ -316,7 +313,7 @@ class Code(VMobject):raise ValueError("Either a code file or a code string must be specified.")style = _STYLES[formatter_style]text = self.default_paragraph_config | (paragraph_config or {})- # the lines as pygments hands them to CE: tabs expanded, blank lines trimmed off+ # tabs expanded, empty lines trimmed offcode = (code_string.expandtabs(tab_width).replace("\r\n", "\n").replace("\r", "\n"))diff --git a/src/manimgx/mobjects/text.py b/src/manimgx/mobjects/text.pyindex 1a6d7da4..4e91ab42 100644--- a/src/manimgx/mobjects/text.py+++ b/src/manimgx/mobjects/text.py@@ -74,6 +74,7 @@ from manimgx.drawing.paint import (ManimColor,ParsableManimColor,Repaint,+ _Look,color_gradient,)from manimgx.drawing.typesetting import (@@ -112,14 +113,8 @@ def _hex(rgba: np.ndarray) -> str:return color-class TypstOptions(Look, Repaint, total=False):- """[Typst][manimgx.Typst]'s keywords, for the classes that pass them on: text and- LaTeX.-- Beyond these, they take the [look keywords][manimgx.drawing.paint.Look], and the- [paint keywords][manimgx.drawing.paint.Repaint], which paint over the colors the- typesetting gives the parts.- """+class _TypstOptions(_Look, Repaint, total=False):+ """TypstOptions's keys, open, for the keywords that add to them."""font_size: float"""The size of the text: an em is `font_size / 96` scene units, 0.5 at the default,@@ -147,6 +142,16 @@ class TypstOptions(Look, Repaint, total=False):Nothing is downloaded."""+class TypstOptions(_TypstOptions, total=False, closed=True):+ """[Typst][manimgx.Typst]'s keywords, for the classes that pass them on: text and+ LaTeX.++ Beyond these, they take the [look keywords][manimgx.drawing.paint.Look], and the+ [paint keywords][manimgx.drawing.paint.Repaint], which paint over the colors the+ typesetting gives the parts.+ """++class TypstGlyph(VMobject):"""One glyph as Typst set it, a part of a typeset mobject: its outline, placed, andwhich characters of the source it draws.@@ -234,6 +239,9 @@ class Typst(VMobject):typeset ones.stroke_width: A stroke width for every part, in hundredths of a scene unit;None keeps the typeset ones, which scale with the mobject.+ opacity: The opacity of every part's fill and stroke, from 0 to 1, where+ `fill_opacity` or `stroke_opacity` doesn't give one; None keeps the+ typeset ones.Examples:```python@@ -271,6 +279,7 @@ class Typst(VMobject):stroke_color: Colors | None = None,stroke_opacity: float | Sequence[float] | None = None,stroke_width: float | None = None,+ opacity: float | None = None,**kwargs: Unpack[Look],):super().__init__(stroke_color=None, fill_color=None, **kwargs)@@ -296,6 +305,9 @@ class Typst(VMobject):),font_size * font_scale * SCALE_FACTOR_PER_FONT_POINT if placed else None,)+ if opacity is not None: # both, where one isn't given its own+ fill_opacity = opacity if fill_opacity is None else fill_opacity+ stroke_opacity = opacity if stroke_opacity is None else stroke_opacityself.set_style(fill_color=fill_color,fill_opacity=fill_opacity,@@ -714,7 +726,7 @@ def _calibration(font: str, kwargs: TypstOptions) -> float:return target / probe.height if probe.height > 0 else 1.0-class TextOptions(TypstOptions, total=False):+class TextOptions(_TypstOptions, total=False, closed=True):"""[Text][manimgx.Text]'s keywords, for the classes that pass them on:[Paragraph][manimgx.Paragraph].@@ -878,8 +890,8 @@ class Text(Typst):disable_ligatures: bool = False,**kwargs: Unpack[TypstOptions],) -> None:- if kwargs.get("fill_opacity") is None: # not given, None too- kwargs["fill_opacity"] = 1.0+ if kwargs.get("fill_opacity") is None and kwargs.get("opacity") is None:+ kwargs["fill_opacity"] = 1.0 # filled, unless an opacity is givenself.text = text"""The text, as it was written."""self.original_text = text@@ -1314,7 +1326,7 @@ class MathTexPart(VGroup):"""The LaTeX the part was typeset from."""-class MathTexOptions(TypstOptions, total=False):+class MathTexOptions(_TypstOptions, total=False, closed=True):"""[MathTex][manimgx.MathTex]'s keywords, for the classes that pass them on:[Tex][manimgx.Tex], [BulletedList][manimgx.BulletedList], [Title][manimgx.Title] andlabels.diff --git a/tests/unit/drawing/test_typesetting.py b/tests/unit/drawing/test_typesetting.pyindex 2e9e0322..058c346b 100644--- a/tests/unit/drawing/test_typesetting.py+++ b/tests/unit/drawing/test_typesetting.py@@ -18,10 +18,18 @@"""import gc+import json+import os+import pickleimport re+import shutil+import subprocess+import sysimport weakreffrom collections.abc import Callable, Iterator, Sequence+from concurrent.futures import ThreadPoolExecutorfrom pathlib import Path+from threading import Eventfrom typing import ClassVar, NamedTupleimport numpy as np@@ -39,6 +47,118 @@ type Document = m.Typst | m.Paragraphtype Answer = tuple[bytes, list[bytes], list[tuple[str, list[int]]], bool]+def test_shared_temporary_cache_cannot_replace_fonts_or_layouts(tmp_path: Path) -> None:+ """Benign, valid empty entries in the old shared location must have no authority."""+ font = next(+ p for p in Path(tc.FONTS[0]).glob("*.ttf") if p.name.startswith("NotoSans[")+ )+ fonts = tmp_path / "fonts"+ fonts.mkdir()+ shutil.copy2(font, fonts / font.name)+ program = r"""+import hashlib, json, sys, tempfile+from pathlib import Path+import numpy as np+from manimgx import _engine+from manimgx.drawing import typesetting as t+root = getattr(_engine, 'cache_directory', lambda: None)()+scans = Path(tempfile.gettempdir()) / 'manimgx-fonts' if root is None else Path(root) / 'fonts'+layouts = t._CACHE+before_scans = set(scans.glob('*.bin'))+before_layouts = set(layouts.glob('*.layout'))+rows, _, _, system = _engine.typeset('#set text(font:"Noto Sans")\nHello Ω', [sys.argv[1]])+table = np.frombuffer(rows).reshape(-1, 23)+keys = sorted(set(int(row[1]) for row in table if row[0] == 0))+native = hashlib.sha256(rows + b''.join(_engine.glyph_outlines(keys))).hexdigest()+layout = t.typeset('Hello Ω', font_paths=[sys.argv[1]])+print(json.dumps({'native': native, 'layout': hashlib.sha256(layout.rows.tobytes()).hexdigest(),+ 'scans': [p.name for p in set(scans.glob('*.bin')) - before_scans],+ 'layouts': [p.name for p in set(layouts.glob('*.layout')) - before_layouts]}))+"""+ env = dict(+ os.environ,+ TMPDIR=str(tmp_path),+ TMP=str(tmp_path),+ TEMP=str(tmp_path),+ PYTHONPATH=str(Path(m.__file__).resolve().parent.parent),+ )+ env.pop("MANIMGX_CACHE_DIR", None)++ def run() -> dict[str, str | list[str]]:+ result = subprocess.run(+ [sys.executable, "-c", program, str(fonts)],+ env=env,+ capture_output=True,+ text=True,+ check=True,+ timeout=30,+ )+ return json.loads(result.stdout)++ before = run()+ assert before["scans"]+ assert before["layouts"]+ for folder, names, payload in (+ ("manimgx-fonts", before["scans"], bytes(8)), # bincode's empty Vec+ (+ "manimgx-layouts",+ before["layouts"],+ pickle.dumps((np.empty((0, tc.ROW)), [], [], 0, {}), protocol=5),+ ),+ ):+ target = tmp_path / folder+ target.mkdir(exist_ok=True)+ for name in names:+ (target / name).write_bytes(payload)+ after = run()+ assert (after["native"], after["layout"]) == (+ before["native"],+ before["layout"],+ )+++def test_concurrent_cache_writers_publish_complete_owned_files(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ path = tmp_path / "entry.layout"+ stored: tc.Stored = (np.zeros((100, tc.ROW)), [], [], 0, {})+ expected = pickle.dumps(stored, protocol=5)+ first_written, second_half, published = Event(), Event(), Event()+ write_bytes, replace = Path.write_bytes, os.replace+ observed: list[bytes] = []++ def write(partial: Path, data: bytes) -> int:+ if not first_written.is_set():+ count = write_bytes(partial, data)+ first_written.set()+ assert second_half.wait(3)+ return count+ with partial.open("wb") as stream:+ stream.write(data[: len(data) // 2])+ stream.flush()+ second_half.set()+ assert published.wait(3)+ observed.append(path.read_bytes())+ stream.write(data[len(data) // 2 :])+ return len(data)++ def publish(source: Path, destination: Path) -> None:+ replace(source, destination)+ published.set()++ monkeypatch.setattr(Path, "write_bytes", write)+ monkeypatch.setattr(os, "replace", publish)+ with ThreadPoolExecutor(max_workers=2) as pool:+ first = pool.submit(tc._write, path, stored)+ assert first_written.wait(3)+ second = pool.submit(tc._write, path, stored)+ first.result(timeout=5)+ second.result(timeout=5)+ assert observed == [expected]+ assert path.read_bytes() == expected+ assert list(tmp_path.iterdir()) == [path]++class Engine:"""The engine, counting the documents it is asked to set; or, `made_up`, a font withligature carets: "first", "second" and "missing" are a glyph each, a square 1000 units wide@@ -81,6 +201,19 @@ class Engine:carets[:] = [900.0] * len(carets)+def test_unavailable_cache_root_typesets_without_disk_reuse(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ engine = Engine(monkeypatch, made_up=True)+ monkeypatch.setattr(tc, "_CACHE", None)+ first = tc.typeset("first second")+ caches.clear()+ second = tc.typeset("first second")+ assert engine.asked == 2+ assert first.rows.tobytes() == second.rows.tobytes()+ assert first.glyphs.keys() == second.glyphs.keys()++class Case(NamedTuple):make: Callable[[], Document]named: dict[str, list[int]] | None = Nonediff --git a/tests/unit/mobjects/test_code.py b/tests/unit/mobjects/test_code.pyindex c58b91f3..41abd061 100644--- a/tests/unit/mobjects/test_code.py+++ b/tests/unit/mobjects/test_code.py@@ -1,11 +1,24 @@"""Code sets its glyphs in rows on a monospace column grid: a tab advances to the next tab stop,an empty line is an empty row, and the line numbers end on one right edge."""+import numpy as npimport pytestimport manimgx as m[email protected]("font", [None, "Monospace"])+def test_default_code_font_is_the_bundled_monospace(font: str | None) -> None:+ listing = "from manim import Scene\n\nclass Example(Scene):\n pass"+ default = m.Code(+ code_string=listing,+ paragraph_config={} if font is None else {"font": font},+ )+ bundled = m.Code(code_string=listing, paragraph_config={"font": "DejaVu Sans Mono"})+ # An installed system monospace must not change outlines, advances or line numbers.+ np.testing.assert_array_equal(default.get_all_points(), bundled.get_all_points())++@pytest.mark.parametrize("tab_width", [2, 4])@pytest.mark.parametrize("font_size", [12, 36])def test_code_rows_partition_glyphs_on_the_column_grid(diff --git a/tests/unit/mobjects/test_text.py b/tests/unit/mobjects/test_text.pyindex 5da0e626..0a56b47a 100644--- a/tests/unit/mobjects/test_text.py+++ b/tests/unit/mobjects/test_text.py@@ -21,6 +21,8 @@set to. Its rules' widths scale with it unless set; fitted before coloring, a text keeps itsligatures' shapes.- A title's color is its underline's too.+- `opacity` is every part's fill and stroke opacity, where `fill_opacity` or+ `stroke_opacity` doesn't give one, in each of Typst's front ends.Baselines are read off capitals "H", whose ink sits on the baseline."""@@ -91,6 +93,21 @@ def test_a_paragraph_is_one_text_its_lines_aligned(}[email protected]("kind", [m.Text, m.MathTex, m.Tex, m.Typst])+def test_opacity_is_each_parts_where_no_other_is_given(+ kind: type[m.Typst] | type[m.Text],+) -> None:+ faint = kind("x", opacity=0.3)+ parts = faint.family_members_with_points()+ assert parts+ for part in parts:+ assert part.get_fill_opacity() == pytest.approx(0.3)+ assert part.get_stroke_opacity() == pytest.approx(0.3)+ filled = kind("x", opacity=0.3, fill_opacity=0.8)+ for part in filled.family_members_with_points():+ assert part.get_fill_opacity() == pytest.approx(0.8)++def test_a_titles_color_is_its_underlines_too() -> None:"""Title(color=c) is Title().set_color(c): the underline included."""given = m.Title("Title", color=m.RED)