xnano.hooks
xnano.hooks
¶
xnano.hooks
A hook is a function xnano calls when an event counts: a key press, a click, a frame, a timer or a change of state.
canvas.hook(function, on='key', keys='q') attaches a hook to a canvas or placement right
away, also as a decorator, and returns a HookHandle whose
remove() detaches it. hook (@xnano.hook(on='frame')) describes a
hook once, to attach to any target later with target | operation.
A hook's on says when it runs (HookTrigger): a kind of event
from HookKind, the name of a custom event, or a condition
(When). Hook is the function a hook runs and
HookResult is what that function may return.
Classes:
-
Context–What a hook is called with.
-
Frame–One frame of a canvas's clock.
-
Plugin–The attachment of a hook: the hook or component that is running right now.
-
ReadLog–What a component read while it was evaluated: the record that decides when it runs again.
-
Tick–One step of a simulation, which runs separately from drawing.
-
HookHandle–One hook attached to a canvas or a placement.
Functions:
-
hook–Describe a hook once, to attach to any canvas or placement later.
Attributes:
-
Hook–What a canvas or placement calls when an event counts: a function of the
-
HookKind(TypeAlias) –When a hook runs.
-
HookResult–What a hook that spans several events returns: a generator that receives the next context at
-
HookTrigger–When a hook runs, given as its
on: a kind of event, the name of a custom event, or a -
IfRunning(TypeAlias) –What an
async defhook does when it is called again while its previous run has not -
When–The condition of a hook: an expression, a function of the context, or a string.
Hook
module-attribute
¶
Hook = TypeAliasType('Hook', Callable[['Context[DepsT, StateT]'], 'object | HookResult[DepsT, StateT]'] | Callable[[], 'object | HookResult[DepsT, StateT]'], type_params=(DepsT, StateT))
What a canvas or placement calls when an event counts: a function of the
Context, or a function with no parameters when it needs none.
HookKind
module-attribute
¶
HookKind: TypeAlias = Literal['frame', 'tick', 'beat', 'key', 'mouse', 'scroll', 'drag', 'paste', 'focus', 'resize', 'state', 'custom']
When a hook runs.
'frame' before each frame, 'tick' at each simulation step, 'beat' on the canvas's
musical beat, 'key', 'mouse', 'scroll', 'drag', 'paste', 'focus' and
'resize' when that input arrives, 'state' when state the hook read changes, and
'custom' for events you push yourself. A hook without on hears every input event.
HookResult
module-attribute
¶
HookResult = TypeAliasType('HookResult', Generator[None, 'Context[DepsT, StateT]', None], type_params=(DepsT, StateT))
What a hook that spans several events returns: a generator that receives the next context at
each bare yield.
HookTrigger
module-attribute
¶
HookTrigger = TypeAliasType('HookTrigger', 'HookKind | str | When[DepsT, StateT]', type_params=(DepsT, StateT))
When a hook runs, given as its on: a kind of event, the name of a custom event, or a
condition.
- A kind from
HookKind, such as'key','tick'or'resize'. - The name of an event pushed with
Event.custom(name), such as'volume_changed'or'game.over': any name that is not a kind and does not start with a name a condition reads (keyboard,mouse,scroll,buffer,parent,root,timeordeps). - A condition, see
When: a string such as"mouse.kind == 'press'", an expression such askeyboard.key == 'q', or a function of the context. A string that reads one input hears only that input, soon="mouse.kind == 'press'"is a mouse hook and hears the pointer inside a placement; a string that reads no input is checked on every tick. An expression or a function hears every input event. Withevery=orafter=a condition is checked on those ticks, and withkeys=on those keys.
- API Reference xnano
IfRunning
module-attribute
¶
What an async def hook does when it is called again while its previous run has not
finished.
'replace' cancels the earlier run and starts the new one, so the latest input wins.
'ignore' keeps the earlier run and drops the new call. 'queue' starts the new run when
the earlier one has finished, so the runs happen one at a time in order. 'overlap' starts
the new run at once, next to the earlier one.
When
module-attribute
¶
When = TypeAliasType('When', str | Callable[['Context[DepsT, StateT]'], bool] | _core.Expression[bool], type_params=(DepsT, StateT))
The condition of a hook: an expression, a function of the context, or a string.
- An expression built from the scopes in
xnano.expressions, such askeyboard.key == 'q', is checked by the runtime before Python is called. - A function takes the context and returns
Truewhen the hook should run. - A string such as
"keyboard.key == 'q' and not mouse.is_down"is parsed once. It uses the nameskeyboard,mouse,scroll,buffer,parent,root,timeanddeps, and the operators==,!=,<,<=,>,>=,in,and,orandnot.
A value the event did not carry, such as keyboard.key while a mouse event arrives, is
neither equal to nor different from anything, so every comparison with it is false.
Context
¶
Context(canvas: Canvas[DepsT_co, StateT_co], owner: Canvas[object, object] | Placement[object, object], hook: HookHandle[object, object], event: Event | TerminalStateChange | Frame | Tick | None, core: CoreContext | None, log: ReadLog | None = None, timeline: Callable[[], Region[float]] | None = None, screen: Screen[object, object] | None = None)
Bases: Generic[DepsT_co, StateT_co]
What a hook is called with.
The context carries the event and live views of where the hook is attached. Its members are
read when you use them, so a context costs almost nothing to receive. A generator hook
receives a new context each time it resumes, so context.mouse.position is always the
newest event's.
target, parent and root are live objects with concrete values. target is
what the hook is attached to, a placement or the canvas, with its hook, state and
fx. parent is where the target is drawn: the placement it is nested in, or the
canvas's screen. Either one has the same members, so context.parent.width is an int
and context.parent.local(context.mouse.position) turns a pointer into its cells at any
depth. The expressions of the same names, such as parent.width, are in
xnano.expressions.
The context has the canvas's devices: screen, speaker, microphone,
keyboard, mouse and clock. Its keyboard and mouse read the event being
handled: each reading is None (or 0 for the wheel) unless the event is of that
kind, and both can press keys and buttons for the program.
Attributes:
-
canvas(Canvas[DepsT_co, StateT_co]) –The root canvas the hook belongs to.
-
event(Event | TerminalStateChange | Frame | Tick | None) –The event, a
Frameforhook(on='frame'), anTickforhook(on='tick'), aTerminalStateChangeforhook(on='state'), orNonewhen no event caused the call. -
hook(HookHandle[object, object]) –The registration, so the hook can call
hook.remove(). -
screen(Screen[DepsT_co, StateT_co]) –The canvas's
Screen; for arenderable, its own screen. -
speaker(Speaker) –The canvas's
Speaker. -
microphone(Microphone) –The canvas's
Microphone. -
keyboard(Keyboard) –The
Keyboard, with the key of the event:key,kind,modifiers, andpastedfor a paste. -
mouse(Mouse) –The
Mouse, with the pointer event:position,buttonandkind, and the wheel steps inscroll. -
clock(Clock) –The canvas's
Clock. -
buffer(Clock) –The placement (or the canvas) the hook is attached to.
-
parent(Placement[object, object] | Screen[object, object]) –Where the buffer is drawn: the placement it is nested in, or the
Screenof the canvas. -
root(Canvas[DepsT_co, StateT_co]) –The root canvas.
-
plugin(Plugin) –The attachment of the hook that is running.
-
deps(DepsT_co) –The dependencies given to
new(deps=...). -
fx(EffectController) –Applies effects to the hook's target while the hook is active.
-
region(Region[float]) –The
Regionof the hook's target: its cells on the screen, or for a hook on a playable the beats and semitones of what it plays. -
size(Size) –The size in cells of
context.targeton the screen, the shortcut forcontext.region.size.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=20, height=3) as canvas:
label = canvas.screen.write('hi', x=2)
heard = []
@label.hook(on="mouse.kind == 'press'")
def pressed(context: xnano.Context) -> None:
heard.append((context.mouse.position.x, context.target.x))
canvas.push(Event.mouse_event(column=3, row=0, kind='press', button='left'))
canvas.deliver_events()
assert heard == [(3, 2)]
Create a context. The runtime does this for you; hooks receive one.
Parameters:
-
canvas(Canvas[DepsT_co, StateT_co]) –The root canvas.
-
owner(Canvas[object, object] | Placement[object, object]) –The canvas or placement the hook is attached to.
-
hook(HookHandle[object, object]) –The hook that is called.
-
event(Event | TerminalStateChange | Frame | Tick | None) –The event, or
None. -
core(CoreContext | None) –The runtime's context for the event, or
None. -
log(ReadLog | None, default:None) –Where to record what is read, for a component;
Nonefor a hook. -
timeline(Callable[[], Region[float]] | None, default:None) –Returns the region on the timeline of what a playable is playing, for a context of a playable;
Nonefor any other, whoseregionis on the screen. -
screen(Screen[object, object] | None, default:None) –The screen of a renderable, its own;
Nonefor the canvas's.
- API Reference xnano
- Learn Hooks & Input
-
API Reference
xnano
-
xnano -
xnano.ai
ai -
xnano.ai.models.art
artAnimation__xnano_write__ -
xnano.ai.models.components
componentsComponent__xnano_write__ -
xnano.art
art -
xnano.audio
audioNote__xnano_play__ -
xnano.components
components-
PlayableComponent__xnano_play__ -
PlayableFunction__xnano_play__ -
RenderableComponent__xnano_render__ -
RenderableFunction__xnano_render__ -
SupportsPlay__xnano_play__ -
SupportsRender__xnano_render__ -
SupportsWrite__xnano_write__ -
WritableComponent__xnano_write__ -
WritableFunction__xnano_write__ -
playable -
renderable -
writable
-
-
xnano.devices
devices -
xnano.effects
effectsEffectController -
xnano.hooks
hooksHookHandle -
xnano.layout
layoutRegion__xnano_write__ -
xnano.operations
operationsContextualOperation -
xnano.styles
stylesRichContent__xnano_write__
-
Methods:
-
local–Convert a cell of the screen into a cell of the hook's target.
Source code in xnano/hooks/_context.py
def __init__(
self,
canvas: Canvas[DepsT_co, StateT_co],
owner: Canvas[object, object] | Placement[object, object],
hook: HookHandle[object, object],
event: _core.Event | _core.TerminalStateChange | Frame | Tick | None,
core: _core.CoreContext | None,
log: ReadLog | None = None,
timeline: Callable[[], Region[float]] | None = None,
screen: Screen[object, object] | None = None,
) -> None:
"""
Create a context. The runtime does this for you; hooks receive one.
Args:
canvas: The root canvas.
owner: The canvas or placement the hook is attached to.
hook: The hook that is called.
event: The event, or ``None``.
core: The runtime's context for the event, or ``None``.
log: Where to record what is read, for a component; ``None`` for a hook.
timeline: Returns the region on the timeline of what a playable is playing, for a
context of a playable; ``None`` for any other, whose ``region`` is on the
screen.
screen: The screen of a renderable, its own; ``None`` for the canvas's.
"""
self.canvas = canvas
self._owner = owner
self.hook = hook
self._event = event
self._core = core
self._log = log
self._timeline = timeline
self._screen = screen
canvas
instance-attribute
¶
canvas: Canvas[DepsT_co, StateT_co] = canvas
The root canvas the hook belongs to.
hook
instance-attribute
¶
hook: HookHandle[object, object] = hook
The registration, so the hook can call hook.remove().
event
property
¶
keyboard
property
¶
keyboard: Keyboard
The Keyboard, reading the key being handled.
key is None unless the event is a key, and pasted unless it is a paste.
mouse
property
¶
mouse: Mouse
The Mouse, reading the pointer event being handled.
position is None for any other event; the wheel is mouse.scroll.
screen
property
¶
screen: Screen[DepsT_co, StateT_co]
The Screen of the canvas the hook belongs to; for a
renderable, its own screen.
target
property
¶
The placement the hook is attached to, or the canvas for a hook on the canvas.
parent
property
¶
Where the hook's target is drawn: the placement it is nested in, or the canvas's
Screen (for a hook on the canvas too).
region
property
¶
The region of the hook's target.
For a hook on a canvas or a placement it is the cells of context.target on the
screen, the same region as context.target.region: x and y are its
column and row, inside the border and padding, and width and height its
cells. A component that reads it runs again when the screen is resized.
For a hook on a playable, or the playable itself, it is on the timeline: a piano roll
of the sound the playable played most recently. x is the beat that sound started
on, counted on the canvas's clock at its bpm, width
the beats it lasts, y its lowest pitch as a MIDI number and height the
semitones it spans. Until the playable has played, the region is empty and starts at
the beat the canvas has reached. Reading the cells of a region on the timeline, or the
beats of a region on the screen, raises a
TerminalError.
The region is typed Region[float], because the same property serves a hook on a
playable. For whole-number x and width on the screen, read
context.target.region, a Region[int], or context.size.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=20, height=6) as canvas:
seen = []
@canvas.hook(on='key')
def pressed(context: xnano.Context) -> None:
seen.append(context.region)
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert (seen[0].resolution, seen[0].width, seen[0].height) == ('cells', 20, 6)
A hook on a playable sees the timeline of its sound:
import xnano
from xnano_core import Event
seen = []
@xnano.playable
def chord(context: xnano.Context) -> xnano.Note:
return xnano.Note(('C4', 'G4'), beats=2)
@chord.hook(on='key')
def pressed(
context: xnano.Context, component_context: xnano.components.ComponentContext
) -> None:
seen.append(context.region)
with xnano.new(width=8, height=1) as canvas:
canvas.speaker.play(chord)
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert (seen[0].width, seen[0].y, seen[0].height) == (2.0, 60, 8)
size
property
¶
The size in cells of context.target on the screen.
For a hook on a canvas or a placement this is context.region.size: inside the
border and padding of a placement. A playable has no region on the screen, so for it
this is the size of the canvas it plays on.
local
¶
Convert a cell of the screen into a cell of the hook's target.
Parameters:
-
point(Point) –A cell in screen coordinates, such as
context.mouse.position.
Examples:
import xnano
from xnano_core import Point
with xnano.new(width=20, height=4) as canvas:
placement = canvas.screen.write('hi', x=10, y=1)
@placement.hook(on='mouse')
def pressed(context: xnano.Context) -> None:
if context.mouse.position is not None:
context.local(context.mouse.position)
assert placement.local(Point(11, 1)) == Point(1, 0)
Source code in xnano/hooks/_context.py
def local(self, point: _core.Point) -> _core.Point:
"""
Convert a cell of the screen into a cell of the hook's target.
Args:
point: A cell in screen coordinates, such as ``context.mouse.position``.
Examples:
```python
import xnano
from xnano_core import Point
with xnano.new(width=20, height=4) as canvas:
placement = canvas.screen.write('hi', x=10, y=1)
@placement.hook(on='mouse')
def pressed(context: xnano.Context) -> None:
if context.mouse.position is not None:
context.local(context.mouse.position)
assert placement.local(Point(11, 1)) == Point(1, 0)
```
"""
point = check_point(point)
bounds = self._owner._buffer._absolute_bounds
return _core.Point(point.x - bounds.x, point.y - bounds.y)
Frame
dataclass
¶
Frame(canvas: Canvas[object, object], index: int, elapsed_seconds: float, delta_seconds: float, area: Rectangle, events: tuple[Event, ...] = ())
One frame of a canvas's clock.
Attributes:
-
canvas(Canvas[object, object]) –The canvas the frame belongs to.
-
index(int) –The number of steps the canvas's clock has counted, which is
Clock.framewhen the frame was made. -
elapsed_seconds(float) –Seconds on the canvas's clock.
-
delta_seconds(float) –Seconds since the previous frame (
0.0for the first). -
area(Rectangle) –The rectangle the frame is drawn into, in cells.
-
events(tuple[Event, ...]) –The events delivered to the canvas since the previous frame of the same
iter()(key presses, mouse events, pastes, resizes, focus changes and custom events), oldest first; empty for the frame of a hook.
index
instance-attribute
¶
index: int
The number of steps the canvas's clock has counted, which is
Clock.frame when the frame was made.
Plugin
¶
Plugin(hook: HookHandle[object, object])
The attachment of a hook: the hook or component that is running right now.
context.plugin names that one attachment and nothing else. The hook itself is
context.hook.
Attributes:
-
hook–The hook this attachment belongs to.
-
state(StateNamespace) –State that belongs to this attachment alone, read with
getand written withset; seeStateNamespace.
Create the attachment of a hook or component. Use context.plugin instead of
calling this.
Parameters:
-
hook(HookHandle[object, object]) –The hook or component driver that is running.
Source code in xnano/hooks/_context.py
state
property
¶
state: StateNamespace
State that belongs to this hook alone.
No other hook or placement sees it, and it is deleted when the hook is removed. To
share a value between hooks, keep it in context.root.state.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
@canvas.hook(on='key')
def count(context: xnano.Context) -> None:
state = context.plugin.state
state.set('presses', state.get('presses', default=0) + 1)
context.root.state.set('latest', state.get('presses'))
canvas.push(Event.key_press('a'))
canvas.push(Event.key_press('b'))
canvas.deliver_events()
assert canvas.state.get('latest') == 2
ReadLog
¶
What a component read while it was evaluated: the record that decides when it runs again.
A component that read nothing that changes is evaluated once. One that read the time is evaluated again on every frame (or every beat for a playable), one that read the size or the region on the screen when the screen is resized, and one that read an input when that input arrives.
Attributes:
-
uses_time–Whether it read the clock, the event or the held keys.
-
uses_size–Whether it read the size or the region of the canvas or of a buffer on the screen.
-
uses_deps–Whether it read the dependencies.
-
input_kinds(set[str]) –The kinds of input it read:
'key','mouse','scroll'or'paste'.
Start an empty record.
Source code in xnano/hooks/_context.py
Tick
dataclass
¶
Tick(canvas: Canvas[object, object], elapsed_seconds: float, delta_seconds: float, is_fixed_step: bool)
One step of a simulation, which runs separately from drawing.
Attributes:
-
canvas(Canvas[object, object]) –The canvas the tick belongs to.
-
elapsed_seconds(float) –Seconds on the tick's clock.
-
delta_seconds(float) –Seconds this tick advances.
-
is_fixed_step(bool) –Whether the tick runs at a fixed rate.
HookHandle
¶
HookHandle(owner: _Hooked[DepsT, StateT], function: Callable[[Context[DepsT, StateT]], object], *, on: HookKind | None, when: CompiledWhen, every: float | None, after: float | None, keys: tuple[str, ...], if_running: IfRunning = 'replace')
Bases: Generic[DepsT, StateT]
One hook attached to a canvas or a placement.
remove stops the hook, cancels its timer and closes its generator.
Attributes:
-
function(Callable[[Context[DepsT, StateT]], object]) –The function that is called when an event counts.
-
on(HookKind | None) –When the hook runs, or
Nonefor a hook that hears every input event. -
is_removed(bool) –Whether
removewas called.
Attach a function to a canvas or placement. Use hook instead of calling this.
Parameters:
-
owner(_Hooked[DepsT, StateT]) –The canvas or placement the hook listens on.
-
function(Callable[[Context[DepsT, StateT]], object]) –The function to call with a
Context. -
on(HookKind | None) –When the hook runs.
-
when(CompiledWhen) –The compiled condition.
-
every(float | None) –Seconds (
'tick') or beats ('beat') between runs. -
after(float | None) –Seconds or beats before the one run.
-
keys(tuple[str, ...]) –The normalized keys of an
on='key'hook. -
if_running(IfRunning, default:'replace') –What an
async defhook does when it is called again while its previous run has not finished.
Methods:
-
remove–Stop this hook. Removing it twice does nothing.
Source code in xnano/hooks/_handles.py
def __init__(
self,
owner: _Hooked[DepsT, StateT],
function: Callable[[Context[DepsT, StateT]], object],
*,
on: HookKind | None,
when: CompiledWhen,
every: float | None,
after: float | None,
keys: tuple[str, ...],
if_running: IfRunning = 'replace',
) -> None:
"""
Attach a function to a canvas or placement. Use ``hook`` instead of calling this.
Args:
owner: The canvas or placement the hook listens on.
function: The function to call with a [`Context`][xnano.hooks.Context].
on: When the hook runs.
when: The compiled condition.
every: Seconds (``'tick'``) or beats (``'beat'``) between runs.
after: Seconds or beats before the one run.
keys: The normalized keys of an ``on='key'`` hook.
if_running: What an ``async def`` hook does when it is called again while its
previous run has not finished.
"""
self._owner = owner
self.function = function
self.on = on
self._when = when
self._every = every
self._after = after
self._keys = keys
self._removed = False
self._is_generator_function = inspect.isgeneratorfunction(function)
# The runs of an async def hook, which happen on an event loop.
self._coroutine_runs: CoroutineRuns | None = (
CoroutineRuns(if_running) if inspect.iscoroutinefunction(function) else None
)
self._generator: Generator[None, Context[DepsT, StateT], None] | None = None
self._core_hook: _core.Hook | None = None
self._registration: _Registration | None = None
self._stop_frames: Callable[[], None] | None = None
# A hook without on= also runs on every frame while a mouse button it heard is held,
# once the button has been held for a short delay after its press.
self._stop_held_button_frames: Callable[[], None] | None = None
self._has_heard_input_since_frame = False
self._held_button_pressed_at_seconds = 0.0
self._due: float | None = None
self._is_captured = False
self._own_revisions: deque[int] = deque(maxlen=4)
self._state_run: _HookRun = _HookRun(track=on == 'state')
self._followed: frozenset[tuple[str | int, ...]] | None = None
self._plugin_state: StateNamespace | None = None
self._effect_state: EffectState | None = None
function
instance-attribute
¶
The function called with a context when an event counts.
on
instance-attribute
¶
on: HookKind | None = on
When the hook runs, or None for a hook that hears every input event.
remove
¶
Stop this hook. Removing it twice does nothing.
Source code in xnano/hooks/_handles.py
def remove(self) -> None:
"""Stop this hook. Removing it twice does nothing."""
if self._removed:
return
self._removed = True
effect_state = self._effect_state
if effect_state is not None:
self._effect_state = None
effect_state.clear()
generator = self._generator
self._generator = None
if generator is not None and inspect.getgeneratorstate(generator) != (
inspect.GEN_RUNNING
):
generator.close()
coroutine_runs = self._coroutine_runs
if coroutine_runs is not None:
coroutine_runs.cancel()
registrations = self._owner._registrations
if self in registrations:
registrations.remove(self)
owner = self._owner
owner._canvas._host.post(self._unregister)
hook
¶
hook(function: Hook[DepsT, StateT]) -> ContextualOperation[DepsT, StateT]
hook(function: Hook[DepsT, StateT] | None = None, /, *, on: HookTrigger[DepsT, StateT] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False, if_running: IfRunning = 'replace') -> ContextualOperation[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], ContextualOperation[DepsT, StateT]]
Describe a hook once, to attach to any canvas or placement later.
It takes the same arguments as target.hook(...) and returns an operation: pipe it onto
a target with target | operation, or pass it to update. Each target gets its own
hook. The function may return an operation, a style or an effect, which is applied to the
target it runs on.
Parameters:
-
function(Hook[DepsT, StateT] | None, default:None) –The function to wrap when
@xnano.hookis used without parentheses: a function of theContext, or one with no parameters. -
on(HookTrigger[DepsT, StateT] | None, default:None) –When the hook runs: a kind of event, the name of a custom event, or a condition; see
HookTrigger. -
every(float | None, default:None) –Repeat every this many seconds (
'tick') or beats ('beat'). -
after(float | None, default:None) –Run once after this many seconds (
'tick') or beats ('beat'). -
keys(KeyName | Sequence[KeyName] | None, default:None) –The key or keys an
on='key'hook reacts to. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). -
if_running(IfRunning, default:'replace') –For an
async deffunction, what happens when the hook runs again before its previous run has finished; seeIfRunning.
Raises:
-
TypeError–functioncannot be called with a context,keysis not a key name or a list of them, oronis not a kind, a name or a condition. -
ValueError–on,every,after,keysorif_runningis not valid, or they do not fit together.
Examples:
import xnano
readings = []
@xnano.hook(on='frame')
def clock_readout(context: xnano.Context) -> None:
readings.append(round(context.clock.elapsed_seconds, 1))
with xnano.new(width=12, height=1) as canvas:
canvas.screen | clock_readout
canvas.clock.step(delta_seconds=0.5)
assert readings == [0.5]
Source code in xnano/hooks/__init__.py
def hook(
function: Hook[DepsT, StateT] | None = None,
/,
*,
on: HookTrigger[DepsT, StateT] | None = None,
every: float | None = None,
after: float | None = None,
keys: KeyName | Sequence[KeyName] | None = None,
requires_deps: bool = False,
if_running: IfRunning = 'replace',
) -> (
ContextualOperation[DepsT, StateT]
| Callable[
[Hook[DepsT, StateT]],
ContextualOperation[DepsT, StateT],
]
):
"""
Describe a hook once, to attach to any canvas or placement later.
It takes the same arguments as ``target.hook(...)`` and returns an operation: pipe it onto
a target with ``target | operation``, or pass it to ``update``. Each target gets its own
hook. The function may return an operation, a style or an effect, which is applied to the
target it runs on.
Args:
function: The function to wrap when ``@xnano.hook`` is used without parentheses: a
function of the [`Context`][xnano.hooks.Context], or one with no parameters.
on: When the hook runs: a kind of event, the name of a custom event, or a condition;
see [`HookTrigger`][xnano.hooks.HookTrigger].
every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
after: Run once after this many seconds (``'tick'``) or beats (``'beat'``).
keys: The key or keys an ``on='key'`` hook reacts to.
requires_deps: Whether the hook needs the dependencies given to ``new(deps=...)``.
if_running: For an ``async def`` function, what happens when the hook runs again
before its previous run has finished; see [`IfRunning`][xnano.hooks.IfRunning].
Raises:
TypeError: ``function`` cannot be called with a context, ``keys`` is not a key name
or a list of them, or ``on`` is not a kind, a name or a condition.
ValueError: ``on``, ``every``, ``after``, ``keys`` or ``if_running`` is not valid, or
they do not fit together.
Examples:
```python
import xnano
readings = []
@xnano.hook(on='frame')
def clock_readout(context: xnano.Context) -> None:
readings.append(round(context.clock.elapsed_seconds, 1))
with xnano.new(width=12, height=1) as canvas:
canvas.screen | clock_readout
canvas.clock.step(delta_seconds=0.5)
assert readings == [0.5]
```
"""
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
_check_hook_arguments(
cast('_Hooked[object, object]', object()), kind, every, after, keys
)
compile_when(condition)
_check_if_running(if_running)
normalized_keys: tuple[str, ...] = (
() if keys is None else (keys,) if isinstance(keys, str) else tuple(keys)
)
def wrap(
callback: Hook[DepsT, StateT],
) -> ContextualOperation[DepsT, StateT]:
checked = _check_hook_function(callback)
_check_if_running_fits(checked, if_running)
return ContextualOperation(
cast('Callable[[Context[DepsT, StateT]], object]', checked),
on=on,
every=every,
after=after,
keys=normalized_keys,
requires_deps=requires_deps,
if_running=if_running,
)
if function is not None:
return wrap(function)
return wrap