Source code for displaydev.sdldisplay

# SPDX-FileCopyrightText: 2024 Brad Barnett
#
# SPDX-License-Identifier: MIT

"""
displaydev.sdldisplay — SDL2 desktop display driver.
"""

import os
import struct
import sys

import usdl2

from displaydev import _DESKTOP_WINDOW_CHROME_H, color_rgb
from displaydev._desktop import DesktopDisplay, FrameRecorderMixin
import events
import keys

_JOYSTICK_API = (
    "SDL_InitSubSystem",
    "SDL_JoystickClose",
    "SDL_JoystickInstanceID",
    "SDL_JoystickOpen",
    "SDL_NumJoysticks",
)
_HAS_JOYSTICK_API = all(hasattr(usdl2, name) for name in _JOYSTICK_API)

# Linux c_lflag bits (MicroPython termios has no ECHO/ICANON constants).
_TTY_ICANON = 0x002
_TTY_ECHO = 0x008
_saved_tty = None


def _save_tty() -> None:
    """Save stdin termios before SDL_Init may alter the controlling terminal."""
    global _saved_tty
    try:
        import os
        import termios

        if os.isatty(0):
            _saved_tty = termios.tcgetattr(0)
    except Exception:
        _saved_tty = None


def _restore_tty() -> None:
    """Restore stdin termios saved at SDL init."""
    global _saved_tty
    if _saved_tty is None:
        return
    try:
        import termios

        termios.tcsetattr(0, termios.TCSANOW, _saved_tty)
    except Exception:
        pass
    _saved_tty = None


def _ensure_tty_sane() -> None:
    """
    Ensure canonical mode and echo are enabled before returning a TTY to the shell.

    SDL_Quit restores the snapshot taken at SDL_Init, which may still reflect a
    no-echo REPL state.  Forcing sane flags avoids a shell prompt that accepts
    input but does not echo typed characters.
    """
    try:
        import termios

        attr = termios.tcgetattr(0)
        attr[3] |= _TTY_ICANON | _TTY_ECHO
        termios.tcsetattr(0, termios.TCSANOW, attr)
    except Exception:
        try:
            import os
            import sys

            # ``stty`` is Unix-only; ``os.system`` on win32 spawns CMD.EXE and
            # errors when micropython.exe is launched from a WSL UNC cwd.
            if sys.platform == "win32":
                return
            os.system("stty sane 2>/dev/null")
        except Exception:
            pass


_event = usdl2.SDL_Event()
_displays = []

# Open joystick handles, keyed by SDL instance id, kept referenced so SDL keeps
# delivering their events.
_joysticks = {}


def _init_joysticks() -> None:
    """
    Initialize the joystick subsystem and open all connected joysticks.

    Joysticks must be opened for SDL to deliver their events.  Devices connected
    after startup are not hot-plugged (connect controllers before launching).
    Failures are ignored so a missing/headless joystick subsystem never breaks
    the display.
    """
    if not _HAS_JOYSTICK_API:
        return
    try:
        if usdl2.SDL_InitSubSystem(usdl2.SDL_INIT_JOYSTICK) != 0:
            return
        for i in range(usdl2.SDL_NumJoysticks()):
            handle = usdl2.SDL_JoystickOpen(i)
            if handle:
                _joysticks[usdl2.SDL_JoystickInstanceID(handle)] = handle
    except Exception:
        pass


def _close_joysticks() -> None:
    """Close any opened joysticks."""
    if not _HAS_JOYSTICK_API:
        return
    for handle in _joysticks.values():
        try:
            usdl2.SDL_JoystickClose(handle)
        except Exception:
            pass
    _joysticks.clear()


def _hat_xy(value):
    """Convert an SDL hat bitmask to an (x, y) tuple matching PyGame's get_hat()."""
    x = (1 if value & usdl2.SDL_HAT_RIGHT else 0) - (1 if value & usdl2.SDL_HAT_LEFT else 0)
    y = (1 if value & usdl2.SDL_HAT_UP else 0) - (1 if value & usdl2.SDL_HAT_DOWN else 0)
    return (x, y)


