rendercanvas 2.6.2__tar.gz → 2.7.0__tar.gz

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.
Files changed (52) hide show
  1. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/PKG-INFO +41 -16
  2. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/README.md +31 -13
  3. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/pyproject.toml +23 -5
  4. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/_version.py +1 -1
  5. rendercanvas-2.7.0/rendercanvas/anywidget.py +410 -0
  6. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/auto.py +27 -38
  7. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/base.py +24 -11
  8. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/contexts/_fullscreen.py +3 -1
  9. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/contexts/bitmapcontext.py +8 -1
  10. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/contexts/wgpucontext.py +59 -37
  11. rendercanvas-2.7.0/rendercanvas/core/__init__.py +1 -0
  12. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/core/coreutils.py +16 -2
  13. rendercanvas-2.7.0/rendercanvas/core/encoders.py +138 -0
  14. rendercanvas-2.7.0/rendercanvas/core/renderview-afm.js +269 -0
  15. rendercanvas-2.7.0/rendercanvas/core/renderview-client.js +177 -0
  16. rendercanvas-2.7.0/rendercanvas/core/renderview-pyodide.js +62 -0
  17. rendercanvas-2.7.0/rendercanvas/core/renderview.css +112 -0
  18. rendercanvas-2.7.0/rendercanvas/core/renderview.js +939 -0
  19. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/core/scheduler.py +6 -1
  20. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/glfw.py +28 -15
  21. rendercanvas-2.7.0/rendercanvas/http.py +611 -0
  22. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/jupyter.py +22 -13
  23. rendercanvas-2.7.0/rendercanvas/pyodide.py +261 -0
  24. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/qt.py +4 -5
  25. rendercanvas-2.7.0/rendercanvas/terminal.py +552 -0
  26. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/utils/asyncadapter.py +3 -4
  27. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/utils/asyncs.py +2 -0
  28. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/wx.py +29 -10
  29. rendercanvas-2.6.2/rendercanvas/pyodide.py +0 -562
  30. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/LICENSE +0 -0
  31. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/__init__.py +0 -0
  32. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/__pyinstaller/__init__.py +0 -0
  33. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/__pyinstaller/conftest.py +0 -0
  34. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/__pyinstaller/hook-rendercanvas.py +0 -0
  35. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/__pyinstaller/test_rendercanvas.py +0 -0
  36. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/asyncio.py +0 -0
  37. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/contexts/__init__.py +0 -0
  38. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/contexts/basecontext.py +0 -0
  39. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/core/enums.py +0 -0
  40. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/core/events.py +0 -0
  41. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/core/loop.py +0 -0
  42. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/core/size.py +0 -0
  43. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/offscreen.py +0 -0
  44. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/pyqt5.py +0 -0
  45. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/pyqt6.py +0 -0
  46. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/pyside2.py +0 -0
  47. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/pyside6.py +0 -0
  48. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/raw.py +0 -0
  49. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/stub.py +0 -0
  50. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/trio.py +0 -0
  51. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/utils/__init__.py +0 -0
  52. {rendercanvas-2.6.2 → rendercanvas-2.7.0}/rendercanvas/utils/cube.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rendercanvas
3
- Version: 2.6.2
3
+ Version: 2.7.0
4
4
  Summary: One canvas API, multiple backends
5
5
  Keywords: canvas,rendering,graphics,wgpu,qt,wx,glfw,jupyter
6
6
  Author: Almar Klein, Korijn van Golen
@@ -13,8 +13,8 @@ Requires-Dist: flit ; extra == "docs"
13
13
  Requires-Dist: sphinx>7.2 ; extra == "docs"
14
14
  Requires-Dist: sphinx_rtd_theme ; extra == "docs"
15
15
  Requires-Dist: sphinx-gallery ; extra == "docs"
16
- Requires-Dist: numpy ; extra == "docs"
17
16
  Requires-Dist: wgpu ; extra == "docs"
17
+ Requires-Dist: blessed ; extra == "docs"
18
18
  Requires-Dist: flit ; extra == "examples"
19
19
  Requires-Dist: numpy ; extra == "examples"
20
20
  Requires-Dist: wgpu ; extra == "examples"
@@ -22,15 +22,20 @@ Requires-Dist: glfw ; extra == "examples"
22
22
  Requires-Dist: pyside6 ; extra == "examples"
