CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-plover

Open Source Stenography Software providing real-time stenographic typing, machine support, and plugin architecture.

Pending
Overview
Eval results
Files

engine.mddocs/

Stenography Engine

The StenoEngine class is the central coordination hub for all stenographic processing in Plover. It manages machine communication, dictionary operations, translation processing, and output generation through a comprehensive event-driven architecture.

Capabilities

Engine Initialization

Creates and configures the stenography engine with required dependencies.

def __init__(self, config, controller=None, keyboard_emulation=None):
    """
    Initialize the stenography engine.
    
    Args:
        config: Configuration object containing engine settings
        controller: Optional controller interface for engine management
        keyboard_emulation: Optional keyboard emulation interface for output
        
    Creates engine instance with specified configuration and optional
    controller and keyboard emulation interfaces.
    """

Engine Lifecycle Management

Controls the stenography engine's operational state with support for starting, stopping, and restarting the processing pipeline.

def start(self) -> None:
    """
    Start the stenography engine and begin processing.
    
    Initializes machine connection, loads configuration, 
    and begins stroke capture and translation processing.
    """

def quit(self, code: int = 0) -> None:
    """
    Shutdown the stenography engine gracefully.
    
    Args:
        code: Exit code for application termination
        
    Disconnects machine, saves configuration, and stops all processing.
    """

def restart(self) -> None:
    """
    Restart the stenography engine.
    
    Performs complete shutdown and restart cycle,
    reloading configuration and reconnecting machine.
    """

def join(self) -> None:
    """
    Wait for engine thread completion.
    
    Blocks until engine processing thread terminates.
    """

Output Control

Manages stenographic output generation with toggle and explicit control methods.

def toggle_output(self) -> None:
    """
    Toggle stenographic output on or off.
    
    Switches between enabled and disabled output states,
    affecting whether translations are sent to applications.
    """

def set_output(self, enabled: bool) -> None:
    """
    Set stenographic output state explicitly.
    
    Args:
        enabled: True to enable output, False to disable
        
    Controls whether stroke translations are converted to text output.
    """

@property
def output(self) -> bool:
    """
    Get current output state.
    
    Returns:
        True if output is enabled, False otherwise
    """

@output.setter
def output(self, enabled: bool) -> None:
    """
    Set output state via property assignment.
    
    Args:
        enabled: True to enable output, False to disable
    """

Configuration Management

Provides access to engine configuration with support for runtime updates and persistence.

@property
def config(self) -> dict:
    """
    Get engine configuration as dictionary.
    
    Returns:
        Complete configuration dictionary with all settings
    """

@config.setter
def config(self, update: dict) -> None:
    """
    Update engine configuration.
    
    Args:
        update: Dictionary of configuration changes to apply
        
    Updates configuration and triggers necessary reloads.
    """

def __getitem__(self, setting: str):
    """
    Get specific configuration value.
    
    Args:
        setting: Configuration key to retrieve
        
    Returns:
        Value of specified configuration setting
    """

def __setitem__(self, setting: str, value) -> None:
    """
    Set specific configuration value.
    
    Args:
        setting: Configuration key to set
        value: New value for the setting
        
    Updates configuration and applies changes immediately.
    """

def load_config(self) -> None:
    """
    Reload configuration from file.
    
    Reads configuration from disk and applies all changes,
    potentially triggering machine reconnection and dictionary reload.
    """

def reset_machine(self) -> None:
    """
    Reset and reconnect stenotype machine.
    
    Disconnects current machine and attempts reconnection
    with current configuration settings.
    """

Dictionary Operations

Comprehensive dictionary interaction supporting lookup, reverse lookup, and translation management.

def lookup(self, strokes: tuple) -> str:
    """
    Look up translation for stroke sequence.
    
    Args:
        strokes: Tuple of stroke strings to look up
        
    Returns:
        Translation string if found, None otherwise
        
    Searches dictionaries in precedence order with filters applied.
    """

def raw_lookup(self, strokes: tuple) -> str:
    """
    Look up translation without dictionary filters.
    
    Args:
        strokes: Tuple of stroke strings to look up
        
    Returns:
        Raw translation string if found, None otherwise
        
    Bypasses all dictionary filters for direct lookup.
    """

def lookup_from_all(self, strokes: tuple) -> list:
    """
    Look up translations from all dictionaries.
    
    Args:
        strokes: Tuple of stroke strings to look up
        
    Returns:
        List of (dictionary_path, translation) tuples
        
    Returns matches from all dictionaries regardless of precedence.
    """

