rendercanvas 2.6.3__tar.gz → 2.7.1__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.3 → rendercanvas-2.7.1}/PKG-INFO +39 -16
  2. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/README.md +29 -13
  3. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/pyproject.toml +23 -5
  4. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/_version.py +1 -1
  5. rendercanvas-2.7.1/rendercanvas/anywidget.py +412 -0
  6. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/auto.py +27 -38
  7. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/base.py +24 -11
  8. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/contexts/_fullscreen.py +3 -1
  9. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/contexts/bitmapcontext.py +8 -1
  10. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/contexts/wgpucontext.py +59 -37
  11. rendercanvas-2.7.1/rendercanvas/core/__init__.py +1 -0
  12. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/core/coreutils.py +16 -2
  13. rendercanvas-2.7.1/rendercanvas/core/encoders.py +138 -0
  14. rendercanvas-2.7.1/rendercanvas/core/renderview-afm.js +269 -0
  15. rendercanvas-2.7.1/rendercanvas/core/renderview-client.js +177 -0
  16. rendercanvas-2.7.1/rendercanvas/core/renderview-pyodide.js +62 -0
  17. rendercanvas-2.7.1/rendercanvas/core/renderview.css +112 -0
  18. rendercanvas-2.7.1/rendercanvas/core/renderview.js +941 -0
  19. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/core/scheduler.py +6 -1
  20. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/glfw.py +28 -15
  21. rendercanvas-2.7.1/rendercanvas/http.py +611 -0
  22. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/jupyter.py +22 -13
  23. rendercanvas-2.7.1/rendercanvas/pyodide.py +261 -0
  24. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/qt.py +4 -5
  25. rendercanvas-2.7.1/rendercanvas/terminal.py +552 -0
  26. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/utils/asyncadapter.py +3 -4
  27. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/utils/asyncs.py +2 -0
  28. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/wx.py +19 -7
  29. rendercanvas-2.6.3/rendercanvas/pyodide.py +0 -562
  30. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/LICENSE +0 -0
  31. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/__init__.py +0 -0
  32. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/__pyinstaller/__init__.py +0 -0
  33. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/__pyinstaller/conftest.py +0 -0
  34. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/__pyinstaller/hook-rendercanvas.py +0 -0
  35. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/__pyinstaller/test_rendercanvas.py +0 -0
  36. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/asyncio.py +0 -0
  37. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/contexts/__init__.py +0 -0
  38. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/contexts/basecontext.py +0 -0
  39. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/core/enums.py +0 -0
  40. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/core/events.py +0 -0
  41. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/core/loop.py +0 -0
  42. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/core/size.py +0 -0
  43. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/offscreen.py +0 -0
  44. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/pyqt5.py +0 -0
  45. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/pyqt6.py +0 -0
  46. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/pyside2.py +0 -0
  47. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/pyside6.py +0 -0
  48. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/raw.py +0 -0
  49. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/stub.py +0 -0
  50. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/trio.py +0 -0
  51. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/utils/__init__.py +0 -0
  52. {rendercanvas-2.6.3 → rendercanvas-2.7.1}/rendercanvas/utils/cube.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rendercanvas
