File: common.py

package info (click to toggle)
pysdl2 0.9.9%2Bdfsg1-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,276 kB
  • sloc: python: 18,592; makefile: 148; sh: 40
file content (122 lines) | stat: -rw-r--r-- 3,172 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""SDL2 helper functions."""
import ctypes
from .. import SDL_Init, SDL_Quit, SDL_QuitSubSystem, SDL_WasInit, \
    SDL_INIT_VIDEO, error, events, timer

_HASSDLTTF = True
try:
    from .. import sdlttf
except ImportError:
    _HASSDLTTF = False
_HASSDLIMAGE = True
try:
    from .. import sdlimage
except ImportError:
    _HASSDLIMAGE = False

__all__ = ["SDLError", "init", "quit", "get_events", "TestEventProcessor"]


class SDLError(Exception):
    """An SDL2-specific exception class."""

    def __init__(self, msg=None):
        """Creates a new SDLError instance with the specified message.

        If no msg is passed, it will try to get the current SDL2 error via
        :func:`sdl2.SDL_GetError`.

        """
        super(SDLError, self).__init__()
        self.msg = msg
        if not msg:
            self.msg = error.SDL_GetError()
            error.SDL_ClearError()

    def __str__(self):
        return repr(self.msg)


def init():
    """Initializes the SDL2 video subsystem.

    Raises an :exc:`SDLError` if the SDL2 video subsystem cannot be
    initialized.

    """
    # TODO: More subsystems?
    if SDL_Init(SDL_INIT_VIDEO) != 0:
        raise SDLError()


def quit():
    """Quits the SDL2 video subysystem.

    If no other subsystems are active, this will also call
    :func:`sdl2.SDL_Quit`, :func:`sdlttf.TTF_Quit` and
    :func:`sdlimage.IMG_Quit`.

    """
    # TODO: More subsystems? Also, is TTF_WasInit always 1?
    SDL_QuitSubSystem(SDL_INIT_VIDEO)
    if SDL_WasInit(0) != 0:
        if _HASSDLTTF and sdlttf.TTF_WasInit() == 1:
            sdlttf.TTF_Quit()
        if _HASSDLIMAGE:
            sdlimage.IMG_Quit()
        SDL_Quit()


def get_events():
    """Gets all SDL events that are currently on the event queue.

    Returns:
        :obj:`List`: A list of all :obj:`~sdl2.SDL_Event` objects currently in
            the event queue.
    
    """
    events.SDL_PumpEvents()

    evlist = []
    SDL_PeepEvents = events.SDL_PeepEvents

    op = events.SDL_GETEVENT
    first = events.SDL_FIRSTEVENT
    last = events.SDL_LASTEVENT

    while True:
        evarray = (events.SDL_Event * 10)()
        ptr = ctypes.cast(evarray, ctypes.POINTER(events.SDL_Event))
        ret = SDL_PeepEvents(ptr, 10, op, first, last)
        if ret <= 0:
            break
        evlist += list(evarray)[:ret]
        if ret < 10:
            break

    return evlist


class TestEventProcessor(object):
    """A simple event processor for testing purposes."""

    def run(self, window):
        """Starts an event loop without actually processing any event.
        
        This method will run endlessly until an ``SDL_QUIT`` event occurs.

        Args:
            window (:obj:`sdl2.ext.Window`): The window within which to run
                the test event loop.
        
        """
        event = events.SDL_Event()
        running = True
        while running:
            ret = events.SDL_PollEvent(ctypes.byref(event), 1)
            if ret == 1:
                if event.type == events.SDL_QUIT:
                    running = False
                    break
            window.refresh()
            timer.SDL_Delay(10)