def raw_lookup_from_all(self, strokes: tuple) -> list:
    """
    Raw lookup from all dictionaries without filters.
    
    Args:
        strokes: Tuple of stroke strings to look up
        
    Returns:
        List of (dictionary_path, translation) tuples
        
    Bypasses filters and returns all matches across dictionaries.
    """

def reverse_lookup(self, translation: str) -> list:
    """
    Find stroke sequences for translation.
    
    Args:
        translation: Translation text to reverse lookup
        
    Returns:
        List of stroke tuples that produce the translation
        
    Searches all dictionaries for strokes matching translation.
    """

def casereverse_lookup(self, translation: str) -> list:
    """
    Case-insensitive reverse lookup.
    
    Args:
        translation: Translation text to reverse lookup
        
    Returns:
        List of stroke tuples for case-insensitive matches
    """

def add_translation(self, strokes: tuple, translation: str, dictionary_path: str = None) -> None:
    """
    Add new translation to dictionary.
    
    Args:
        strokes: Tuple of stroke strings
        translation: Translation text to associate
        dictionary_path: Specific dictionary path, uses first writable if None
        
    Adds translation to specified or default writable dictionary.
    """

@property
def dictionaries(self) -> StenoDictionaryCollection:
    """
    Get dictionary collection.
    
    Returns:
        StenoDictionaryCollection managing all loaded dictionaries
    """

def add_dictionary_filter(self, dictionary_filter) -> None:
    """
    Add dictionary filter function.
    
    Args:
        dictionary_filter: Function to filter dictionary lookups
        
    Filter functions receive (strokes, translation) and return bool.
    """

def remove_dictionary_filter(self, dictionary_filter) -> None:
    """
    Remove dictionary filter function.
    
    Args:
        dictionary_filter: Filter function to remove
    """

Translation State Management

Controls translator state for undo functionality and stroke sequencing.

@property
def translator_state(self):
    """
    Get current translator state.
    
    Returns:
        Internal translator state object for undo operations
    """

@translator_state.setter
def translator_state(self, state) -> None:
    """
    Set translator state.
    
    Args:
        state: Translator state object to restore
        
    Used for implementing undo functionality.
    """

def clear_translator_state(self, undo: bool = False) -> None:
    """
    Clear translator state.
    
    Args:
        undo: Whether to trigger undo before clearing
        
    Resets translation state, optionally undoing current translations.
    """

@property
def starting_stroke_state(self) -> StartingStrokeState:
    """
    Get starting stroke state.
    
    Returns:
        StartingStrokeState named tuple with formatting preferences
    """

@starting_stroke_state.setter  
def starting_stroke_state(self, state: StartingStrokeState) -> None:
    """
    Set starting stroke state.
    
    Args:
        state: StartingStrokeState with attach, capitalize, space_char
    """

Suggestions

Provides translation suggestions for improving stenographic efficiency.

def get_suggestions(self, translation: str) -> list:
    """
    Get stroke suggestions for translation.
    
    Args:
        translation: Translation text to get suggestions for
        
    Returns:
        List of Suggestion namedtuples with text and steno_list
        
    Analyzes dictionaries to suggest efficient stroke patterns.
    """

Machine State

Access to stenotype machine connection status and capabilities.

@property
def machine_state(self) -> str:
    """
    Get current machine state.
    
    Returns:
        Machine state string: 'stopped', 'initializing', 'connected', or 'disconnected'
    """

Hook System

Event-driven architecture enabling extensions to respond to stenographic events.

HOOKS = [
    'stroked', 'translated', 'machine_state_changed', 
    'output_changed', 'config_changed', 'dictionaries_loaded',
    'send_string', 'send_backspaces', 'send_key_combination',
    'add_translation', 'focus', 'configure', 'lookup', 
    'suggestions', 'quit'
]

def hook_connect(self, hook: str, callback) -> None:
    """
    Connect callback to engine event.
    
    Args:
        hook: Event name from HOOKS list
        callback: Function to call when event occurs
        
    Callback signature varies by hook type.
    """

def hook_disconnect(self, hook: str, callback) -> None:
    """
    Disconnect callback from engine event.
    
    Args:
        hook: Event name from HOOKS list
        callback: Function to disconnect
    """

Usage Examples:

from plover.engine import StenoEngine
from plover.config import Config

# Create engine with configuration
config = Config()
engine = StenoEngine(config)

# Connect to stroke events
def on_stroke(stroke):
    print(f"Stroke: {stroke}")

engine.hook_connect('stroked', on_stroke)

# Start processing
engine.start()

# Control output
engine.set_output(True)
engine.toggle_output()