_SDL_WINDOWEVENT = getattr(usdl2, "SDL_WINDOWEVENT", 0x200)
_SDL_WINDOWEVENT_CLOSE = getattr(usdl2, "SDL_WINDOWEVENT_CLOSE", 0xE)


def _display_for_window_id(window_id):
    """Return the `SDLDisplay` for ``window_id``, or ``None``."""
    if window_id is None:
        return None
    for display in _displays:
        if getattr(display, "_window_id", None) == window_id:
            return display
    return None


def _panel_size(window_id=None):
    """Logical panel size for normalizing SDL finger coords (0..1 → pixels)."""
    d = _display_for_window_id(window_id)
    if d is None and _displays:
        d = _displays[0]
    if d is not None:
        return int(d.width), int(d.height)
    return 320, 240


def _handle_window_event(e):
    """Handle SDL_WINDOWEVENT; may return an events event or ``None``."""
    wev = e.window.event
    if wev != _SDL_WINDOWEVENT_CLOSE:
        return None
    # The dummy video driver has no real window a user could close, yet it
    # can surface a spurious WINDOWEVENT_CLOSE right after creation --
    # observed quitting apps ~0.1s in under SDL_VIDEODRIVER=dummy (and,
    # inverted, hanging forever on older lvgl wheels). Headless runs decide
    # their own lifetime; ignore synthetic close events there.
    if os.environ.get("SDL_VIDEODRIVER", "").lower() in ("dummy", "offscreen"):
        return None
    wid = int(e.window.windowID)
    display = _display_for_window_id(wid)
    if display is None or display is _displays[0] or len(_displays) <= 1:
        return events.Quit(events.QUIT)
    app = getattr(display, "app", None)
    if app is not None and callable(getattr(app, "remove_display", None)):
        app.remove_display(display)
    else:
        try:
            display.quit()
        except Exception:
            pass
        try:
            _displays.remove(display)
        except ValueError:
            pass
    return None


def _process_sdl_event(raw):
    """Convert one polled SDL event to events, or ``None`` to skip."""
    e = usdl2.SDL_Event(raw)
    if e.type == _SDL_WINDOWEVENT:
        return _handle_window_event(e)
    if e.type in events.filter:
        return _convert(e)
    return None


