Coverage for src/manimgx/rendering/window.py: 70%

94 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-26 05:52 +0000

1"""Window: ManimGX's player in a window of its own, on this machine's screen, drawn by its GPU. 

2 

3A window plays the takes it is sent (see [`Film`][manimgx.Film]): each frame as soon as it is 

4recorded, any frame again at once. A newer take — the scene run again — replaces the one shown 

5at the same moment, once it gets there: an edit never loses the place. 

6 

7 with m.Window() as window: 

8 MyScene().render(take=window) 

9 window.wait() # until it is closed 

10 

11The window is a process of its own, which the take reaches through a pipe: it plays on while 

12the scene runs, and a scene's process stays free for the scene. It closes when it is closed, or 

13when the process that opened it closes it, or ends. 

14""" 

15 

16import contextlib 

17import json 

18import queue 

19import subprocess 

20import sys 

21import threading 

22from collections.abc import Sequence 

23from types import TracebackType 

24from typing import Self 

25from warnings import deprecated 

26 

27from manimgx import _engine 

28from manimgx.rendering.film import Cut 

29 

30__all__ = ["Window"] 

31 

32 

33class Window: 

34 """ManimGX's player in a window on this machine's screen, which plays the takes it is sent. 

35 

36 A window is a [`Take`][manimgx.rendering.film.Take]: hand it to 

37 [`Scene.render`][manimgx.Scene.render] as `take`, and it plays the film as it is recorded. 

38 Once it is closed, a film sent to it is cut (see [`Cut`][manimgx.rendering.film.Cut]). 

39 

40 Its viewer can ask for another of the file's scenes (N and P). 

41 

42 Args: 

43 title: The window's title. 

44 time: Where its playhead starts, in seconds. 

45 """ 

46 

47 def __init__(self, title: str = "ManimGX", *, time: float = 0.0) -> None: 

48 self._process = subprocess.Popen( 

49 [ 

50 sys.executable, 

51 "-c", 

52 "from manimgx.rendering.window import _main; _main()", 

53 ] 

54 + [title, repr(float(time))], 

55 stdin=subprocess.PIPE, 

56 stdout=subprocess.PIPE, 

57 ) 

58 self._asked: queue.Queue[str] = queue.Queue() 

59 self.failure: str | None = None 

60 """Why the window failed, if it did (no screen to open on, no GPU): it is closed.""" 

61 self._listening = threading.Thread(target=self._listen, daemon=True) 

62 self._listening.start() 

63 

64 def __call__(self, data: bytes) -> None: 

65 """Send the window the take's next bytes. 

66 

67 Raises: 

68 Cut: The window is closed: the film is cut there. 

69 """ 

70 pipe = self._process.stdin 

71 if pipe is None or pipe.closed: 

72 raise Cut 

73 try: 

74 pipe.write(data) # whole: a buffered pipe writes it all 

75 pipe.flush() 

76 except (BrokenPipeError, ValueError): 

77 with contextlib.suppress(OSError): 

78 pipe.close() 

79 raise Cut from None 

80 

81 @deprecated("ManimGX's machinery: ManimGX preview calls it", category=None) 

82 def scenes(self, names: Sequence[str], playing: str) -> None: 

83 """Tell the window the file's scenes, and the one it plays: its viewer can ask for 

84 the others (N, P; see [`asked`][manimgx.Window.asked]). 

85 

86 Args: 

87 names: The file's scenes, in order. 

88 playing: The one its takes are of now. 

89 """ 

90 self._say({"scenes": list(names), "scene": playing}) 

91 

92 @deprecated("ManimGX's machinery: ManimGX preview calls it", category=None) 

93 def failed(self, error: BaseException, trace: str, line: int | None = None) -> None: 

94 """Show the scene's error over the last picture it made, until the next take. 

95 

96 Args: 

97 trace: What to show: the lines of the scene's code it went through, and the error. 

98 line: The line of the scene's file it failed at, if any. 

99 """ 

100 fault = {"message": str(error), "type": type(error).__name__} 

101 self._say({"error": {**fault, "trace": trace, "line": line}}) 

102 

103 def _say(self, note: dict[str, object]) -> None: 

104 """A note between takes (the director's JSON, see `Film`): nothing, to a closed 

105 window.""" 

106 with contextlib.suppress(Cut): 

107 self(_engine.note(json.dumps(note))) 

108 

109 @property 

110 def open(self) -> bool: 

111 """Whether the window is open: until its viewer closes it, or it is closed.""" 

112 return self._process.poll() is None 

113 

114 @deprecated("ManimGX's machinery: ManimGX preview calls it", category=None) 

115 def asked(self) -> str | None: 

116 """The scene the viewer asked for last, if they asked since (N, P: the next or the 

117 previous of the file's scenes).""" 

118 name = None 

119 while not self._asked.empty(): 

120 name = self._asked.get_nowait() 

121 return name 

122 

123 def wait(self, timeout: float | None = None) -> bool: 

124 """Wait until the window is closed, at most `timeout` seconds; whether it was.""" 

125 try: 

126 self._process.wait(timeout) 

127 except subprocess.TimeoutExpired: 

128 return False 

129 self._listening.join() # what it said before it closed, `failure` among it 

130 return True 

131 

132 def close(self) -> None: 

133 """Close the window.""" 

134 pipe = self._process.stdin 

135 if pipe is not None and not pipe.closed: 

136 with contextlib.suppress(OSError): 

137 pipe.close() # its end of the take: it closes 

138 if not self.wait(10): 

139 self._process.kill() 

140 self.wait() 

141 

142 def __enter__(self) -> Self: 

143 return self 

144 

145 def __exit__( 

146 self, 

147 kind: type[BaseException] | None, 

148 error: BaseException | None, 

149 trace: TracebackType | None, 

150 ) -> None: 

151 self.close() 

152 

153 def _listen(self) -> None: 

154 """What the window says, a line of JSON each, as it comes: a scene its viewer asks 

155 for, or why it failed; its end of the pipe closed once it has said all.""" 

156 assert self._process.stdout is not None 

157 with self._process.stdout as lines: 

158 for line in lines: 

159 try: 

160 said = json.loads(line) 

161 except ValueError: 

162 continue 

163 if not isinstance(said, dict): 

164 continue 

165 if isinstance(scene := said.get("scene"), str): 

166 self._asked.put(scene) 

167 if isinstance(failure := said.get("failure"), str): 

168 self.failure = failure 

169 

170 

171def _main() -> None: 

172 """The window's own process (`Window` starts it): the window, until it is closed.""" 

173 import signal 

174 

175 from manimgx.drawing.typesetting import FONTS 

176 

177 # Ctrl+C reaches every process of the terminal: the window's director closes it 

178 signal.signal(signal.SIGINT, signal.SIG_IGN) 

179 title, time = sys.argv[1], float(sys.argv[2]) 

180 try: 

181 _engine.window(title, time, list(FONTS)) 

182 except BaseException as failed: # a panic of the engine's too 

183 print(json.dumps({"failure": str(failed) or type(failed).__name__}), flush=True) 

184 sys.exit(1)