# Work with dictionaries
translation = engine.lookup(('H', 'E', 'L', 'O'))
engine.add_translation(('K', 'U', 'S', 'T', 'O', 'M'), 'custom')

# Get suggestions
suggestions = engine.get_suggestions('hello')

# Shutdown
engine.quit()

Hook Event Details

Stroke Events

  • stroked: Fired when stroke received from machine
    • Callback signature: callback(stroke: list[str])
  • translated: Fired when stroke translated to text
    • Callback signature: callback(old: list, new: list)

State Events

  • machine_state_changed: Machine connection status changed
    • Callback signature: callback(machine_type: str, machine_state: str)
  • output_changed: Output enabled/disabled state changed
    • Callback signature: callback(enabled: bool)
  • config_changed: Configuration updated
    • Callback signature: callback(update: dict)
  • dictionaries_loaded: Dictionary collection reloaded
    • Callback signature: callback()

Output Events

  • send_string: Text string sent to output
    • Callback signature: callback(text: str)
  • send_backspaces: Backspaces sent to output
    • Callback signature: callback(count: int)
  • send_key_combination: Key combination sent
    • Callback signature: callback(combo: str)

Interface Events

  • add_translation: Translation added to dictionary
    • Callback signature: callback()
  • focus: Focus main window requested
    • Callback signature: callback()
  • configure: Configuration dialog requested
    • Callback signature: callback()
  • lookup: Lookup dialog requested
    • Callback signature: callback()
  • suggestions: Suggestions dialog requested
    • Callback signature: callback()
  • quit: Application quit requested
    • Callback signature: callback()

Threading and Engine Management

Engine Threading

Core threading method that runs the engine's main event loop.

def run(self) -> None:
    """
    Main event loop for the engine thread.
    
    Processes queued operations from other threads in a thread-safe manner.
    This method runs continuously until the engine is shut down via quit().
    
    Note: This method is typically called automatically when using start(),
    but can be called directly for custom threading scenarios.
    """

Context Manager Support

Thread-safe access to engine internals through context manager protocol.

def __enter__(self) -> 'StenoEngine':
    """
    Enter context manager for thread-safe engine access.
    
    Returns:
        Engine instance for use within context
        
    Enables 'with engine:' syntax for thread-safe operations.
    """

def __exit__(self, exc_type, exc_value, traceback) -> None:
    """
    Exit context manager and release thread lock.
    
    Args:
        exc_type: Exception type if raised within context
        exc_value: Exception value if raised within context  
        traceback: Exception traceback if raised within context
    """

Dictionary-Style Configuration Access

Convenient dictionary-style access to engine configuration settings.

def __getitem__(self, setting: str) -> Any:
    """
    Get configuration setting using dictionary syntax.
    
    Args:
        setting: Configuration key name
        
    Returns:
        Configuration value for the specified setting
        
    Enables engine['setting_name'] syntax for configuration access.
    """

def __setitem__(self, setting: str, value: Any) -> None:
    """
    Set configuration setting using dictionary syntax.
    
    Args:
        setting: Configuration key name
        value: New value for the setting
        
    Enables engine['setting_name'] = value syntax for configuration.
    """

Available Hook Events

The engine supports these predefined hook event types:

HOOKS = [
    'stroked',              # Stroke input received
    'translated',           # Translation completed  
    'machine_state_changed', # Machine connection state changed
    'output_changed',       # Output enabled/disabled state changed
    'config_changed',       # Configuration updated
    'dictionaries_loaded',  # Dictionary loading completed
    'send_string',          # String output requested
    'send_backspaces',      # Backspace output requested
    'send_key_combination', # Key combination output requested
    'add_translation',      # Translation addition requested
    'focus',               # Application focus requested
    'configure',           # Configuration dialog requested
    'lookup',              # Lookup dialog requested
    'suggestions',         # Suggestions dialog requested
    'quit'                 # Application quit requested
]

Types

from typing import List, Dict, Tuple, Optional, Callable, Any
from collections import namedtuple

StartingStrokeState = namedtuple('StartingStrokeState', 
    'attach capitalize space_char', defaults=(False, False, ' '))

MachineParams = namedtuple('MachineParams', 'type options keymap')

HookCallback = Callable[..., None]
StrokeList = List[str]
TranslationTuple = Tuple[str, ...]
ConfigDict = Dict[str, Any]

Install with Tessl CLI

npx tessl i tessl/pypi-plover

docs

configuration.md

dictionaries.md

engine.md

extensions.md

index.md

machines.md

registry.md

steno-data.md

tile.json