3
- Version: 2.6.3
3
+ Version: 2.7.1
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,6 +45,8 @@ 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)
@@ -78,18 +85,24 @@ Providing a generic API for:
78
85
  * presenting rendered results as a bitmap ([`BitmapContext`](https://rendercanvas.readthedocs.io/stable/contexts.html#rendercanvas.contexts.BitmapContext)).
79
86
  * working with events that have standardized behavior.
80
87
 
81
- Implement that on top of a variety of backends:
88
+ The following backends are currently available:
82
89
 
83
- * Running on desktop with a light backend (glfw).
84
- * Running in the browser (with Pyodide or PyScript).
85
- * Running from a (Jupyter) notebook.
86
- * Embedding as a widget in a GUI library.
87
- * Qt
88
- * wx
89
- * In addition to the GUI libraries mentioned above, the following event loops are supported:
90
- * asyncio
91
- * trio
92
- * raw
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:
102
+
103
+ * `asyncio`
104
+ * `trio`
105
+ * `raw`
93
106
 
94
107
 
95
108
  ## Installation
@@ -171,14 +184,24 @@ See the [docs on async](https://rendercanvas.readthedocs.io/stable/start.html#as
171
184
  This code is distributed under the 2-clause BSD license.
172
185
 
173
186
 
174
- ## Developers
187
+ ## Contributing
188
+
189
+ See the [contribution guide](CONTRIBUTING.md).
190
+
191
+ ### Development install
175
192
 
176
193
  * Clone the repo.
177
194
  * Install `rendercanvas` and developer deps using `pip install -e .[dev]`.
195
+
196
+ ### Quick tips
197
+
178
198
  * Use `ruff format` to apply autoformatting.
179
199
  * Use `ruff check` to check for linting errors.
180
- * 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`.
181
200
  * Use `pytest tests` to run the tests.
182
201
  * Use `pytest examples` to run a subset of the examples.
183
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
+
184
207
 
@@ -34,18 +34,24 @@ Providing a generic API for:
34
34
  * presenting rendered results as a bitmap ([`BitmapContext`](https://rendercanvas.readthedocs.io/stable/contexts.html#rendercanvas.contexts.BitmapContext)).
35
35
  * working with events that have standardized behavior.
36
36
 
37
- Implement that on top of a variety of backends:
37
+ The following backends are currently available:
38
38
 
39
- * Running on desktop with a light backend (glfw).
40
- * Running in the browser (with Pyodide or PyScript).
41
- * Running from a (Jupyter) notebook.
42
- * Embedding as a widget in a GUI library.
43
- * Qt
44
- * wx
45
- * In addition to the GUI libraries mentioned above, the following event loops are supported:
46
- * asyncio
47
- * trio
48
- * raw
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:
51
+
52
+ * `asyncio`
53
+ * `trio`
54
+ * `raw`
49
55
 
50
56
 
51
57
  ## Installation
@@ -127,13 +133,23 @@ See the [docs on async](https://rendercanvas.readthedocs.io/stable/start.html#as
127
133
  This code is distributed under the 2-clause BSD license.
128
134
 
129
135
 
130
- ## Developers
136
+ ## Contributing
137
+
138
+ See the [contribution guide](CONTRIBUTING.md).
139
+
140
+ ### Development install
131
141
 
132
142
  * Clone the repo.
133
143
  * Install `rendercanvas` and developer deps using `pip install -e .[dev]`.
144
+
145
+ ### Quick tips
146
+
134
147
  * Use `ruff format` to apply autoformatting.
135
148
  * Use `ruff check` to check for linting errors.
136
- * 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`.
137
149
  * Use `pytest tests` to run the tests.
138
150
  * Use `pytest examples` to run a subset of the examples.
139
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.3"
25
+ __version__ = "2.7.1"
26
26
 
27
27
  # Set this to your library name
28
28
  project_name = "rendercanvas"
@@ -0,0 +1,412 @@
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
+
131
+ self._rfb_schedule_maybe_draw()
132
+
133
+ def _replace_snapshot(self, array):
134
+ pending_display = self._rfb_pending_snapshot_display
135
+ self._rfb_pending_snapshot_display = None
136
+
137
+ event = self._rfb_last_resize_event or {}
138
+ w = event.get("width", array.shape[1])
139
+ h = event.get("height", array.shape[0])
140
+
141
+ mimetype, data = encode_array(array, 70)
142
+ src = f"data:image/{mimetype};base64," + encodebytes(data).decode()
143
+ html = f"<img src='{src}' style='width:{w}px;height:{h}px;' />"
144
+
145
+ pending_display.update(HTML(html))
146
+
147
+ def _rfb_handle_msg(self, widget, content, buffers):
148
+ """Receive custom messages and filter our events."""
149
+ event_type = content.get("type")
150
+
151
+ if event_type is not None:
152
+ event = content
153
+
154
+ if event_type == "resize":
155
+ self._last_event = event
156
+ self._size_info.set_physical_size(
157
+ event["pwidth"], event["pheight"], event["ratio"]
158
+ )
159
+ elif event_type == "close":
160
+ self.close()
161
+ elif event_type in valid_event_types:
162
+ # Compatibility between new renderview event spec and current rendercanvas/pygfx events
163
+ event["event_type"] = event.pop("type")
164
+ event["time_stamp"] = event.pop("timestamp")
165
+ # Turn lists into tuples (js/json does not have tuples)
166
+ if "buttons" in event:
167
+ event["buttons"] = tuple(event["buttons"])
168
+ if "modifiers" in event:
169
+ event["modifiers"] = tuple(event["modifiers"])
170
+ self.submit_event(event)
171
+
172
+ def _rfb_schedule_maybe_draw(self, *args):
173
+ """Schedule _maybe_draw() to be called in a fresh event loop iteration."""
174
+ try:
175
+ loop = asyncio.get_running_loop()
176
+ except RuntimeError:
177
+ return
178
+ loop.call_soon(self._rfb_maybe_draw)
179
+
180
+ def _rfb_maybe_draw(self):
181
+ """Perform a draw, if we can and should."""
182
+ feedback = self._frame_feedback
183
+ # Update stats
184
+ self._rfb_update_stats(feedback)
185
+ # Determine whether we should perform a draw: a draw was requested, and
186
+ # the client is ready for a new frame, and the client widget is visible.
187
+ frames_in_flight = self._rfb_frame_index - feedback.get("index", 0)
188
+ should_draw = (
189
+ self._rfb_draw_requested
190
+ and frames_in_flight < self._max_buffered_frames
191
+ and self._has_visible_views
192
+ ) or self._rfb_pending_snapshot_display is not None
193
+
194
+ # Do the draw if we should.
195
+ if should_draw:
196
+ self._rfb_draw_requested = False
197
+ self._time_to_draw() # -> _rc_present_bitmap -> _rfb_send_frame
198
+
199
+ def _rfb_schedule_lossless_draw(self, array, delay=0.3):
200
+ self._rfb_cancel_lossless_draw()
201
+ loop = asyncio.get_running_loop()
202
+ handle = loop.call_later(delay, self._rfb_lossless_draw)
203
+ self._rfb_lossless_draw_info = array, handle
204
+
205
+ def _rfb_cancel_lossless_draw(self):
206
+ if self._rfb_lossless_draw_info:
207
+ _, handle = self._rfb_lossless_draw_info
208
+ self._rfb_lossless_draw_info = None
209
+ handle.cancel()
210
+
211
+ def _rfb_lossless_draw(self):
212
+ array, _ = self._rfb_lossless_draw_info
213
+ self._rfb_send_frame(array, True)
214
+
215
+ def _rfb_send_frame(self, array, is_lossless_redraw=False):
216
+ """Actually send a frame over to the client."""
217
+ # For considerations about performance,
218
+ # see https://github.com/vispy/jupyter_rfb/issues/3
219
+
220
+ quality = 100 if is_lossless_redraw else self._quality
221
+
222
+ self._rfb_frame_index += 1
223
+ timestamp = time.time()
224
+
225
+ # Turn array into a based64-encoded JPEG or PNG
226
+ t1 = time.perf_counter()
227
+ mimetype, data = encode_array(array, quality)
228
+ if self._use_websocket:
229
+ datas = [data]
230
+ data_b64 = None
231
+ else:
232
+ datas = []
233
+ data_b64 = f"data:{mimetype};base64," + encodebytes(data).decode()
234
+ t2 = time.perf_counter()
235
+
236
+ if "jpeg" in mimetype:
237
+ self._rfb_schedule_lossless_draw(array)
238
+ else:
239
+ self._rfb_cancel_lossless_draw()
240
+ # Issue png warning?
241
+ if quality < 100 and not CAN_JPEG and not self._rfb_warned_png:
242
+ self._rfb_warned_png = True
243
+ logger.warning(
244
+ "No JPEG encoder found, using PNG instead. Install simplejpeg for better performance."
245
+ )
246
+
247
+ if is_lossless_redraw:
248
+ # No stats, also not on the confirmation of this frame
249
+ self._rfb_last_confirmed_index = self._rfb_frame_index
250
+ else:
251
+ # Stats
252
+ self._rfb_stats["img_encoding_sum"] += t2 - t1
253
+ self._rfb_stats["sent_frames"] += 1
254
+ if self._rfb_stats["start_time"] <= 0: # Start measuring
255
+ self._rfb_stats["start_time"] = timestamp
256
+ self._rfb_last_confirmed_index = self._rfb_frame_index - 1
257
+
258
+ # Reload the output if we did not have a frame when the widget was first loaded
259
+ if self._rfb_pending_snapshot_display is not None:
260
+ self._replace_snapshot(array)
261
+
262
+ # Compose message and send
263
+ msg = dict(
264
+ type="framebufferdata",
265
+ mimetype=mimetype,
266
+ data_b64=data_b64,
267
+ index=self._rfb_frame_index,
268
+ timestamp=timestamp,
269
+ )
270
+ self.send(msg, datas)
271
+
272
+ # ----- related to stats
273
+
274
+ def reset_stats(self):
275
+ """Restart measuring statistics from the next sent frame."""
276
+ self._rfb_stats = {
277
+ "start_time": 0,
278
+ "last_time": 1,
279
+ "sent_frames": 0,
280
+ "confirmed_frames": 0,
281
+ "roundtrip_count": 0,
282
+ "roundtrip_sum": 0,
283
+ "delivery_sum": 0,
284
+ "img_encoding_sum": 0,
285
+ }
286
+
287
+ def get_stats(self):
288
+ """Get the current stats since the last time ``.reset_stats()`` was called.
289
+
290
+ Stats is a dict with the following fields:
291
+
292
+ * *sent_frames*: the number of frames sent.
293
+ * *confirmed_frames*: number of frames confirmed by the client.
294
+ * *roundtrip*: average time for processing a frame, including receiver confirmation.
295
+ * *delivery*: average time for processing a frame until it's received by the client.
296
+ This measure assumes that the clock of the server and client are precisely synced.
297
+ * *img_encoding*: the average time spent on encoding the array into an image.
298
+ * *b64_encoding*: the average time spent on base64 encoding the data.
299
+ * *fps*: the average FPS, measured from the first frame sent since ``.reset_stats()``
300
+ was called, until the last confirmed frame.
301
+ """
302
+ d = self._rfb_stats
303
+ roundtrip_count_div = d["roundtrip_count"] or 1
304
+ sent_frames_div = d["sent_frames"] or 1
305
+ fps_div = (d["last_time"] - d["start_time"]) or 0.001
306
+ return {
307
+ "sent_frames": d["sent_frames"],
308
+ "confirmed_frames": d["confirmed_frames"],
309
+ "roundtrip": d["roundtrip_sum"] / roundtrip_count_div,
310
+ "delivery": d["delivery_sum"] / roundtrip_count_div,
311
+ "img_encoding": d["img_encoding_sum"] / sent_frames_div,
312
+ "fps": d["confirmed_frames"] / fps_div,
313
+ }
314
+
315
+ def _rfb_update_stats(self, feedback):
316
+ """Update the stats when a new frame feedback has arrived."""
317
+ last_index = feedback.get("index", 0)
318
+ if last_index > self._rfb_last_confirmed_index:
319
+ timestamp = feedback["timestamp"]
320
+ nframes = last_index - self._rfb_last_confirmed_index
321
+ self._rfb_last_confirmed_index = last_index
322
+ self._rfb_stats["confirmed_frames"] += nframes
323
+ self._rfb_stats["roundtrip_count"] += 1
324
+ self._rfb_stats["roundtrip_sum"] += time.time() - timestamp
325
+ self._rfb_stats["delivery_sum"] += feedback["localtime"] - timestamp
326
+ self._rfb_stats["last_time"] = time.time()
327
+
328
+ # --- the API to be a rendercanvas backend
329
+
330
+ def _rc_gui_poll(self):
331
+ pass
332
+
333
+ def _rc_get_present_info(self, present_methods):
334
+ # Only allow simple format for now. srgb is assumed.
335
+ if "bitmap" in present_methods:
336
+ return {
337
+ "method": "bitmap",
338
+ "formats": ["rgba-u8"],
339
+ }
340
+ else:
341
+ return None # raises error
342
+
343
+ def _rc_request_draw(self):
344
+ # Technically, _maybe_draw() may not perform a draw if there are too
345
+ # many frames in-flight. But in this case, we'll eventually get
346
+ # new frame_feedback, which will then trigger a draw.
347
+ if not self._rfb_draw_requested:
348
+ self._rfb_draw_requested = True
349
+ self._rfb_cancel_lossless_draw()
350
+ self._rfb_schedule_maybe_draw()
351
+
352
+ def _rc_request_paint(self):
353
+ # We technically don't need to call _time_to_paint, because this backend only does bitmap mode.
354
+ # But in case the base backend will do something in _time_to_paint later, we behave nice.
355
+ loop = self._rc_canvas_group.get_loop()
356
+ loop.call_soon(self._time_to_paint)
357
+
358
+ def _rc_force_paint(self):
359
+ pass # works as-is via push_frame
360
+
361
+ def _rc_present_bitmap(self, *, data, format, **kwargs):
362
+ assert format == "rgba-u8"
363
+ self._rfb_send_frame(np.asarray(data))
364
+
365
+ def _rc_set_logical_size(self, width, height):
366
+ self._last_set_logical_size = width, height
367
+ self._css_width = f"{width}px"
368
+ self._css_height = f"{height}px"
369
+
370
+ def _rc_close(self):
371
+ anywidget.AnyWidget.close(self)
372
+ self._rfb_handle_msg(self, {"type": "close"}, [])
373
+ self._is_closed = True
374
+
375
+ def _rc_get_closed(self):
376
+ return self._is_closed
377
+
378
+ def _rc_set_title(self, title):
379
+ self._title = str(title)
380
+ self._has_titlebar = bool(title)
381
+
382
+ def _rc_set_cursor(self, cursor):
383
+ self._cursor = cursor
384
+
385
+ def set_css_width(self, css_width: str):
386
+ """Set the width of the canvas as a CSS string."""
387
+ self._css_width = css_width
388
+
389
+ def set_css_height(self, css_height: str):
390
+ """Set the height of the canvas as a CSS string."""
391
+ self._css_height = css_height
392
+
393
+ def set_resizable(self, resizable: bool):
394
+ """Set whether the canvas is manually resizable."""
395
+ self._resizable = resizable
396
+
397
+ def set_minimizable(self, minimizable: bool):
398
+ """Set whether the canvas is manually minimizable via a button in the titlebar.
399
+
400
+ If all views of the canvas are hidden (out of view or minimized), its rendering is paused,
401
+ saving CPU cycles and battery.
402
+ """
403
+ self._is_minimizable = minimizable
404
+
405
+ def set_closable(self, closable: bool):
406
+ """Set whether the canvas is manually closable via a button in the titlebar."""
407
+ self._is_closable = closable
408
+
409
+
410
+ # Make available under a common name
411
+ RenderCanvas = AnywidgetRenderCanvas
412
+ loop = loop