async2v.components.pygame.keyboard module

Pygame based keyboard input

This module provides an abstraction from the concrete key bindings by defining a keyboard handler based on actions. Those actions can be mapped to arbitrary keys. A default mapping can be specified. This module also comes with ready-to-use configurator & command line interface to perform common keyboard layout management tasks like generating a default layout file or configuring the desired layout via command line switch.

Two base classes are available that can be overridden to provide an application with keyboard support, KeyboardHandler and EventBasedKeyboardHandler.

Example for integrating a keyboard handler into an application:

class MyKeyboardHandler(EventBasedKeyboardHandler):
    ACTIONS = [
        Action('run', ['UP', 'w']),
        Action('jump', ['SPACE']),
    ]

class Launcher(ApplicationLauncher):

    def __init__(self):
        super().__init__()
        self.add_configurator(MyKeyboardHandler.configurator())
        self.add_configurator(MainWindow.configurator())

    def register_application_components(self, args, app: Application):
        # ...
        main_window_config = MainWindow.configurator().config_from_args(args)
        layout = MyKeyboardHandler.configurator().layout_from_args(args)
        keyboard = MyKeyboardHandler(layout)
        # ...
        main = MainWindow([display], keyboard_handler=keyboard, config=main_window_config)
        app.register(main)

Summary

Classes:

Action Keyboard action
CaptureTextEvent Keyboard event denoting the current capture state of text
EventBasedKeyboardHandler Abstract event based keyboard handler base class
KeyboardConfigurator Configurator for subclasses of KeyboardHandler
KeyboardEvent Keyboard event denoting the state change of a Action
KeyboardHandler Abstract keyboard handler base class
KeyboardLayout Concrete mapping from keys to actions

Reference

class Action(name, defaults=None, description=None)

Bases: object

Keyboard action

Parameters:
  • name (str) – Name of the keyboard action (must not contain whitespace)
  • defaults (Optional[List[str]]) – Default keybindings for this action
  • description (Optional[str]) –
class KeyboardLayout(actions_by_key, actions_by_scancode, help)

Bases: object

Concrete mapping from keys to actions

Do not instantiate this class directly, but create it via the matching KeyboardConfigurator.

class KeyboardConfigurator(actions)

Bases: async2v.cli.Configurator

Configurator for subclasses of KeyboardHandler

Do not instantiate this class directly, but create it from a subclass of KeyboardHandler via the configurator class method.

layout_from_args(args)

Create a keyboard layout. Use this to construct an instance of the KeyboardHandler subclass this configurator was created from.

Return type:KeyboardLayout
class KeyboardHandler(layout)

Bases: async2v.components.base.SubComponent

Abstract keyboard handler base class

Override this class to implement advanced keyboard handling. For most use cases, EventBasedKeyboardHandler should be sufficient.

Example:

class MyKeyboardHandler(KeyboardHandler):
    ACTIONS = [
        Action('left', ['a']),
        Action('right', ['d']),
    ]

    def __init__(self, layout: KeyboardLayout):
        super().__init__(layout)
        self.output = Output('output')

    def key_down(self, action: str) -> None:
        self.output.push(['ping', action])

    def key_up(self, action: str) -> None:
        self.output.push(['pong', action])

    def process(self) -> None:
        pass
Parameters:layout (KeyboardLayout) – Use layout created by the layout_from_args method of the KeyboardConfigurator created for that concrete KeyboardHandler
ACTIONS = []
Type:List[Action]

Needs to be overwritten in subclass to specify the keyboard actions for thta layout

COMPLETE_CAPTURE = [13, 271]
Type:List[int]

Can be overwritten to change the keys completing text capture (see capture_text)

BACK = [8]
Type:List[int]

Can be overwritten to change the keys removing the last character from text capture (see capture_text)

REPEAT_DELAY_MS = 500
Type:int

Can be overwritten to change the delay before keys are repeated on long key press during text capture (see capture_text)

REPEAT_INTERVAL_MS = 50
Type:int

Can be overwritten to change the interval at which keys are repeated on long key press during text capture (see capture_text)

classmethod configurator()

Create a configurator for the keyboard ACTIONS specified in the concrete handler

Return type:KeyboardConfigurator
push_key_down(key, scancode, character)

This method is used by the framework to push KEYDOWN events to the handler. You should not need to call this method from your production code.

Return type:None
push_key_up(key, scancode)

This method is used by the framework to push KEYUP events to the handler. You should not need to call this method from your production code.

Return type:None
capture_text(capture_id, initial='')

Trigger the capture of a single-line string. Capturing ends when RETURN is pressed. The result, together with the capture_id, is passed to the text function. As a side-effect, artificial key_up events are triggered for all active actions and their state is set to up.

text_capture_completed(capture_id, text)

Override this method to receive captured text.

text_capture_update(capture_id, text)

Override this method to receive changes to the currently captured text.

is_pressed(action)

Query the current state of a keyboard action

Return type:bool
key_down(action)

Called after a KEYDOWN event for the associated key has been received by pygame

Return type:None
key_up(action)

Called after a KEYUP event for the associated key has been received by pygame

Return type:None
process()

Called after all pending keyboard events in the current iteration have been processed. Especially, this method is called after the key_down & key_up methods were called. This method is the place to trigger actions based on the state of actions that can be queried via the is_pressed method.

Return type:None
class KeyboardEvent(action, active)

Bases: object

Keyboard event denoting the state change of a Action

action = None
Type:str

Keyboard action name as defined in the corresponding Action

active = None
Type:bool

True if the key mapped to this action is pressed

class CaptureTextEvent(capture_id, text, complete)

Bases: object

Keyboard event denoting the current capture state of text

Capturing text is triggered by calling capture_text on the keyboard handler.

capture_id = None
Type:str

Capture ide passed to capture_text

text = None
Type:str

Captured text so far

complete = None
Type:bool

True iff this text capture flow is complete (in that case, text contains the complete text)

class EventBasedKeyboardHandler(layout)

Bases: async2v.components.pygame.keyboard.KeyboardHandler

Abstract event based keyboard handler base class

This keyboard handler emits events containing KeyboardEvent payload on the event key KEYBOARD_EVENT, when a key bound to a configured Action is pressed or released.

Text capture can be triggered by sending an event containing a capture_id to the key CAPTURE_TEXT_TRIGGER. The results of this text capture flow are emitted via events containing CaptureTextEvent payload on the event key CAPTURE_TEXT_EVENT.

Example:

class MyKeyboardHandler(EventBasedKeyboardHandler):
    ACTIONS = [
        Action('up', ['UP', 'w']),
        Action('down', ['DOWN', 's']),
        Action('left', ['LEFT', 'a']),
        Action('right', ['RIGHT', 'd']),
    ]
Parameters:layout (KeyboardLayout) – Use layout created by the layout_from_args method of the KeyboardConfigurator created for that concrete KeyboardHandler
CAPTURE_TEXT_TRIGGER = 'async2v.keyboard.trigger.capture'
Type:str
CAPTURE_TEXT_EVENT = 'async2v.keyboard.text'
Type:str
KEYBOARD_EVENT = 'async2v.keyboard.action'
Type:str