CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pysdl2

Pure Python wrapper around SDL2 libraries for cross-platform multimedia development

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

system-utils.mddocs/

System Integration and Utilities

System integration functions for clipboard access, file system paths, platform detection, and power management. These utilities provide cross-platform access to system services and information.

Capabilities

Clipboard Access

Functions for reading and writing text to the system clipboard.

def SDL_SetClipboardText(text: bytes) -> int:
    """
    Put UTF-8 text into the clipboard.
    
    Parameters:
    - text: text to copy to clipboard as bytes
    
    Returns:
    0 on success, negative on error
    """

def SDL_GetClipboardText() -> bytes:
    """
    Get UTF-8 text from the clipboard.
    
    Returns:
    Clipboard text as bytes, or empty bytes if no text available
    """

def SDL_HasClipboardText() -> bool:
    """
    Check whether the clipboard has text.
    
    Returns:
    True if clipboard has text, False otherwise
    """

def SDL_SetPrimarySelectionText(text: bytes) -> int:
    """
    Put UTF-8 text into the primary selection (Unix/Linux only).
    
    Parameters:
    - text: text to set as primary selection
    
    Returns:
    0 on success, negative on error
    """

def SDL_GetPrimarySelectionText() -> bytes:
    """Get UTF-8 text from the primary selection (Unix/Linux only)."""

def SDL_HasPrimarySelectionText() -> bool:
    """Check whether the primary selection has text (Unix/Linux only)."""

File System Paths

Functions for getting standard application directories and paths.

def SDL_GetBasePath() -> bytes:
    """
    Get the path where the application resides.
    
    Returns:
    Path to the application directory as bytes, or None on error
    """

def SDL_GetPrefPath(org: bytes, app: bytes) -> bytes:
    """
    Get the user-specific preferences directory for the application.
    
    Parameters:
    - org: organization name as bytes
    - app: application name as bytes
    
    Returns:
    Path to preferences directory as bytes, or None on error
    """

Platform Detection

Functions for detecting the current platform and system information.

def SDL_GetPlatform() -> bytes:
    """
    Get the name of the platform.
    
    Returns:
    Platform name as bytes (e.g., b"Windows", b"Mac OS X", b"Linux")
    """

Power Management

Functions for querying battery and power state information.

def SDL_GetPowerInfo(secs: int, pct: int) -> int:
    """
    Get current power supply details.
    
    Parameters:
    - secs: pointer to store seconds of battery life left (-1 if unknown)
    - pct: pointer to store percentage of battery life left (-1 if unknown)
    
    Returns:
    SDL_PowerState value indicating current power state
    """

Power State Constants

# Power states
SDL_POWERSTATE_UNKNOWN = 0      # Cannot determine power status
SDL_POWERSTATE_ON_BATTERY = 1   # Not plugged in, running on battery
SDL_POWERSTATE_NO_BATTERY = 2   # Plugged in, no battery available
SDL_POWERSTATE_CHARGING = 3     # Plugged in, charging battery
SDL_POWERSTATE_CHARGED = 4      # Plugged in, battery charged

Usage Examples

Clipboard Operations

import sdl2

# Initialize SDL
sdl2.SDL_Init(0)

# Check if clipboard has text
if sdl2.SDL_HasClipboardText():
    # Get clipboard text
    clipboard_text = sdl2.SDL_GetClipboardText()
    print(f"Clipboard contains: {clipboard_text.decode('utf-8')}")
else:
    print("Clipboard is empty")

# Set clipboard text
text_to_copy = "Hello from PySDL2!"
result = sdl2.SDL_SetClipboardText(text_to_copy.encode('utf-8'))
if result == 0:
    print("Text copied to clipboard successfully")
else:
    print("Failed to copy text to clipboard")

File System Paths

import sdl2
import os

# Initialize SDL
sdl2.SDL_Init(0)

# Get application base path
base_path = sdl2.SDL_GetBasePath()
if base_path:
    print(f"Application directory: {base_path.decode('utf-8')}")
    
    # Use base path for loading resources
    resource_path = os.path.join(base_path.decode('utf-8'), "assets", "image.png")
    print(f"Resource path: {resource_path}")

