The util module

Utilities for Vispy. A collection of modules that are used in one or more Vispy sub-packages.


vispy.util.event

The event module implements the classes that make up the event system. The Event class and its subclasses are used to represent "stuff that happens". The EventEmitter class provides an interface to connect to events and to emit events. The EmitterGroup groups EventEmitter objects.

For more information see http://github.com/vispy/vispy/wiki/API_Events


class vispy.util.event.Event(type, native=None, **kwargs)

Class describing events that occur and can be reacted to with callbacks. Each event instance contains information about a single event that has occurred such as a key press, mouse motion, timer activation, etc.

Subclasses: KeyEvent, MouseEvent, TouchEvent, StylusEvent

The creation of events and passing of events to the appropriate callback functions is the responsibility of EventEmitter instances.

Note that each event object has an attribute for each of the input arguments listed below.

Parameters:

type : str

String indicating the event type (e.g. mouse_press, key_release)

native : object (optional)

The native GUI event object

**kwargs : keyword arguments

All extra keyword arguments become attributes of the event object.

blocked

This boolean property indicates whether the event will be delivered to event callbacks. If it is set to True, then no further callbacks will receive the event. When possible, it is recommended to use Event.handled rather than Event.blocked.

handled

This boolean property indicates whether the event has already been acted on by an event handler. Since many handlers may have access to the same events, it is recommended that each check whether the event has already been handled as well as set handled=True if it decides to act on the event.

source

The object that the event applies to (i.e. the source of the event).

sources

List of objects that the event applies to (i.e. are or have been a source of the event). Can contain multiple objects in case the event traverses a hierarchy of objects.

class vispy.app.canvas.MouseEvent(type, pos=None, button=None, buttons=None, modifiers=None, delta=None, last_event=None, press_event=None, **kwargs)

Mouse event class

Note that each event object has an attribute for each of the input arguments listed below, as well as a "time" attribute with the event's precision start time.

Parameters:

type : str

String indicating the event type (e.g. mouse_press, key_release)

pos : (int, int)

The position of the mouse (in screen coordinates).

button : int | None

The button that generated this event (can be None). Left=1, right=2, middle=3. During a mouse drag, this will return the button that started the drag (same thing as event.press_event.button).

buttons : [int, ...]

The list of buttons depressed during this event.

modifiers : tuple of Key instances

Tuple that specifies which modifier keys were pressed down at the time of the event (shift, control, alt, meta).

delta : (float, float)

The amount of scrolling in horizontal and vertical direction. One "tick" corresponds to a delta of 1.0.

press_event : MouseEvent

The press event that was generated at the start of the current drag, if any.

last_event : MouseEvent

The MouseEvent immediately preceding the current event. During drag operations, all generated events retain their last_event properties, allowing the entire drag to be reconstructed.

native : object (optional)

The native GUI event object

**kwargs : keyword arguments

All extra keyword arguments become attributes of the event object.

Methods

drag_events
trail
drag_events()

Return a list of all mouse events in the current drag operation.

Returns None if there is no current drag operation.

is_dragging

Indicates whether this event is part of a mouse drag operation.

trail()

Return an (N, 2) array of mouse coordinates for every event in the current mouse drag operation.

Returns None if there is no current drag operation.

class vispy.app.canvas.KeyEvent(type, key=None, text='', modifiers=None, **kwargs)

Key event class

Note that each event object has an attribute for each of the input arguments listed below.

Parameters:

type : str

String indicating the event type (e.g. mouse_press, key_release)

key : vispy.keys.Key instance

The Key object for this event. Can be compared to string names.

text : str

The text representation of the key (can be an empty string).

modifiers : tuple of Key instances

Tuple that specifies which modifier keys were pressed down at the time of the event (shift, control, alt, meta).

native : object (optional)

The native GUI event object

**kwargs : keyword arguments

All extra keyword arguments become attributes of the event object.

class vispy.app.canvas.ResizeEvent(type, size=None, physical_size=None, **kwargs)

Resize event class

Note that each event object has an attribute for each of the input arguments listed below.

Parameters:

type : str

String indicating the event type (e.g. mouse_press, key_release)

size : (int, int)

The new size of the Canvas, in points (logical pixels).

physical_size : (int, int)

The new physical size of the Canvas, in pixels.

native : object (optional)

The native GUI event object

**kwargs : extra keyword arguments

All extra keyword arguments become attributes of the event object.

class vispy.app.canvas.DrawEvent(type, region=None, **kwargs)