[docs] def poll_event(): """ Poll for one pending event. Returns: Optional[events]: One events event, or ``None``. """ global _event _flush_pending_displays() if usdl2.SDL_PollEvent(_event): return _process_sdl_event(_event) return None
[docs] def get_events(): """ Drain all pending events from the SDL queue. Returns: list | None: A list of events, or ``None`` if the queue was empty. """ global _event _flush_pending_displays() eventlist = [] while usdl2.SDL_PollEvent(_event): evt = _process_sdl_event(_event) if evt is not None: eventlist.append(evt) return eventlist if len(eventlist) > 0 else None
def _flush_pending_displays(): for display in tuple(_displays): if display._show_pending: display._flush_pending_show() def _convert(e): # Convert an SDL event to a Pygame event if e.type == usdl2.SDL_MOUSEMOTION: l = 1 if e.motion.state & usdl2.SDL_BUTTON_LMASK else 0 # noqa: E741 m = 1 if e.motion.state & usdl2.SDL_BUTTON_MMASK else 0 r = 1 if e.motion.state & usdl2.SDL_BUTTON_RMASK else 0 evt = events.Motion( e.type, (e.motion.x, e.motion.y), (e.motion.xrel, e.motion.yrel), (l, m, r), e.motion.which != 0, e.motion.windowID, ) elif e.type in (usdl2.SDL_MOUSEBUTTONDOWN, usdl2.SDL_MOUSEBUTTONUP): evt = events.Button( e.type, (e.button.x, e.button.y), e.button.button, e.button.which != 0, e.button.windowID, ) elif e.type in (usdl2.SDL_FINGERDOWN, usdl2.SDL_FINGERUP, usdl2.SDL_FINGERMOTION): wid = int(e.tfinger.windowID) w, h = _panel_size(wid) fx = e.tfinger.x fy = e.tfinger.y evt = events.Finger( e.type, (int(fx * w), int(fy * h)), int(e.tfinger.fingerId), wid, ) elif e.type == usdl2.SDL_MOUSEWHEEL: evt = events.Wheel( e.type, e.wheel.direction != 0, e.wheel.x, e.wheel.y, e.wheel.preciseX, e.wheel.preciseY, e.wheel.which != 0, e.wheel.windowID, ) elif e.type in (usdl2.SDL_KEYDOWN, usdl2.SDL_KEYUP): # Match browser backends: ignore OS auto-repeat KEYDOWNs. Consumers that # need held-key repeat (e.g. LVGL textarea) use their own long-press path. if e.type == usdl2.SDL_KEYDOWN and getattr(e.key, "repeat", 0): return None sym = e.key.keysym.sym name = usdl2.SDL_GetKeyName(sym) # Some hosts (notably WSLg/RDP) report letters as # SDL_SCANCODE_TO_KEYCODE(scancode) (bit 0x40000000) instead of ASCII. if isinstance(sym, int) and (sym & 0x40000000) and name: if len(name) == 1: sym = ord(name.lower()) elif name == "Space": sym = 32 elif name == "Return": sym = 13 elif name == "Backspace": sym = 8 elif name == "Escape": sym = 27 elif name == "Tab": sym = 9 elif name == "Delete": sym = 127 evt = events.Key( e.type, name, sym, e.key.keysym.mod, e.key.keysym.scancode, e.key.windowID, ) elif e.type == usdl2.SDL_JOYAXISMOTION: # Normalize the Sint16 axis value to -1.0..1.0 to match PyGame/Gamepad. evt = events.JoyAxisMotion(e.type, e.jaxis.which, e.jaxis.axis, e.jaxis.value / 32767) elif e.type == usdl2.SDL_JOYBALLMOTION: evt = events.JoyBallMotion( e.type, e.jball.which, e.jball.ball, (e.jball.xrel, e.jball.yrel) ) elif e.type == usdl2.SDL_JOYHATMOTION: evt = events.JoyHatMotion(e.type, e.jhat.which, e.jhat.hat, _hat_xy(e.jhat.value)) elif e.type == usdl2.SDL_JOYBUTTONDOWN: evt = events.JoyButtonDown(e.type, e.jbutton.which, e.jbutton.button) elif e.type == usdl2.SDL_JOYBUTTONUP: evt = events.JoyButtonUp(e.type, e.jbutton.which, e.jbutton.button) elif e.type == usdl2.SDL_QUIT: evt = events.Quit(e.type) else: evt = events.Unknown(e.type) return evt def retcheck(retvalue): # Check the return value of an SDL function and raise an exception if it's not 0 if retvalue: raise RuntimeError(usdl2.SDL_GetError()) def _sdl_init_display(): """Init SDL for desktop display; video first so usable desktop bounds work.""" retcheck(usdl2.SDL_Init(usdl2.SDL_INIT_VIDEO)) extra = usdl2.SDL_INIT_EVERYTHING & ~usdl2.SDL_INIT_VIDEO if extra: retcheck(usdl2.SDL_InitSubSystem(extra)) def _desktop_usable(display_index=0): """Return ``(x, y, w, h)`` of the usable desktop area, or zeros if unknown. Prefers ``SDL_GetDisplayUsableBounds`` (excludes taskbar / dock). Falls back to the full desktop mode at ``(0, 0)``. """ display_index = int(display_index) try: get_bounds = usdl2.SDL_GetDisplayUsableBounds get_mode = usdl2.SDL_GetDesktopDisplayMode except AttributeError: return 0, 0, 0, 0 try: rect = bytearray(16) if get_bounds(display_index, rect) == 0: x, y, w, h = struct.unpack_from("<iiii", rect, 0) if w > 0 and h > 0: return x, y, w, h mode = bytearray(16) if get_mode(display_index, mode) == 0: w, h = struct.unpack_from("<ii", mode, 4) if w > 0 and h > 0: return 0, 0, w, h except Exception: pass return 0, 0, 0, 0 def _window_position(win_w, win_h, x, y, usable=None): """Center a window in the usable work area when *x*/*y* request centering.""" centered = x == usdl2.SDL_WINDOWPOS_CENTERED and y == usdl2.SDL_WINDOWPOS_CENTERED if not centered: return x, y if usable is None: usable = _desktop_usable() ux, uy, uw, uh = usable if uw <= 0 or uh <= 0: return x, y # Leave title-bar chrome above the client so the frame stays in the work area. x = ux + max(0, (uw - win_w) // 2) y = uy + _DESKTOP_WINDOW_CHROME_H + max(0, (uh - _DESKTOP_WINDOW_CHROME_H - win_h) // 2) return x, y def _hard_process_exit(code: int = 0) -> None: """Terminate immediately without SDL teardown (kit subprocesses).""" try: import ffi ffi.open("libc.so.6").func("v", "_exit", "i")(code) except Exception: pass try: import os os._exit(code) except Exception: pass raise SystemExit(code)
[docs] class SDLDisplay(FrameRecorderMixin, DesktopDisplay): """Emulate an LCD window with SDL2 (via ``usdl2``). Provides scrolling and rotation similar to a panel driver. The SDL texture acts as the LCD's internal memory. Scale is reduced automatically when the window would not fit the desktop work area. Args: width (int, optional): Panel width in pixels. Defaults to 320. height (int, optional): Panel height in pixels. Defaults to 240. rotation (int, optional): Rotation in degrees. Defaults to 0. color_depth (int, optional): Bits per pixel (16/24/32). Defaults to 16. title (str, optional): Window title. Defaults to ``"SDL2 Display"``. scale (float, optional): Window scale factor. Defaults to 1.0. window_flags (int, optional): ``SDL_WINDOW_*`` flags. render_flags (int, optional): ``SDL_RENDERER_*`` flags. x (int, optional): Window X (default centered). y (int, optional): Window Y (default centered). quiet (bool): Suppress init chatter when True. Attributes: needs_refresh (bool): True — ``appdev.App`` drives periodic ``show()``. """ needs_refresh = True quit_chord = (keys.K_q, keys.KMOD_CTRL) def __init__( self, width=320, height=240, rotation=0, color_depth=16, title="SDL2 Display", scale=1.0, window_flags=usdl2.SDL_WINDOW_SHOWN, render_flags=usdl2.SDL_RENDERER_ACCELERATED | usdl2.SDL_RENDERER_PRESENTVSYNC, x=usdl2.SDL_WINDOWPOS_CENTERED, y=usdl2.SDL_WINDOWPOS_CENTERED, *, quiet=False, ): self._width = width self._height = height self._rotation = rotation self.color_depth = color_depth self._title = title self._window_flags = window_flags self._scale = scale self.touch_scale = 1.0 self._buffer = None self._render_dirty = False self._show_pending = False self._requires_byteswap = False self._frame_recorder = None # Determine the pixel format if color_depth == 32: self._px_format = usdl2.SDL_PIXELFORMAT_ARGB8888 elif color_depth == 24: self._px_format = usdl2.SDL_PIXELFORMAT_RGB888 elif color_depth == 16: self._px_format = usdl2.SDL_PIXELFORMAT_RGB565 else: raise ValueError("Unsupported color_depth") _save_tty() _sdl_init_display() usable = _desktop_usable() _ux, _uy, desktop_w, desktop_h = usable self._scale = self._fit_scale(desktop_w, desktop_h, quiet) _init_joysticks() win_w = int(self.width * self._scale) win_h = int(self.height * self._scale) x, y = _window_position(win_w, win_h, x, y, usable=usable) self._window = usdl2.SDL_CreateWindow( self._title.encode(), x, y, win_w, win_h, self._window_flags, ) if not self._window: raise RuntimeError(f"{usdl2.SDL_GetError()}") get_id = getattr(usdl2, "SDL_GetWindowID", None) self._window_id = int(get_id(self._window)) if get_id is not None else None self.app = None self._lock_window_size() self._renderer = usdl2.SDL_CreateRenderer(self._window, -1, render_flags) if not self._renderer and (render_flags & usdl2.SDL_RENDERER_ACCELERATED): render_flags = ( render_flags & ~usdl2.SDL_RENDERER_ACCELERATED ) | usdl2.SDL_RENDERER_SOFTWARE self._renderer = usdl2.SDL_CreateRenderer(self._window, -1, render_flags) if not self._renderer: raise RuntimeError(f"{usdl2.SDL_GetError()}") self._buffer = usdl2.SDL_CreateTexture( self._renderer, self._px_format, usdl2.SDL_TEXTUREACCESS_TARGET, self.width, self.height, ) if not self._buffer: raise RuntimeError(f"{usdl2.SDL_GetError()}") retcheck(usdl2.SDL_SetTextureBlendMode(self._buffer, usdl2.SDL_BLENDMODE_NONE)) _displays.append(self) super().__init__(quiet=quiet) # System-wide SDL queue drain (same callable on every SDLDisplay). self.get_events = get_events ############### Required API Methods ################ def _lock_window_size(self) -> None: """Keep the OS window fixed to the scaled panel size (not user-resizable). When rotation swaps the aspect ratio, the previous min==max lock rejects ``SetWindowSize`` and then ``SetWindowMaximumSize`` (max would be smaller than the old min). Raise max, relax min, resize, then re-lock. On Android the Activity already owns a single SurfaceView-backed window; ``SetWindowSize`` / min==max locks fight that surface and can break presents. """ if sys.platform == "android": return w = int(self.width * self._scale) h = int(self.height * self._scale) usdl2.SDL_SetWindowResizable(self._window, 0) # Raise max first so aspect swaps are not blocked by the old min==max lock. # SDL rejects 0 for min/max on this build; use 1 and a large ceiling. usdl2.SDL_SetWindowMaximumSize(self._window, 16384, 16384) usdl2.SDL_SetWindowMinimumSize(self._window, 1, 1) usdl2.SDL_SetWindowSize(self._window, w, h) usdl2.SDL_SetWindowMinimumSize(self._window, w, h) usdl2.SDL_SetWindowMaximumSize(self._window, w, h)
[docs] def init(self) -> None: """ Initializes the display instance. Called by __init__ and rotation setter. """ self._lock_window_size() retcheck(usdl2.SDL_RenderSetLogicalSize(self._renderer, self.width, self.height)) # Full-height scroll region, no repaint during init. self._reset_vscroll()
[docs] def blit_rect(self, buffer: memoryview, x: int, y: int, w: int, h: int): """ Blit a buffer into the display texture. Compositing is deferred until ``show()``. """ if not self._sdl_active(): return (x, y, w, h) pitch = int(w * self.color_depth // 8) need = pitch * h buflen = len(buffer) if buflen < need: raise ValueError("Buffer size does not match dimensions") # Prefix is enough (PGDisplay / MCU blitters index w*h pixels). Examples # often pass a larger scratch framebuffer with a smaller blit height. if buflen > need: buffer = memoryview(buffer)[:need] blitRect = usdl2.SDL_Rect(x, y, w, h) retcheck(usdl2.SDL_UpdateTexture(self._buffer, blitRect, buffer, pitch)) self._render_dirty = True return (x, y, w, h)
[docs] def fill_rect(self, x: int, y: int, w: int, h: int, c: int): """ Fill a rectangle in the display texture. Compositing is deferred until ``show()``. """ fillRect = usdl2.SDL_Rect(x, y, w, h) r, g, b = color_rgb(c) try: retcheck(usdl2.SDL_SetRenderTarget(self._renderer, None)) except RuntimeError: pass retcheck( usdl2.SDL_SetRenderTarget(self._renderer, self._buffer) ) # Set the render target to the texture retcheck( usdl2.SDL_SetRenderDrawColor(self._renderer, r, g, b, 255) ) # Set the color to fill the rectangle retcheck( usdl2.SDL_RenderFillRect(self._renderer, fillRect) ) # Fill the rectangle on the texture retcheck( usdl2.SDL_SetRenderTarget(self._renderer, None) ) # Reset the render target back to the window self._render_dirty = True return (x, y, w, h)
[docs] def pixel(self, x: int, y: int, c: int): """ Set a pixel on the display. Args: x (int): The x-coordinate of the pixel. y (int): The y-coordinate of the pixel. c (int): The color of the pixel. Returns: (tuple): A tuple containing the x, y values. """ return self.blit_rect(bytearray(c.to_bytes(2, "little")), x, y, 1, 1)
############### API Method Overrides ################ def _rotation_helper(self, value): """ Creates a new texture to use as the buffer and copies the old one, applying rotation with SDL_RenderCopyEx. Destroys the old buffer. Args: value (int): The new rotation value. """ if (angle := (value % 360) - (self._rotation % 360)) != 0: # 90/270 swap dims; 180 keeps the current logical size. if abs(angle) % 180 == 0: new_w, new_h = self.width, self.height else: new_w, new_h = self.height, self.width tempBuffer = usdl2.SDL_CreateTexture( self._renderer, self._px_format, usdl2.SDL_TEXTUREACCESS_TARGET, new_w, new_h, ) if not tempBuffer: raise RuntimeError(f"{usdl2.SDL_GetError()}") retcheck(usdl2.SDL_SetTextureBlendMode(tempBuffer, usdl2.SDL_BLENDMODE_NONE)) retcheck(usdl2.SDL_SetRenderTarget(self._renderer, tempBuffer)) if abs(angle) != 180: dstrect = usdl2.SDL_Rect( (new_w - self.width) // 2, (new_h - self.height) // 2, self.width, self.height, ) else: dstrect = None retcheck( usdl2.SDL_RenderCopyEx(self._renderer, self._buffer, None, dstrect, angle, None, 0) ) retcheck(usdl2.SDL_SetRenderTarget(self._renderer, None)) retcheck(usdl2.SDL_DestroyTexture(self._buffer)) self._buffer = tempBuffer self._render_dirty = True ############### Class Specific Methods ############## def _sdl_active(self) -> bool: """True while SDL video is initialized and this driver is live.""" if getattr(self, "_deinitialized", False): return False return self._renderer is not None and self._window is not None def _read_texture_rgb(self): """Read the logical display texture as packed RGB24.""" width = self.width height = self.height pixels = bytearray(width * height * 3) retcheck(usdl2.SDL_SetRenderTarget(self._renderer, self._buffer)) try: usdl2.SDL_RenderReadPixels( self._renderer, None, usdl2.SDL_PIXELFORMAT_RGB24, pixels, width * 3, ) finally: retcheck(usdl2.SDL_SetRenderTarget(self._renderer, None)) return bytes(pixels) def _visible_rgb(self): """Return the scrolled and scaled visible frame as RGB24.""" width = self.width height = self.height stride = width * 3 source = self._read_texture_rgb() y_start = self.vscsad() if y_start: rows = [] rows.extend(range(self._tfa)) rows.extend(range(y_start, self._tfa + self._vsa)) rows.extend(range(self._tfa, y_start)) rows.extend(range(self._tfa + self._vsa, height)) source = b"".join(source[y * stride : (y + 1) * stride] for y in rows) out_width = int(width * self._scale) out_height = int(height * self._scale) if out_width == width and out_height == height: return source, width, height integer_scale = int(self._scale) if ( integer_scale == self._scale and out_width == width * integer_scale and out_height == height * integer_scale ): scaled = bytearray() for src_y in range(height): row = source[src_y * stride : (src_y + 1) * stride] expanded = bytearray() for src_x in range(0, stride, 3): expanded.extend(row[src_x : src_x + 3] * integer_scale) scaled.extend(expanded * integer_scale) return bytes(scaled), out_width, out_height scaled = bytearray(out_width * out_height * 3) for out_y in range(out_height): src_y = min(height - 1, int(out_y / self._scale)) src_row = src_y * stride out_row = out_y * out_width * 3 for out_x in range(out_width): src_x = min(width - 1, int(out_x / self._scale)) * 3 dst = out_row + out_x * 3 scaled[dst : dst + 3] = source[src_row + src_x : src_row + src_x + 3] return bytes(scaled), out_width, out_height
[docs] def render(self, renderRect=None): """ Composite the logical framebuffer to the window. Called from ``show()`` when draws are pending. """ if not self._sdl_active(): return # Single SDL_RenderCopy was disabled: not working on Chromebooks, Ubuntu, Raspberry Pi OS. y_start = self.vscsad() if self._tfa > 0: tfaRect = usdl2.SDL_Rect(0, 0, self.width, self._tfa) retcheck(usdl2.SDL_RenderCopy(self._renderer, self._buffer, tfaRect, tfaRect)) vsaTopHeight = self._vsa + self._tfa - y_start vsaTopSrcRect = usdl2.SDL_Rect(0, y_start, self.width, vsaTopHeight) vsaTopDestRect = usdl2.SDL_Rect(0, self._tfa, self.width, vsaTopHeight) retcheck(usdl2.SDL_RenderCopy(self._renderer, self._buffer, vsaTopSrcRect, vsaTopDestRect)) vsaBtmHeight = self._vsa - vsaTopHeight vsaBtmSrcRect = usdl2.SDL_Rect(0, self._tfa, self.width, vsaBtmHeight) vsaBtmDestRect = usdl2.SDL_Rect(0, self._tfa + vsaTopHeight, self.width, vsaBtmHeight) retcheck(usdl2.SDL_RenderCopy(self._renderer, self._buffer, vsaBtmSrcRect, vsaBtmDestRect)) if self._bfa > 0: bfaRect = usdl2.SDL_Rect(0, self._tfa + self._vsa, self.width, self._bfa) retcheck(usdl2.SDL_RenderCopy(self._renderer, self._buffer, bfaRect, bfaRect)) self._render_dirty = False
[docs] def show(self, _timer=None) -> None: """ Show the display. """ if not self._sdl_active(): return self._show_pending = True try: self._flush_pending_show() except MemoryError: return
def _flush_pending_show(self): if not self._sdl_active(): return # Recomposite every frame, even when nothing was drawn. After # SDL_RenderPresent the backbuffer is undefined: on GLES (Android) the # swap chain rotates through two or three buffers, so presenting a # frame that wasn't redrawn shows a stale or black buffer, and the # screen flickers at the refresh rate (android-runner#8). Clearing # first also blanks the letterbox bars, which otherwise show garbage. retcheck(usdl2.SDL_SetRenderDrawColor(self._renderer, 0, 0, 0, 255)) retcheck(usdl2.SDL_RenderClear(self._renderer)) self.render() recorder = self._frame_recorder if recorder is not None: pixels, _width, _height = self._visible_rgb() recorder.write(pixels) usdl2.SDL_RenderPresent(self._renderer) self._show_pending = False
[docs] def capture_rgb(self): """Return the visible window as ``(RGB24 bytes, width, height)``.""" if not self._sdl_active(): raise RuntimeError("SDL display is not active") read_pixels = getattr(usdl2, "SDL_RenderReadPixels", None) if read_pixels is None: raise RuntimeError("usdl2 does not provide SDL_RenderReadPixels") return self._visible_rgb()
def _deinit(self) -> None: """Release this window; call ``SDL_Quit`` only when no SDLDisplay remains.""" self.close_frame_recorder() try: _displays.remove(self) except ValueError: pass if self._buffer is not None: usdl2.SDL_DestroyTexture(self._buffer) self._buffer = None if self._renderer is not None: usdl2.SDL_DestroyRenderer(self._renderer) self._renderer = None if self._window is not None: usdl2.SDL_DestroyWindow(self._window) self._window = None self._window_id = None self.app = None # Keep SDL (and the primary window) alive while other displays remain — # same policy as PGDisplay._deinit. if _displays: return _close_joysticks() usdl2.SDL_Quit() _restore_tty() _ensure_tty_sane()
[docs] def quit(self, code: int = 0, force: bool = False) -> None: """Release SDL resources (REPL-safe unless ``force=True``).""" if not force: self.deinit() return try: self.deinit() except Exception: pass try: _ensure_tty_sane() except Exception: pass _hard_process_exit(code)
[docs] def force_quit(self, code: int = 0) -> None: """Release SDL resources then hard-exit the process. On MicroPython and CircuitPython, ``SDL_Quit`` during subprocess shutdown can SIGSEGV; skip SDL teardown and ``_exit`` immediately after restoring the TTY (kit harnesses and other short-lived desktop runs). """ import sys if sys.implementation.name in ("micropython", "circuitpython"): try: _restore_tty() _ensure_tty_sane() except Exception: pass _hard_process_exit(code) self.quit(code, force=True)