23
23
  Requires-Dist: imageio ; extra == "examples"
24
24
  Requires-Dist: pytest ; extra == "examples"
25
+ Requires-Dist: blessed ; extra == "examples"
25
26
  Requires-Dist: glfw>=1.9 ; extra == "glfw"
26
27
  Requires-Dist: jupyter_rfb>=0.4.2 ; extra == "jupyter"
28
+ Requires-Dist: simplejpeg ; extra == "jupyter" and ( implementation_name != 'pypy')
27
29
  Requires-Dist: ruff ; extra == "lint"
28
30
  Requires-Dist: pre-commit ; extra == "lint"
31
+ Requires-Dist: anywidget ; extra == "notebook"
32
+ Requires-Dist: simplejpeg ; extra == "notebook" and ( implementation_name != 'pypy')
33
+ Requires-Dist: blessed ; extra == "terminal"
29
34
  Requires-Dist: pytest ; extra == "tests"
30
- Requires-Dist: numpy ; extra == "tests"
31
35
  Requires-Dist: wgpu ; extra == "tests"
32
36
  Requires-Dist: glfw ; extra == "tests"
33
37
  Requires-Dist: trio ; extra == "tests"
38
+ Requires-Dist: simplejpeg ; extra == "tests" and ( implementation_name != 'pypy')
34
39
  Project-URL: Documentation, https://rendercanvas.readthedocs.io
35
40
  Project-URL: Homepage, https://github.com/pygfx/rendercanvas
36
41
  Project-URL: Repository, https://github.com/pygfx/rendercanvas
@@ -40,12 +45,16 @@ Provides-Extra: examples
40
45
  Provides-Extra: glfw
41
46
  Provides-Extra: jupyter
42
47
  Provides-Extra: lint
48
+ Provides-Extra: notebook
49
+ Provides-Extra: terminal
43
50
  Provides-Extra: tests
44
51
 