# Get preferences path
pref_path = sdl2.SDL_GetPrefPath(b"MyCompany", b"MyGame")
if pref_path:
    print(f"Preferences directory: {pref_path.decode('utf-8')}")
    
    # Use for saving config files, save games, etc.
    config_file = os.path.join(pref_path.decode('utf-8'), "config.ini")
    save_file = os.path.join(pref_path.decode('utf-8'), "savegame.dat")

Platform Detection

import sdl2

# Initialize SDL
sdl2.SDL_Init(0)

# Get platform name
platform = sdl2.SDL_GetPlatform()
platform_str = platform.decode('utf-8')

print(f"Running on: {platform_str}")

# Platform-specific code
if platform_str == "Windows":
    print("Windows-specific initialization")
elif platform_str == "Mac OS X":
    print("macOS-specific initialization")
elif platform_str == "Linux":
    print("Linux-specific initialization")
else:
    print(f"Unknown platform: {platform_str}")

Power Management

import sdl2
from ctypes import c_int, pointer

# Initialize SDL
sdl2.SDL_Init(0)

# Get power information  
seconds_left = c_int()
percentage_left = c_int()

power_state = sdl2.SDL_GetPowerInfo(pointer(seconds_left), pointer(percentage_left))

# Interpret power state
if power_state == sdl2.SDL_POWERSTATE_UNKNOWN:
    print("Power state unknown")
elif power_state == sdl2.SDL_POWERSTATE_ON_BATTERY:
    print("Running on battery")
    if seconds_left.value >= 0:
        minutes = seconds_left.value // 60
        print(f"Battery time remaining: {minutes} minutes")
    if percentage_left.value >= 0:
        print(f"Battery level: {percentage_left.value}%")
elif power_state == sdl2.SDL_POWERSTATE_NO_BATTERY:
    print("Plugged in, no battery")
elif power_state == sdl2.SDL_POWERSTATE_CHARGING:
    print("Plugged in, charging")
    if percentage_left.value >= 0:
        print(f"Battery level: {percentage_left.value}%")
elif power_state == sdl2.SDL_POWERSTATE_CHARGED:
    print("Plugged in, battery fully charged")

Cross-Platform File Handling

import sdl2
import os

def get_app_data_path(app_name):
    """Get appropriate data directory for the application"""
    # Get platform
    platform = sdl2.SDL_GetPlatform().decode('utf-8')
    
    if platform == "Windows":
        # Use preferences path on Windows
        return sdl2.SDL_GetPrefPath(b"", app_name.encode('utf-8'))
    else:
        # Use preferences path on other platforms too
        return sdl2.SDL_GetPrefPath(b"", app_name.encode('utf-8'))

def save_game_data(app_name, data):
    """Save game data to appropriate location"""
    data_path = get_app_data_path(app_name)
    if data_path:
        save_file = os.path.join(data_path.decode('utf-8'), "savegame.dat")
        with open(save_file, 'w') as f:
            f.write(data)
        print(f"Game saved to: {save_file}")
        return True
    return False

# Usage
if save_game_data("MyGame", "player_level=5\nscore=1500"):
    print("Game saved successfully")

Types

# Power state enumeration
SDL_PowerState = int
"""
Power state values:
- SDL_POWERSTATE_UNKNOWN: Cannot determine power status
- SDL_POWERSTATE_ON_BATTERY: Not plugged in, running on battery  
- SDL_POWERSTATE_NO_BATTERY: Plugged in, no battery available
- SDL_POWERSTATE_CHARGING: Plugged in, charging battery
- SDL_POWERSTATE_CHARGED: Plugged in, battery charged
"""

Install with Tessl CLI

npx tessl i tessl/pypi-pysdl2

docs

audio.md

events-input.md

file-io.md

fonts-text.md

graphics-rendering.md

image-processing.md

index.md

joystick-input.md

sprites-animation.md

system-utils.md

timer.md

window-display.md

tile.json