Draw event class

This type of event is sent to Canvas.events.draw when a redraw is required.

Note that each event object has an attribute for each of the input arguments listed below.

Parameters:

type : str

String indicating the event type (e.g. mouse_press, key_release)

region : (int, int, int, int) or None

The region of the canvas which needs to be redrawn (x, y, w, h). If None, the entire canvas must be redrawn.

native : object (optional)

The native GUI event object

**kwargs : extra keyword arguments

All extra keyword arguments become attributes of the event object.


class vispy.util.event.EventEmitter(source=None, type=None, event_class=<class 'vispy.util.event.Event'>)

Encapsulates a list of event callbacks.

Each instance of EventEmitter represents the source of a stream of similar events, such as mouse click events or timer activation events. For example, the following diagram shows the propagation of a mouse click event to the list of callbacks that are registered to listen for that event:

User clicks    |Canvas creates
mouse on       |MouseEvent:                |'mouse_press' EventEmitter:         |callbacks in sequence: # noqa
Canvas         |                           |                                    |  # noqa
            -->|event = MouseEvent(...) -->|Canvas.events.mouse_press(event) -->|callback1(event)  # noqa
               |                           |                                 -->|callback2(event)  # noqa
               |                           |                                 -->|callback3(event)  # noqa

Callback functions may be added or removed from an EventEmitter using connect() or disconnect().

Calling an instance of EventEmitter will cause each of its callbacks to be invoked in sequence. All callbacks are invoked with a single argument which will be an instance of Event.

EventEmitters are generally created by an EmitterGroup instance.

Parameters:

source : object

The object that the generated events apply to. All emitted Events will have their .source property set to this value.

type : str or None

String indicating the event type (e.g. mouse_press, key_release)

event_class : subclass of Event

The class of events that this emitter will generate.

Methods

block([callback]) Block this emitter.
blocked([callback]) Return boolean indicating whether the emitter is blocked for the given callback.
blocker([callback]) Return an EventBlocker to be used in 'with' statements
connect(callback[, ref, position, before, after]) Connect this emitter to a new callback.
disconnect([callback]) Disconnect a callback from this emitter.
unblock([callback]) Unblock this emitter.
__call__(**kwargs)

Invoke all callbacks for this emitter.

Emit a new event object, created with the given keyword arguments, which must match with the input arguments of the corresponding event class. Note that the 'type' argument is filled in by the emitter.

Alternatively, the emitter can also be called with an Event instance as the only argument. In this case, the specified Event will be used rather than generating a new one. This allows customized Event instances to be emitted and also allows EventEmitters to be chained by connecting one directly to another.

Note that the same Event instance is sent to all callbacks. This allows some level of communication between the callbacks (notably, via Event.handled) but also requires that callbacks be careful not to inadvertently modify the Event.

block(callback=None)

Block this emitter. Any attempts to emit an event while blocked will be silently ignored. If callback is given, then the emitter is only blocked for that specific callback.

Calls to block are cumulative; the emitter must be unblocked the same number of times as it is blocked.

blocked(callback=None)

Return boolean indicating whether the emitter is blocked for the given callback.

blocker(callback=None)

Return an EventBlocker to be used in 'with' statements

Notes

For example, one could do:

with emitter.blocker():
    pass  # ..do stuff; no events will be emitted..
callback_refs

The set of callback references

callbacks

The set of callbacks

connect(callback, ref=False, position='first', before=None, after=None)

Connect this emitter to a new callback.

Parameters:

callback : function | tuple

callback may be either a callable object or a tuple (object, attr_name) where object.attr_name will point to a callable object. Note that only a weak reference to object will be kept.

ref : bool | str

Reference used to identify the callback in before/after. If True, the callback ref will automatically determined (see Notes). If False, the callback cannot be referred to by a string. If str, the given string will be used. Note that if ref is not unique in callback_refs, an error will be thrown.

position : str

If 'first', the first eligible position is used (that meets the before and after criteria), 'last' will use the last position.

before : str | callback | list of str or callback | None

List of callbacks that the current callback should precede. Can be None if no before-criteria should be used.

after : str | callback | list of str or callback | None

List of callbacks that the current callback should follow. Can be None if no after-criteria should be used.

Notes

If ref=True, the callback reference will be determined from:

  1. If callback is tuple, the secend element in the tuple.
  2. The __name__ attribute.
  3. The __class__.__name__ attribute.