45
52
  [![CI](https://github.com/pygfx/rendercanvas/workflows/CI/badge.svg)](https://github.com/pygfx/rendercanvas/actions)
46
53
  [![Documentation Status](https://readthedocs.org/projects/rendercanvas/badge/?version=stable)](https://rendercanvas.readthedocs.io)
47
54
  [![PyPI version](https://badge.fury.io/py/rendercanvas.svg)](https://badge.fury.io/py/rendercanvas)
48
55
  [![EffVer Versioning](https://img.shields.io/badge/version_scheme-EffVer-0097a7)](https://jacobtomlinson.dev/effver)
56
+ [![Zenodo badge](https://zenodo.org/badge/DOI/10.5281/zenodo.18922945.svg)](https://doi.org/10.5281/zenodo.18922945)
57
+
49
58
 
50
59
  <h1 align="center"><img src="https://github.com/user-attachments/assets/74ddfc1e-03ae-4965-afe9-8697ec4614b5" height="128"><br>rendercanvas</h1>
51
60
 
@@ -76,18 +85,24 @@ Providing a generic API for:
76
85
  * presenting rendered results as a bitmap ([`BitmapContext`](https://rendercanvas.readthedocs.io/stable/contexts.html#rendercanvas.contexts.BitmapContext)).
77
86
  * working with events that have standardized behavior.
78
87
 
79
- Implement that on top of a variety of backends:
88
+ The following backends are currently available:
89
+
90
+ * `auto` - automatically selects an appropriate backend.
91
+ * `glfw` - a native desktop window.
92
+ * `offscreen` - for offscreen rendering.
93
+ * `terminal` - to render in the terminal (e.g. over SSH).
94
+ * `qt` (`pyside6` / `pyside2` / `pyqt6` / `pyqt5`) - to embed a render canvas in a qt GUI.
95
+ * `wx` - to embed a render canvas in a wx GUI.
96
+ * `anywidget` - for notebooks like Jupyter, VSCode, and Marimo.
97
+ * `jupyter` - previous backend for notebooks that uses jupyter_rfb.
98
+ * `http` - for server side rendering, display in a browser connected via the internet.
99
+ * `pyodide` - to run in the browser with Pyodide or PyScript.
100
+
101
+ In addition to the GUI libraries mentioned above, the following event loops are supported:
80
102
 
81
- * Running on desktop with a light backend (glfw).
82
- * Running in the browser (with Pyodide or PyScript).
83
- * Running from a (Jupyter) notebook.
84
- * Embedding as a widget in a GUI library.
85
- * Qt
86
- * wx
87
- * In addition to the GUI libraries mentioned above, the following event loops are supported:
88
- * asyncio
89
- * trio
90
- * raw
103
+ * `asyncio`
104
+ * `trio`
105
+ * `raw`
91
106
 
92
107
 
93
108
  ## Installation
@@ -169,14 +184,24 @@ See the [docs on async](https://rendercanvas.readthedocs.io/stable/start.html#as
169
184
  This code is distributed under the 2-clause BSD license.
170
185
 
171
186
 
172
- ## Developers
187
+ ## Contributing
188
+
189
+ See the [contribution guide](CONTRIBUTING.md).
190
+
191
+ ### Development install
173
192
 
174
193
  * Clone the repo.
175
194
  * Install `rendercanvas` and developer deps using `pip install -e .[dev]`.
195
+
196
+ ### Quick tips
197
+
176
198
  * Use `ruff format` to apply autoformatting.
177
199
  * Use `ruff check` to check for linting errors.
178
- * Optionally, if you install [pre-commit](https://github.com/pre-commit/pre-commit/) hooks with `pre-commit install`, lint fixes and formatting will be automatically applied on `git commit`.
179
200
  * Use `pytest tests` to run the tests.
180
201
  * Use `pytest examples` to run a subset of the examples.
181
202
 
203
+ ### Code of Conduct
204
+
205
+ This repository follows the [PyGfx Code of Conduct](https://github.com/pygfx/pygfx/blob/main/CODE_OF_CONDUCT.md)
206
+
182
207
 
@@ -2,6 +2,8 @@
2
2
  [![Documentation Status](https://readthedocs.org/projects/rendercanvas/badge/?version=stable)](https://rendercanvas.readthedocs.io)
3
3
  [![PyPI version](https://badge.fury.io/py/rendercanvas.svg)](https://badge.fury.io/py/rendercanvas)
4
4
  [![EffVer Versioning](https://img.shields.io/badge/version_scheme-EffVer-0097a7)](https://jacobtomlinson.dev/effver)
5
+ [![Zenodo badge](https://zenodo.org/badge/DOI/10.5281/zenodo.18922945.svg)](https://doi.org/10.5281/zenodo.18922945)
6
+
5
7
 
6
8
  <h1 align="center"><img src="https://github.com/user-attachments/assets/74ddfc1e-03ae-4965-afe9-8697ec4614b5" height="128"><br>rendercanvas</h1>
7
9
 
@@ -32,18 +34,24 @@ Providing a generic API for:
32
34
  * presenting rendered results as a bitmap ([`BitmapContext`](https://rendercanvas.readthedocs.io/stable/contexts.html#rendercanvas.contexts.BitmapContext)).
33
35
  * working with events that have standardized behavior.
34
36
 
35
- Implement that on top of a variety of backends:
37
+ The following backends are currently available:
38
+
39
+ * `auto` - automatically selects an appropriate backend.
40
+ * `glfw` - a native desktop window.
41
+ * `offscreen` - for offscreen rendering.
42
+ * `terminal` - to render in the terminal (e.g. over SSH).
43
+ * `qt` (`pyside6` / `pyside2` / `pyqt6` / `pyqt5`) - to embed a render canvas in a qt GUI.
44
+ * `wx` - to embed a render canvas in a wx GUI.
45
+ * `anywidget` - for notebooks like Jupyter, VSCode, and Marimo.
46
+ * `jupyter` - previous backend for notebooks that uses jupyter_rfb.
47
+ * `http` - for server side rendering, display in a browser connected via the internet.
48
+ * `pyodide` - to run in the browser with Pyodide or PyScript.
49
+
50
+ In addition to the GUI libraries mentioned above, the following event loops are supported:
36
51
 
37
- * Running on desktop with a light backend (glfw).
38
- * Running in the browser (with Pyodide or PyScript).
39
- * Running from a (Jupyter) notebook.
40
- * Embedding as a widget in a GUI library.
41
- * Qt
42
- * wx
43
- * In addition to the GUI libraries mentioned above, the following event loops are supported:
44
- * asyncio
45
- * trio
46
- * raw
52
+ * `asyncio`
53
+ * `trio`
54
+ * `raw`
47
55
 
48
56
 
49
57
  ## Installation
@@ -125,13 +133,23 @@ See the [docs on async](https://rendercanvas.readthedocs.io/stable/start.html#as
125
133
  This code is distributed under the 2-clause BSD license.
126
134
 
127
135
 
128
- ## Developers
136
+ ## Contributing
137
+
138
+ See the [contribution guide](CONTRIBUTING.md).
139
+
140
+ ### Development install
129
141
 
130
142
  * Clone the repo.
131
143
  * Install `rendercanvas` and developer deps using `pip install -e .[dev]`.
144
+
145
+ ### Quick tips
146
+
132
147
  * Use `ruff format` to apply autoformatting.
133
148
  * Use `ruff check` to check for linting errors.
134
- * Optionally, if you install [pre-commit](https://github.com/pre-commit/pre-commit/) hooks with `pre-commit install`, lint fixes and formatting will be automatically applied on `git commit`.
135
149
  * Use `pytest tests` to run the tests.
136
150
  * Use `pytest examples` to run a subset of the examples.
137
151
 
152
+ ### Code of Conduct
153
+
154
+ This repository follows the [PyGfx Code of Conduct](https://github.com/pygfx/pygfx/blob/main/CODE_OF_CONDUCT.md)
155
+
@@ -18,23 +18,41 @@ keywords = [
18
18
  "jupyter",
19
19
  ]
20
20
  requires-python = ">= 3.10"
21
- dependencies = ['numpy'] # Numpy is the only hard dependency
21
+ dependencies = ["numpy"] # Numpy is the only hard dependency
22
+
22
23
  [project.optional-dependencies]
23
24
  # For users
24
- jupyter = ["jupyter_rfb>=0.4.2"]
25
+ jupyter = ["jupyter_rfb>=0.4.2", "simplejpeg; implementation_name != 'pypy'"]
26
+ notebook = ["anywidget", "simplejpeg; implementation_name != 'pypy'"]
25
27
  glfw = ["glfw>=1.9"]
28
+ terminal = ["blessed"]
26
29
  # For devs / ci
27
30
  lint = ["ruff", "pre-commit"]
28
- examples = ["flit", "numpy", "wgpu", "glfw", "pyside6", "imageio", "pytest"]
31
+ examples = [
32
+ "flit",
33
+ "numpy",
34
+ "wgpu",
35
+ "glfw",
36
+ "pyside6",
37
+ "imageio",
38
+ "pytest",
39
+ "blessed",
40
+ ]
29
41
  docs = [
30
42
  "flit",
31
43
  "sphinx>7.2",
32
44
  "sphinx_rtd_theme",
33
45
  "sphinx-gallery",
34
- "numpy",
35
46
  "wgpu",
47
+ "blessed",
48
+ ]
49
+ tests = [
50
+ "pytest",
51
+ "wgpu",
52
+ "glfw",
53
+ "trio",
54
+ "simplejpeg; implementation_name != 'pypy'",
36
55
  ]
37
- tests = ["pytest", "numpy", "wgpu", "glfw", "trio"]
38
56
  dev = ["rendercanvas[lint,tests,examples,docs]"]
39
57
 
40
58
  [project.entry-points."pyinstaller40"]
@@ -22,7 +22,7 @@ from pathlib import Path
22
22
 
23
23
  # This is the base version number, to be bumped before each release.
24
24
  # The build system detects this definition when building a distribution.
25
- __version__ = "2.6.2"
25
+ __version__ = "2.7.0"
26
26
 
27
27
  # Set this to your library name
28
28
  project_name = "rendercanvas"
@@ -0,0 +1,410 @@
1
+ """
2
+ A backend based on anywidget, supporting canvases inside a large variety of notebooks and similar browser-like environments.
3
+ """
4
+
5
+ __all__ = ["AnywidgetRenderCanvas", "RenderCanvas", "loop"]
6
+
7
+ import time
8
+ import asyncio
9
+ from base64 import encodebytes
10
+ from importlib.resources import files as resource_files
11
+
12
+ from .base import BaseCanvasGroup, BaseRenderCanvas, logger
13
+ from .asyncio import loop
14
+ from .core.encoders import encode_array, CAN_JPEG
15
+ from .core.events import valid_event_types
16
+
17
+ import numpy as np
18
+ import anywidget
19
+ from IPython.display import display, HTML
20
+ from traitlets import Bool, Dict, Int, Unicode
21
+
22
+
23
+ def _load_js_and_css():
24
+ js = ""
25
+ for fname in ["renderview.js", "renderview-afm.js"]:
26
+ js_path = resource_files("rendercanvas.core").joinpath(fname)
27
+ js += js_path.read_text() + "\n\n"
28
+
29
+ css_path = resource_files("rendercanvas.core").joinpath("renderview.css")
30
+
31
+ return js, css_path.read_text()
32
+
33
+
34
+ JS, CSS = _load_js_and_css()
35
+
36
+
37
+ class AnywidgetCanvasGroup(BaseCanvasGroup):
38
+ pass
39
+
40
+
41
+ class AnywidgetRenderCanvas(BaseRenderCanvas, anywidget.AnyWidget):
42
+ """An anywidget canvas to use in notebooks (e.g. jupyter, marimo, VSCode, etc.).
43
+
44
+ This is an AnyWidget subclass, so you can easily combine it with other widgets.
45
+ """
46
+
47
+ # This class uses some '_rfb_' prefixes to avoid name clashes with super and sub classes.
48
+ # This specific prefix was inherited from jupyter_rfb, and we decided to keep it as is.
49
+
50
+ _rc_canvas_group = AnywidgetCanvasGroup(loop)
51
+
52
+ _esm = JS
53
+ _css = CSS
54
+
55
+ # Client -> server
56
+ _frame_feedback = Dict({}).tag(sync=True)
57
+ _has_visible_views = Bool(False).tag(sync=True)
58
+ # Server -> client
59
+ _css_width = Unicode("500px").tag(sync=True)
60
+ _css_height = Unicode("300px").tag(sync=True)
61
+ _resizable = Bool(True).tag(sync=True)
62
+ _is_minimizable = Bool(False).tag(sync=True)
63
+ _is_closable = Bool(False).tag(sync=True)
64
+ _has_titlebar = Bool(False).tag(sync=True)
65
+ _title = Unicode("").tag(sync=True)
66
+ _cursor = Unicode("default").tag(sync=True)
67
+ # Server only
68
+ _max_buffered_frames = Int(2, min=1)
69
+ _quality = Int(80, min=1, max=100)
70
+
71
+ def __init__(self, *args, **kwargs):
72
+ # This backend's default title is empty
73
+ kwargs["title"] = kwargs.get("title", "")
74
+
75
+ super().__init__(*args, **kwargs)
76
+
77
+ self._is_closed = False
78
+
79
+ self._rfb_draw_requested = False
80
+ self._rfb_frame_index = 0
81
+ self._rfb_last_confirmed_index = 0
82
+ self._rfb_warned_png = False
83
+ self._rfb_lossless_draw_info = None
84
+ self._rfb_last_resize_event = None
85
+ self._rfb_pending_snapshot_display = None
86
+
87
+ self._last_set_logical_size = 100, 100
88
+ self._use_websocket = True # Could be a prop, private for now
89
+
90
+ self.reset_stats()
91
+ self.on_msg(self._rfb_handle_msg)
92
+ self.observe(
93
+ self._rfb_schedule_maybe_draw,
94
+ names=["_frame_feedback", "_has_visible_views"],
95
+ )
96
+
97
+ # Set size, title, etc.
98
+ self._final_canvas_init()
99
+
100
+ def snapshot(self, *, pixel_ratio=None):
101
+ """Render a frame and include the resulting image in the output.
102
+
103
+ An initial placeholder output is produced, which is replaced by an html
104
+ ``<img>`` as soon as the next frame is rendered.
105
+
106
+ If the widget is not displayed yet, a resize event is emitted to mimic a widget
107
+ size. The ``pixel_ratio`` argument is then used to calculate the physical size.
108
+ """
109
+ if self._rfb_last_resize_event is None:
110
+ w, h = self._last_set_logical_size
111
+ r = float(pixel_ratio) if pixel_ratio is not None else 1.0
112
+ pw, ph = int(w * r), (h * r)
113
+ event = {
114
+ "type": "resize",
115
+ "width": pw / r,
116
+ "height": ph / r,
117
+ "pwidth": pw,
118
+ "pheight": ph,
119
+ "ratio": r,
120
+ "timestamp": 0,
121
+ }
122
+ self._rfb_handle_msg(self, event, [])
123
+
124
+ self._rfb_pending_snapshot_display = display(
125
+ HTML(
126
+ "<div style='display: inline-block; padding: 5px; border-radius: 5px; background:#ddd; color:#000'>pending screenshot ...</span>"
127
+ ),
128
+ display_id=True,
129
+ )
130
+ self.request_draw()
131
+
132
+ def _replace_snapshot(self, array):
133
+ pending_display = self._rfb_pending_snapshot_display
134
+ self._rfb_pending_snapshot_display = None
135
+
136
+ event = self._rfb_last_resize_event or {}
137
+ w = event.get("width", array.shape[1])
138
+ h = event.get("height", array.shape[0])
139
+
140
+ mimetype, data = encode_array(array, 70)
141
+ src = f"data:image/{mimetype};base64," + encodebytes(data).decode()
142
+ html = f"<img src='{src}' style='width:{w}px;height:{h}px;' />"
143
+
144
+ pending_display.update(HTML(html))
145
+
146
+ def _rfb_handle_msg(self, widget, content, buffers):
147
+ """Receive custom messages and filter our events."""
148
+ event_type = content.get("type")
149
+
150
+ if event_type is not None:
151
+ event = content
152
+
153
+ if event_type == "resize":
154
+ self._last_event = event
155
+ self._size_info.set_physical_size(
156
+ event["pwidth"], event["pheight"], event["ratio"]
157
+ )
158
+ elif event_type == "close":
159
+ self.close()
160
+ elif event_type in valid_event_types:
161
+ # Compatibility between new renderview event spec and current rendercanvas/pygfx events
162
+ event["event_type"] = event.pop("type")
163
+ event["time_stamp"] = event.pop("timestamp")
164
+ # Turn lists into tuples (js/json does not have tuples)
165
+ if "buttons" in event:
166
+ event["buttons"] = tuple(event["buttons"])
167
+ if "modifiers" in event:
168
+ event["modifiers"] = tuple(event["modifiers"])
169
+ self.submit_event(event)
170
+
171
+ def _rfb_schedule_maybe_draw(self, *args):
172
+ """Schedule _maybe_draw() to be called in a fresh event loop iteration."""
173
+ try:
174
+ loop = asyncio.get_running_loop()
175
+ except RuntimeError:
176
+ return
177
+ loop.call_soon(self._rfb_maybe_draw)
178
+
179
+ def _rfb_maybe_draw(self):
180
+ """Perform a draw, if we can and should."""
181
+ feedback = self._frame_feedback
182
+ # Update stats
183
+ self._rfb_update_stats(feedback)
184
+ # Determine whether we should perform a draw: a draw was requested, and
185
+ # the client is ready for a new frame, and the client widget is visible.
186
+ frames_in_flight = self._rfb_frame_index - feedback.get("index", 0)
187
+ should_draw = (
188
+ self._rfb_draw_requested
189
+ and frames_in_flight < self._max_buffered_frames
190
+ and (self._has_visible_views or self._rfb_pending_snapshot_display)
191
+ )
192
+ # Do the draw if we should.
193
+ if should_draw:
194
+ self._rfb_draw_requested = False
195
+ self._time_to_draw() # -> _rc_present_bitmap -> _rfb_send_frame
196
+
197
+ def _rfb_schedule_lossless_draw(self, array, delay=0.3):
198
+ self._rfb_cancel_lossless_draw()
199
+ loop = asyncio.get_running_loop()
200
+ handle = loop.call_later(delay, self._rfb_lossless_draw)
201
+ self._rfb_lossless_draw_info = array, handle
202
+
203
+ def _rfb_cancel_lossless_draw(self):
204
+ if self._rfb_lossless_draw_info:
205
+ _, handle = self._rfb_lossless_draw_info
206
+ self._rfb_lossless_draw_info = None
207
+ handle.cancel()
208
+
209
+ def _rfb_lossless_draw(self):
210
+ array, _ = self._rfb_lossless_draw_info
211
+ self._rfb_send_frame(array, True)
212
+
213
+ def _rfb_send_frame(self, array, is_lossless_redraw=False):
214
+ """Actually send a frame over to the client."""
215
+ # For considerations about performance,
216
+ # see https://github.com/vispy/jupyter_rfb/issues/3
217
+
218
+ quality = 100 if is_lossless_redraw else self._quality
219
+
220
+ self._rfb_frame_index += 1
221
+ timestamp = time.time()
222
+
223
+ # Turn array into a based64-encoded JPEG or PNG
224
+ t1 = time.perf_counter()
225
+ mimetype, data = encode_array(array, quality)
226
+ if self._use_websocket:
227
+ datas = [data]
228
+ data_b64 = None
229
+ else:
230
+ datas = []
231
+ data_b64 = f"data:{mimetype};base64," + encodebytes(data).decode()
232
+ t2 = time.perf_counter()
233
+
234
+ if "jpeg" in mimetype:
235
+ self._rfb_schedule_lossless_draw(array)
236
+ else:
237
+ self._rfb_cancel_lossless_draw()
238
+ # Issue png warning?
239
+ if quality < 100 and not CAN_JPEG and not self._rfb_warned_png:
240
+ self._rfb_warned_png = True
241
+ logger.warning(
242
+ "No JPEG encoder found, using PNG instead. Install simplejpeg for better performance."
243
+ )
244
+
245
+ if is_lossless_redraw:
246
+ # No stats, also not on the confirmation of this frame
247
+ self._rfb_last_confirmed_index = self._rfb_frame_index
248
+ else:
249
+ # Stats
250
+ self._rfb_stats["img_encoding_sum"] += t2 - t1
251
+ self._rfb_stats["sent_frames"] += 1
252
+ if self._rfb_stats["start_time"] <= 0: # Start measuring
253
+ self._rfb_stats["start_time"] = timestamp
254
+ self._rfb_last_confirmed_index = self._rfb_frame_index - 1
255
+
256
+ # Reload the output if we did not have a frame when the widget was first loaded
257
+ if self._rfb_pending_snapshot_display is not None:
258
+ self._replace_snapshot(array)
259
+
260
+ # Compose message and send
261
+ msg = dict(
262
+ type="framebufferdata",
263
+ mimetype=mimetype,
264
+ data_b64=data_b64,
265
+ index=self._rfb_frame_index,
266
+ timestamp=timestamp,
267
+ )
268
+ self.send(msg, datas)
269
+
270
+ # ----- related to stats
271
+
272
+ def reset_stats(self):
273
+ """Restart measuring statistics from the next sent frame."""
274
+ self._rfb_stats = {
275
+ "start_time": 0,
276
+ "last_time": 1,
277
+ "sent_frames": 0,
278
+ "confirmed_frames": 0,
279
+ "roundtrip_count": 0,
280
+ "roundtrip_sum": 0,
281
+ "delivery_sum": 0,
282
+ "img_encoding_sum": 0,
283
+ }
284
+
285
+ def get_stats(self):
286
+ """Get the current stats since the last time ``.reset_stats()`` was called.
287
+
288
+ Stats is a dict with the following fields:
289
+
290
+ * *sent_frames*: the number of frames sent.
291
+ * *confirmed_frames*: number of frames confirmed by the client.
292
+ * *roundtrip*: average time for processing a frame, including receiver confirmation.
293
+ * *delivery*: average time for processing a frame until it's received by the client.
294
+ This measure assumes that the clock of the server and client are precisely synced.
295
+ * *img_encoding*: the average time spent on encoding the array into an image.
296
+ * *b64_encoding*: the average time spent on base64 encoding the data.
297
+ * *fps*: the average FPS, measured from the first frame sent since ``.reset_stats()``
298
+ was called, until the last confirmed frame.
299
+ """
300
+ d = self._rfb_stats
301
+ roundtrip_count_div = d["roundtrip_count"] or 1
302
+ sent_frames_div = d["sent_frames"] or 1
303
+ fps_div = (d["last_time"] - d["start_time"]) or 0.001
304
+ return {
305
+ "sent_frames": d["sent_frames"],
306
+ "confirmed_frames": d["confirmed_frames"],
307
+ "roundtrip": d["roundtrip_sum"] / roundtrip_count_div,
308
+ "delivery": d["delivery_sum"] / roundtrip_count_div,
309
+ "img_encoding": d["img_encoding_sum"] / sent_frames_div,
310
+ "fps": d["confirmed_frames"] / fps_div,
311
+ }
312
+
313
+ def _rfb_update_stats(self, feedback):
314
+ """Update the stats when a new frame feedback has arrived."""
315
+ last_index = feedback.get("index", 0)
316
+ if last_index > self._rfb_last_confirmed_index:
317
+ timestamp = feedback["timestamp"]
318
+ nframes = last_index - self._rfb_last_confirmed_index
319
+ self._rfb_last_confirmed_index = last_index
320
+ self._rfb_stats["confirmed_frames"] += nframes
321
+ self._rfb_stats["roundtrip_count"] += 1
322
+ self._rfb_stats["roundtrip_sum"] += time.time() - timestamp
323
+ self._rfb_stats["delivery_sum"] += feedback["localtime"] - timestamp
324
+ self._rfb_stats["last_time"] = time.time()
325
+
326
+ # --- the API to be a rendercanvas backend
327
+
328
+ def _rc_gui_poll(self):
329
+ pass
330
+
331
+ def _rc_get_present_info(self, present_methods):
332
+ # Only allow simple format for now. srgb is assumed.
333
+ if "bitmap" in present_methods:
334
+ return {
335
+ "method": "bitmap",
336
+ "formats": ["rgba-u8"],
337
+ }
338
+ else:
339
+ return None # raises error
340
+
341
+ def _rc_request_draw(self):
342
+ # Technically, _maybe_draw() may not perform a draw if there are too
343
+ # many frames in-flight. But in this case, we'll eventually get
344
+ # new frame_feedback, which will then trigger a draw.
345
+ if not self._rfb_draw_requested:
346
+ self._rfb_draw_requested = True
347
+ self._rfb_cancel_lossless_draw()
348
+ self._rfb_schedule_maybe_draw()
349
+
350
+ def _rc_request_paint(self):
351
+ # We technically don't need to call _time_to_paint, because this backend only does bitmap mode.
352
+ # But in case the base backend will do something in _time_to_paint later, we behave nice.
353
+ loop = self._rc_canvas_group.get_loop()
354
+ loop.call_soon(self._time_to_paint)
355
+
356
+ def _rc_force_paint(self):
357
+ pass # works as-is via push_frame
358
+
359
+ def _rc_present_bitmap(self, *, data, format, **kwargs):
360
+ assert format == "rgba-u8"
361
+ self._rfb_send_frame(np.asarray(data))
362
+
363
+ def _rc_set_logical_size(self, width, height):
364
+ self._last_set_logical_size = width, height
365
+ self._css_width = f"{width}px"
366
+ self._css_height = f"{height}px"
367
+
368
+ def _rc_close(self):
369
+ anywidget.AnyWidget.close(self)
370
+ self._rfb_handle_msg(self, {"type": "close"}, [])
371
+ self._is_closed = True
372
+
373
+ def _rc_get_closed(self):
374
+ return self._is_closed
375
+
376
+ def _rc_set_title(self, title):
377
+ self._title = str(title)
378
+ self._has_titlebar = bool(title)
379
+
380
+ def _rc_set_cursor(self, cursor):
381
+ self._cursor = cursor
382
+
383
+ def set_css_width(self, css_width: str):
384
+ """Set the width of the canvas as a CSS string."""
385
+ self._css_width = css_width
386
+
387
+ def set_css_height(self, css_height: str):
388
+ """Set the height of the canvas as a CSS string."""
389
+ self._css_height = css_height
390
+
391
+ def set_resizable(self, resizable: bool):
392
+ """Set whether the canvas is manually resizable."""
393
+ self._resizable = resizable
394
+
395
+ def set_minimizable(self, minimizable: bool):
396
+ """Set whether the canvas is manually minimizable via a button in the titlebar.
397
+
398
+ If all views of the canvas are hidden (out of view or minimized), its rendering is paused,
399
+ saving CPU cycles and battery.
400
+ """
401
+ self._is_minimizable = minimizable
402
+
403
+ def set_closable(self, closable: bool):
404
+ """Set whether the canvas is manually closable via a button in the titlebar."""
405
+ self._is_closable = closable
406
+
407
+
408
+ # Make available under a common name
409
+ RenderCanvas = AnywidgetRenderCanvas
410
+ loop = loop