Coverage for src/manimgx/cli/preview.py: 94%
126 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
1"""`manimgx preview`: a scene in ManimGX's player, in a window of its own, made again each time
2its code is saved.
4The scene runs here, as `manimgx render` runs it, but its film is recorded as a take (see
5[`Film`][manimgx.Film]) and sent to a [`Window`][manimgx.Window], which plays it as it is made.
6On a save the scene runs again — at once: a run a save has made out of date is cut — and its new
7take replaces the old at the same moment, once it gets there: an edit never loses the place. An
8error is shown over the last good take.
9"""
11import importlib
12import sys
13import time
14import traceback
15from collections.abc import Callable, Iterator, Sequence
16from contextlib import contextmanager
17from importlib.abc import MetaPathFinder
18from importlib.machinery import ModuleSpec, PathFinder, SourceFileLoader
19from pathlib import Path
20from types import ModuleType
21from typing import Annotated
23import typer
25from manimgx.cli.scenes import (
26 File,
27 Format,
28 Fps,
29 Mistake,
30 Resolution,
31 SceneName,
32 Size,
33 Source,
34 fail,
35 load,
36 pick,
37 report_error,
38 scenes,
39)
40from manimgx.rendering.film import Cut
41from manimgx.rendering.window import Window
42from manimgx.settings import config
44POLL = 0.02 # seconds between looks at the files
47def preview(
48 file: File,
49 name: SceneName = None,
50 time_: Annotated[
51 float,
52 typer.Option(
53 "--time", "-t", min=0, help="Where the playhead starts, in seconds."
54 ),
55 ] = 0.0,
56 resolution: Resolution = None,
57 fps: Fps = None,
58) -> None:
59 """Preview a scene live: in a window, made again each time its code is saved.
61 The window plays the scene as it is made. Saving the file, or a module it imports from
62 beside it, runs the scene again, and the window keeps its place; an error shows over the
63 last good picture. A file of several scenes plays the one named, or its first; N and P go
64 to the others. Keys: Space play/pause, ← → 5 s, , . a frame, Option (or Ctrl) with ← → a
65 play, ? all of them. Closing the window, or Ctrl+C, stops."""
66 if not file.is_file():
67 raise fail(f"error: {file}: no such file")
68 with Window(f"{file.name} — ManimGX", time=time_) as window:
69 try:
70 files = [file]
71 while window.open:
72 news = News(files, window) # the files as this run reads them
73 files = run(file, name, resolution, fps, window, news)
74 news.watch(files)
75 while window.open and not news():
76 time.sleep(POLL)
77 if news.asked is not None:
78 name = news.asked
79 else:
80 time.sleep(POLL) # an editor saving in steps: let it finish
81 except KeyboardInterrupt:
82 pass
83 if window.failure is not None:
84 raise fail(f"error: the window: {window.failure}", 1)
87class News:
88 """What makes a run out of date: a file it reads saved again, or another scene asked for
89 in the window. Called, whether there is any (it looks every `POLL` seconds)."""
91 def __init__(self, files: list[Path], window: Window) -> None:
92 self.seen = dict(zip(files, stamps(files), strict=True))
93 self.window = window
94 self.asked: str | None = None
95 self.any = False # there was some
96 self.looked = time.monotonic()
98 def watch(self, files: list[Path]) -> None:
99 """Watch `files` too: those not watched yet as they are now."""
100 new = [f for f in files if f not in self.seen]
101 self.seen.update(zip(new, stamps(new), strict=True))
103 def __call__(self) -> bool:
104 now = time.monotonic()
105 if now - self.looked < POLL:
106 return False
107 self.looked = now
108 self.asked = self.window.asked() or self.asked
109 files = list(self.seen)
110 self.any = self.asked is not None or stamps(files) != list(self.seen.values())
111 return self.any
114def run(
115 file: Path,
116 name: str | None,
117 resolution: Size | None,
118 fps: int | None,
119 window: Window,
120 news: News,
121) -> list[Path]:
122 """Run the scene once, its take (or its error) into `window`, and cut it once `news`
123 makes it out of date. Returns the files to watch: the scene's, and the modules it imported
124 from beside it."""
125 root = file.resolve().parent
126 started = time.perf_counter()
128 def take(data: bytes) -> None:
129 if news():
130 raise Cut # out of date: run again
131 window(data)
133 with imports(file, news.watch) as source:
134 try:
135 module = load(file)
136 found = [s.__name__ for s in scenes(module)]
137 # unnamed, the file's first scene: its viewer goes to the others in the window (N, P)
138 kind = pick(
139 file, module, found[0] if name is None and len(found) > 1 else name
140 )
141 window.scenes(found, kind.__name__)
142 look = Format.own(resolution, fps)
143 config.pixel_width, config.pixel_height = look.width, look.height
144 config.frame_rate = look.fps
145 film = kind().render(take=take)
146 cut = "cut: " if news.any or not window.open else ""
147 typer.echo(
148 f"{kind.__name__}: {cut}{film.frame_count} frames in"
149 f" {time.perf_counter() - started:.2f} s",
150 err=True,
151 )
152 except Exception as error:
153 text = str(error) if isinstance(error, Mistake) else report_error(error)
154 typer.echo(text, err=True)
155 own = [
156 f
157 for f in traceback.extract_tb(error.__traceback__)
158 if Path(f.filename).resolve().is_relative_to(root)
159 ]
160 window.failed(
161 error, text, own[-1].lineno if own else getattr(error, "lineno", None)
162 )
163 return list(source.files)
166class Sources(MetaPathFinder):
167 """The scene-directory imports owned by one authoring generation."""
169 def __init__(
170 self, file: Path, host: set[str], watch: Callable[[list[Path]], None] | None
171 ) -> None:
172 self.root = file.resolve().parent
173 self.host = host
174 self.watch = watch
175 self.modules = {file.stem}
176 self.files = {file.resolve()}
178 def find_spec(
179 self,
180 fullname: str,
181 path: Sequence[str] | None = None,
182 target: ModuleType | None = None,
183 ) -> ModuleSpec | None:
184 top = fullname.partition(".")[0]
185 if top in self.host and top not in self.modules:
186 return None
187 spec = PathFinder.find_spec(fullname, path, target)
188 if spec is None:
189 return None
190 if "." not in fullname:
191 local = PathFinder.find_spec(fullname, [str(self.root)])
192 if local is None or local.origin != spec.origin:
193 return None
194 if spec.origin is None and not set(
195 local.submodule_search_locations or ()
196 ) & set(spec.submodule_search_locations or ()):
197 return None
198 elif fullname.rpartition(".")[0] not in self.modules:
199 return None
200 self.modules.add(fullname)
201 if isinstance(spec.loader, SourceFileLoader):
202 file = Path(spec.loader.path).absolute()
203 # Ownership follows the import entry, including symlinks and namespace portions.
204 self.files.add(file)
205 if self.watch is not None:
206 self.watch([file])
207 spec.loader = Source(fullname, str(file))
208 return spec
211@contextmanager
212def imports(
213 file: Path, watch: Callable[[list[Path]], None] | None = None
214) -> Iterator[Sources]:
215 """Load the scene's modules for one run; preserve the process that hosts it."""
216 before, path = dict(sys.modules), sys.path.copy()
217 source = Sources(file, {name.partition(".")[0] for name in before}, watch)
218 sys.meta_path.insert(sys.meta_path.index(PathFinder), source)
219 importlib.invalidate_caches()
220 try:
221 yield source
222 finally:
223 sys.meta_path.remove(source)
224 sys.path[:] = path
225 for name in source.modules:
226 if name in before:
227 sys.modules[name] = before[name]
228 else:
229 sys.modules.pop(name, None)
232def stamps(paths: list[Path]) -> list[float]:
233 """The files' modification times (0 for one that is gone, for now)."""
234 return [p.stat().st_mtime if p.exists() else 0.0 for p in paths]