API
These are the base classes that make up the rendercanvas API:
The
BaseRenderCanvas
represents the main API.The
BaseLoop
provides functionality to work with the event-loop in a generic way.The
EventType
specifies the different types of events that can be connected to withcanvas.add_event_handler()
.
- class rendercanvas.BaseRenderCanvas(*args, size=(640, 480), title='$backend', update_mode='ondemand', min_fps=1.0, max_fps=30.0, vsync=True, present_method=None, **kwargs)
The base canvas class.
This base class defines a uniform canvas API so render systems can use code that is portable accross multiple GUI libraries and canvas targets. The scheduling mechanics are generic, even though they run on different backend event systems.
- Parameters:
size (tuple) – the logical size (width, height) of the canvas.
title (str) – The title of the canvas. Can use ‘$backend’ to show the RenderCanvas class name, and ‘$fps’ to show the fps.
update_mode (EventType) – The mode for scheduling draws and events. Default ‘ondemand’.
min_fps (float) – A minimal frames-per-second to use when the
update_mode
is ‘ondemand’. The default is 1: even without draws requested, it still draws every second.max_fps (float) – A maximal frames-per-second to use when the
update_mode
is ‘ondemand’ or ‘continuous’. The default is 30, which is usually enough.vsync (bool) – Whether to sync the draw with the monitor update. Helps against screen tearing, but can reduce fps. Default True.
present_method (str | None) – Override the method to present the rendered result. Can be set to e.g. ‘screen’ or ‘bitmap’. Default None (auto-select).
- classmethod select_loop(loop)
Select the loop to run newly created canvases with. Can only be called when there are no live canvases of this class.
- get_physical_size()
Get the physical size of the canvas in integer pixels.
- get_context(context_type)
Get a context object that can be used to render to this canvas.
The context takes care of presenting the rendered result to the canvas. Different types of contexts are available:
“wgpu”: get a
WgpuCanvasContext
provided by thewgpu
library.“bitmap”: get a
BitmapRenderingContext
provided by therendercanvas
library.“another.module”: other libraries may provide contexts too. We’ve only listed the ones we know of.
“your.module:ContextClass”: Explicit name.
Later calls to this method, with the same context_type argument, will return the same context instance as was returned the first time the method was invoked. It is not possible to get a different context object once the first one has been created.
- add_event_handler(*args, **kwargs)
Register an event handler to receive events.
- Parameters:
callback (callable) – The event handler. Must accept a single event argument. Can be a plain function or a coroutine function. If you use async callbacks, see Async for the limitations.
*types (list of strings) – A list of event types.
order (float) – Set callback priority order. Callbacks with lower priorities are called first. Default is 0. When an event is emitted, callbacks with the same priority are called in the order that they were added.
For the available events, see https://jupyter-rfb.readthedocs.io/en/stable/events.html.
The callback is stored, so it can be a lambda or closure. This also means that if a method is given, a reference to the object is held, which may cause circular references or prevent the Python GC from destroying that object.
Example:
def my_handler(event): print(event) canvas.add_event_handler(my_handler, "pointer_up", "pointer_down")
Can also be used as a decorator:
@canvas.add_event_handler("pointer_up", "pointer_down") def my_handler(event): print(event)
Catch ‘m all:
canvas.add_event_handler(my_handler, "*")
- remove_event_handler(*args, **kwargs)
Unregister an event handler.
- Parameters:
callback (callable) – The event handler.
*types (list of strings) – A list of event types.
- submit_event(event)
Submit an event.
Events are emitted later by the scheduler.
- request_draw(draw_function=None)
Schedule a new draw event.
This function does not perform a draw directly, but schedules a draw at a suitable moment in time. At that time the draw function is called, and the resulting rendered image is presented to screen.
Only affects drawing with schedule-mode ‘ondemand’.
- Parameters:
draw_function (callable or None) – The function to set as the new draw function. If not given or None, the last set draw function is used.
- force_draw()
Perform a draw right now.
In most cases you want to use
request_draw()
. If you find yourself using this, consider using a timer. Nevertheless, sometimes you just want to force a draw right now.
- get_logical_size()
Get the logical size (width, height) in float pixels.
- get_pixel_ratio()
Get the float ratio between logical and physical pixels.
- close()
Close the canvas.
- get_closed()
Get whether the window is closed.
- set_logical_size(width, height)
Set the window size (in logical pixels).
- set_title(title)
Set the window title.
The words “$backend”, “$loop”, and “$fps” can be used as variables that are filled in with the corresponding values.
- class rendercanvas.BaseLoop
The base class for an event-loop object.
Canvas backends can implement their own loop subclass (like qt and wx do), but a canvas backend can also rely on one of muliple loop implementations (like glfw running on asyncio or trio).
The lifecycle states of a loop are:
off (0): the initial state, the subclass should probably not even import dependencies yet.
ready (1): the first canvas is created,
_rc_init()
is called to get the loop ready for running.active (2): the loop is active, but not running via our entrypoints.
active (3): the loop is inter-active in e.g. an IDE.
running (4): the loop is running via
_rc_run()
or_rc_run_async()
.
Notes:
The loop goes back to the “off” state after all canvases are closed.
Stopping the loop (via
.stop()
) closes the canvases, which will then stop the loop.From there it can go back to the ready state (which would call
_rc_init()
again).In backends like Qt, the native loop can be started without us knowing: state “active”.
In interactive settings like an IDE that runs an syncio or Qt loop, the loop can become “active” as soon as the first canvas is created.
- get_canvases()
Get a list of currently active (not-closed) canvases.
- add_task(async_func, *args, name='unnamed')
Run an async function in the event-loop.
All tasks are stopped when the loop stops. See Async for the limitations of async code in rendercanvas.
- call_soon(callback, *args)
Arrange for a callback to be called as soon as possible.
The callback will be called in the next iteration of the event-loop, but other pending events/callbacks may be handled first. Returns None.
- call_later(delay, callback, *args)
Arrange for a callback to be called after the given delay (in seconds).
- run()
Enter the main loop.
This provides a generic API to start the loop. When building an application (e.g. with Qt) its fine to start the loop in the normal way.
This call usually blocks, but it can also return immediately, e.g. when there are no canvases, or when the loop is already active (e.g. interactve via IDE).
- async run_async()
“Alternative to
run()
, to enter the mainloop from a running async framework.Only supported by the asyncio and trio loops.
- stop()
Close all windows and stop the currently running event-loop.
If the loop is active but not running via our
run()
method, the loop moves back to its off-state, but the underlying loop is not stopped.
- class rendercanvas.EventType
The EventType enum specifies the possible events for a RenderCanvas.
This includes the events from the jupyter_rfb event spec (see https://jupyter-rfb.readthedocs.io/en/stable/events.html) plus some rendercanvas-specific events.
- resize = 'resize'
The canvas has changed size. Has ‘width’ and ‘height’ in logical pixels, ‘pixel_ratio’.
- close = 'close'
The canvas is closed. No additional fields.
- pointer_down = 'pointer_down'
The pointing device is pressed down. Has ‘x’, ‘y’, ‘button’, ‘butons’, ‘modifiers’, ‘ntouches’, ‘touches’.
- pointer_up = 'pointer_up'
The pointing device is released. Same fields as pointer_down.
- pointer_move = 'pointer_move'
The pointing device is moved. Same fields as pointer_down.
- double_click = 'double_click'
A double-click / long-tap. This event looks like a pointer event, but without the touches.
- wheel = 'wheel'
The mouse-wheel is used (scrolling), or the touchpad/touchscreen is scrolled/pinched. Has ‘dx’, ‘dy’, ‘x’, ‘y’, ‘modifiers’.
- key_down = 'key_down'
A key is pressed down. Has ‘key’, ‘modifiers’.
- key_up = 'key_up'
A key is released. Has ‘key’, ‘modifiers’.
- char = 'char'
Experimental
- animate = 'animate'
Animation event. Has ‘step’ representing the step size in seconds. This is stable, except when the ‘catch_up’ field is nonzero.