The current list of callback refs can be obtained using event.callback_refs. Callbacks can be referred to by either their string reference (if given), or by the actual callback that was attached (e.g., (canvas, 'swap_buffers')).

If the specified callback is already connected, then the request is ignored.

If before is None and after is None (default), the new callback will be added to the beginning of the callback list. Thus the callback that is connected _last_ will be the _first_ to receive events from the emitter.

disconnect(callback=None)

Disconnect a callback from this emitter.

If no callback is specified, then all callbacks are removed. If the callback was not already connected, then the call does nothing.

ignore_callback_errors

Whether exceptions during callbacks will be caught by the emitter

This allows it to continue invoking other callbacks if an error occurs.

print_callback_errors

Print a message and stack trace if a callback raises an exception

Valid values are "first" (only show first instance), "reminders" (show complete first instance, then counts), "always" (always show full traceback), or "never".

This assumes ignore_callback_errors=True. These will be raised as warnings, so ensure that the vispy logging level is set to at least "warning".

source

The object that events generated by this emitter apply to

unblock(callback=None)

Unblock this emitter. See event.EventEmitter.block().

Note: Use of unblock(None) only reverses the effect of block(None); it does not unblock callbacks that were explicitly blocked using block(callback).


vispy.util.fonts

The fonts module implements some helpful functions for dealing with system fonts.

vispy.util.fonts.list_fonts()

List system fonts

Returns:

fonts : list of str

List of system fonts.


vispy.util.keys

Define constants for keys.

Each key constant is defined as a Key object, which allows comparison with strings (e.g. 'A', 'Escape', 'Shift'). This enables handling of key events without using the key constants explicitly (e.g. if ev.key == 'Left':).

In addition, key objects that represent characters can be matched to the integer ordinal (e.g. 32 for space, 65 for A). This behavior is mainly intended as a compatibility measure.

class vispy.util.keys.Key(*names)

Represent the identity of a certain key.

This represents one or more names that the key in question is known by.

A Key object can be compared to one of its string names (case insensitive), to the integer ordinal of the key (only for keys that represent characters), and to another Key instance.

name

The primary name of the key.


vispy.util.transforms

Very simple transformation library that is needed for some examples.

vispy.util.transforms.affine_map(points1, points2)

Find a 3D transformation matrix that maps points1 onto points2.

Arguments are specified as arrays of four 3D coordinates, shape (4, 3).

vispy.util.transforms.frustum(left, right, bottom, top, znear, zfar)

Create view frustum

Parameters:

left : float

Left coordinate of the field of view.

right : float

Right coordinate of the field of view.

bottom : float

Bottom coordinate of the field of view.

top : float

Top coordinate of the field of view.

znear : float

Near coordinate of the field of view.

zfar : float

Far coordinate of the field of view.

Returns:

M : ndarray

View frustum matrix (4x4).

vispy.util.transforms.ortho(left, right, bottom, top, znear, zfar)

Create orthographic projection matrix

Parameters:

left : float

Left coordinate of the field of view.

right : float

Right coordinate of the field of view.

bottom : float

Bottom coordinate of the field of view.

top : float

Top coordinate of the field of view.

znear : float

Near coordinate of the field of view.

zfar : float

Far coordinate of the field of view.

Returns:

M : ndarray

Orthographic projection matrix (4x4).

vispy.util.transforms.perspective(fovy, aspect, znear, zfar)

Create perspective projection matrix

Parameters:

fovy : float

The field of view along the y axis.

aspect : float

Aspect ratio of the view.

znear : float

Near coordinate of the field of view.

zfar : float

Far coordinate of the field of view.

Returns:

M : ndarray

Perspective projection matrix (4x4).

vispy.util.transforms.rotate(angle, axis, dtype=None)

The 3x3 rotation matrix for rotation about a vector.

Parameters:

angle : float

The angle of rotation, in degrees.

axis : ndarray

The x, y, z coordinates of the axis direction vector.

vispy.util.transforms.scale(s, dtype=None)

Non-uniform scaling along the x, y, and z axes

Parameters:

s : array-like, shape (3,)

Scaling in x, y, z.

dtype : dtype | None

Output type (if None, don't cast).

Returns:

M : ndarray

Transformation matrix describing the scaling.

vispy.util.transforms.translate(offset, dtype=None)

Translate by an offset (x, y, z) .

Parameters:

offset : array-like, shape (3,)

Translation in x, y, z.

dtype : dtype | None

Output type (if None, don't cast).

Returns:

M : ndarray

Transformation matrix describing the translation.