Skip to content

Commit 01c9bb6

Browse files
committed
Move tcod.sdl internals to a sub-module.
To keep things out of a potential namespace.
1 parent ce0ea64 commit 01c9bb6

File tree

8 files changed

+133
-131
lines changed

8 files changed

+133
-131
lines changed

tcod/sdl/__init__.py

Lines changed: 1 addition & 125 deletions
Original file line numberDiff line numberDiff line change
@@ -1,128 +1,4 @@
1-
from __future__ import annotations
2-
3-
import logging
4-
import sys as _sys
5-
from dataclasses import dataclass
1+
"""tcod.sdl package."""
62
from pkgutil import extend_path
7-
from types import TracebackType
8-
from typing import Any, Callable, TypeVar
9-
10-
from tcod.loader import ffi, lib
113

124
__path__ = extend_path(__path__, __name__)
13-
14-
T = TypeVar("T")
15-
16-
logger = logging.getLogger("tcod.sdl")
17-
18-
_LOG_PRIORITY = {
19-
1: logging.DEBUG, # SDL_LOG_PRIORITY_VERBOSE
20-
2: logging.DEBUG, # SDL_LOG_PRIORITY_DEBUG
21-
3: logging.INFO, # SDL_LOG_PRIORITY_INFO
22-
4: logging.WARNING, # SDL_LOG_PRIORITY_WARN
23-
5: logging.ERROR, # SDL_LOG_PRIORITY_ERROR
24-
6: logging.CRITICAL, # SDL_LOG_PRIORITY_CRITICAL
25-
}
26-
27-
_LOG_CATEGORY = {
28-
int(lib.SDL_LOG_CATEGORY_APPLICATION): "APPLICATION",
29-
int(lib.SDL_LOG_CATEGORY_ERROR): "ERROR",
30-
int(lib.SDL_LOG_CATEGORY_ASSERT): "ASSERT",
31-
int(lib.SDL_LOG_CATEGORY_SYSTEM): "SYSTEM",
32-
int(lib.SDL_LOG_CATEGORY_AUDIO): "AUDIO",
33-
int(lib.SDL_LOG_CATEGORY_VIDEO): "VIDEO",
34-
int(lib.SDL_LOG_CATEGORY_RENDER): "RENDER",
35-
int(lib.SDL_LOG_CATEGORY_INPUT): "INPUT",
36-
int(lib.SDL_LOG_CATEGORY_TEST): "TEST",
37-
int(lib.SDL_LOG_CATEGORY_CUSTOM): "",
38-
}
39-
40-
41-
@dataclass
42-
class _UnraisableHookArgs:
43-
exc_type: type[BaseException]
44-
exc_value: BaseException | None
45-
exc_traceback: TracebackType | None
46-
err_msg: str | None
47-
object: object
48-
49-
50-
class _ProtectedContext:
51-
def __init__(self, obj: object = None) -> None:
52-
self.obj = obj
53-
54-
def __enter__(self) -> None:
55-
pass
56-
57-
def __exit__(
58-
self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
59-
) -> bool:
60-
if exc_type is None:
61-
return False
62-
if _sys.version_info < (3, 8):
63-
return False
64-
_sys.unraisablehook(_UnraisableHookArgs(exc_type, value, traceback, None, self.obj)) # type: ignore[arg-type]
65-
return True
66-
67-
68-
@ffi.def_extern() # type: ignore
69-
def _sdl_log_output_function(_userdata: None, category: int, priority: int, message_p: Any) -> None: # noqa: ANN401
70-
"""Pass logs sent by SDL to Python's logging system."""
71-
message = str(ffi.string(message_p), encoding="utf-8")
72-
logger.log(_LOG_PRIORITY.get(priority, 0), "%s:%s", _LOG_CATEGORY.get(category, ""), message)
73-
74-
75-
def _get_error() -> str:
76-
"""Return a message from SDL_GetError as a Unicode string."""
77-
return str(ffi.string(lib.SDL_GetError()), encoding="utf-8")
78-
79-
80-
def _check(result: int) -> int:
81-
"""Check if an SDL function returned without errors, and raise an exception if it did."""
82-
if result < 0:
83-
raise RuntimeError(_get_error())
84-
return result
85-
86-
87-
def _check_p(result: Any) -> Any:
88-
"""Check if an SDL function returned NULL, and raise an exception if it did."""
89-
if not result:
90-
raise RuntimeError(_get_error())
91-
return result
92-
93-
94-
if lib._sdl_log_output_function:
95-
lib.SDL_LogSetOutputFunction(lib._sdl_log_output_function, ffi.NULL)
96-
if __debug__:
97-
lib.SDL_LogSetAllPriority(lib.SDL_LOG_PRIORITY_VERBOSE)
98-
99-
100-
def _compiled_version() -> tuple[int, int, int]:
101-
return int(lib.SDL_MAJOR_VERSION), int(lib.SDL_MINOR_VERSION), int(lib.SDL_PATCHLEVEL)
102-
103-
104-
def _linked_version() -> tuple[int, int, int]:
105-
sdl_version = ffi.new("SDL_version*")
106-
lib.SDL_GetVersion(sdl_version)
107-
return int(sdl_version.major), int(sdl_version.minor), int(sdl_version.patch)
108-
109-
110-
def _version_at_least(required: tuple[int, int, int]) -> None:
111-
"""Raise an error if the compiled version is less than required. Used to guard recently defined SDL functions."""
112-
if required <= _compiled_version():
113-
return
114-
msg = f"This feature requires SDL version {required}, but tcod was compiled with version {_compiled_version()}"
115-
raise RuntimeError(msg)
116-
117-
118-
def _required_version(required: tuple[int, int, int]) -> Callable[[T], T]:
119-
if not lib: # Read the docs mock object.
120-
return lambda x: x
121-
if required <= _compiled_version():
122-
return lambda x: x
123-
124-
def replacement(*_args: Any, **_kwargs: Any) -> Any:
125-
msg = f"This feature requires SDL version {required}, but tcod was compiled with version {_compiled_version()}"
126-
raise RuntimeError(msg)
127-
128-
return lambda x: replacement # type: ignore[return-value]

tcod/sdl/_internal.py

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
"""tcod.sdl private functions."""
2+
from __future__ import annotations
3+
4+
import logging
5+
import sys as _sys
6+
from dataclasses import dataclass
7+
from types import TracebackType
8+
from typing import Any, Callable, TypeVar
9+
10+
from tcod.loader import ffi, lib
11+
12+
T = TypeVar("T")
13+
14+
logger = logging.getLogger("tcod.sdl")
15+
16+
_LOG_PRIORITY = {
17+
1: logging.DEBUG, # SDL_LOG_PRIORITY_VERBOSE
18+
2: logging.DEBUG, # SDL_LOG_PRIORITY_DEBUG
19+
3: logging.INFO, # SDL_LOG_PRIORITY_INFO
20+
4: logging.WARNING, # SDL_LOG_PRIORITY_WARN
21+
5: logging.ERROR, # SDL_LOG_PRIORITY_ERROR
22+
6: logging.CRITICAL, # SDL_LOG_PRIORITY_CRITICAL
23+
}
24+
25+
_LOG_CATEGORY = {
26+
int(lib.SDL_LOG_CATEGORY_APPLICATION): "APPLICATION",
27+
int(lib.SDL_LOG_CATEGORY_ERROR): "ERROR",
28+
int(lib.SDL_LOG_CATEGORY_ASSERT): "ASSERT",
29+
int(lib.SDL_LOG_CATEGORY_SYSTEM): "SYSTEM",
30+
int(lib.SDL_LOG_CATEGORY_AUDIO): "AUDIO",
31+
int(lib.SDL_LOG_CATEGORY_VIDEO): "VIDEO",
32+
int(lib.SDL_LOG_CATEGORY_RENDER): "RENDER",
33+
int(lib.SDL_LOG_CATEGORY_INPUT): "INPUT",
34+
int(lib.SDL_LOG_CATEGORY_TEST): "TEST",
35+
int(lib.SDL_LOG_CATEGORY_CUSTOM): "",
36+
}
37+
38+
39+
@dataclass
40+
class _UnraisableHookArgs:
41+
exc_type: type[BaseException]
42+
exc_value: BaseException | None
43+
exc_traceback: TracebackType | None
44+
err_msg: str | None
45+
object: object
46+
47+
48+
class _ProtectedContext:
49+
def __init__(self, obj: object = None) -> None:
50+
self.obj = obj
51+
52+
def __enter__(self) -> None:
53+
pass
54+
55+
def __exit__(
56+
self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
57+
) -> bool:
58+
if exc_type is None:
59+
return False
60+
if _sys.version_info < (3, 8):
61+
return False
62+
_sys.unraisablehook(_UnraisableHookArgs(exc_type, value, traceback, None, self.obj)) # type: ignore[arg-type]
63+
return True
64+
65+
66+
@ffi.def_extern() # type: ignore
67+
def _sdl_log_output_function(_userdata: None, category: int, priority: int, message_p: Any) -> None: # noqa: ANN401
68+
"""Pass logs sent by SDL to Python's logging system."""
69+
message = str(ffi.string(message_p), encoding="utf-8")
70+
logger.log(_LOG_PRIORITY.get(priority, 0), "%s:%s", _LOG_CATEGORY.get(category, ""), message)
71+
72+
73+
def _get_error() -> str:
74+
"""Return a message from SDL_GetError as a Unicode string."""
75+
return str(ffi.string(lib.SDL_GetError()), encoding="utf-8")
76+
77+
78+
def _check(result: int) -> int:
79+
"""Check if an SDL function returned without errors, and raise an exception if it did."""
80+
if result < 0:
81+
raise RuntimeError(_get_error())
82+
return result
83+
84+
85+
def _check_p(result: Any) -> Any:
86+
"""Check if an SDL function returned NULL, and raise an exception if it did."""
87+
if not result:
88+
raise RuntimeError(_get_error())
89+
return result
90+
91+
92+
if lib._sdl_log_output_function:
93+
lib.SDL_LogSetOutputFunction(lib._sdl_log_output_function, ffi.NULL)
94+
if __debug__:
95+
lib.SDL_LogSetAllPriority(lib.SDL_LOG_PRIORITY_VERBOSE)
96+
97+
98+
def _compiled_version() -> tuple[int, int, int]:
99+
return int(lib.SDL_MAJOR_VERSION), int(lib.SDL_MINOR_VERSION), int(lib.SDL_PATCHLEVEL)
100+
101+
102+
def _linked_version() -> tuple[int, int, int]:
103+
sdl_version = ffi.new("SDL_version*")
104+
lib.SDL_GetVersion(sdl_version)
105+
return int(sdl_version.major), int(sdl_version.minor), int(sdl_version.patch)
106+
107+
108+
def _version_at_least(required: tuple[int, int, int]) -> None:
109+
"""Raise an error if the compiled version is less than required. Used to guard recently defined SDL functions."""
110+
if required <= _compiled_version():
111+
return
112+
msg = f"This feature requires SDL version {required}, but tcod was compiled with version {_compiled_version()}"
113+
raise RuntimeError(msg)
114+
115+
116+
def _required_version(required: tuple[int, int, int]) -> Callable[[T], T]:
117+
if not lib: # Read the docs mock object.
118+
return lambda x: x
119+
if required <= _compiled_version():
120+
return lambda x: x
121+
122+
def replacement(*_args: Any, **_kwargs: Any) -> Any:
123+
msg = f"This feature requires SDL version {required}, but tcod was compiled with version {_compiled_version()}"
124+
raise RuntimeError(msg)
125+
126+
return lambda x: replacement # type: ignore[return-value]

tcod/sdl/audio.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
import tcod.sdl.sys
5858
from tcod.loader import ffi, lib
59-
from tcod.sdl import _check, _get_error, _ProtectedContext
59+
from tcod.sdl._internal import _check, _get_error, _ProtectedContext
6060

6161

6262
def _get_format(format: DTypeLike) -> int:

tcod/sdl/joystick.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
import tcod.sdl.sys
1414
from tcod.loader import ffi, lib
15-
from tcod.sdl import _check, _check_p
15+
from tcod.sdl._internal import _check, _check_p
1616

1717
_HAT_DIRECTIONS: dict[int, tuple[Literal[-1, 0, 1], Literal[-1, 0, 1]]] = {
1818
lib.SDL_HAT_CENTERED or 0: (0, 0),

tcod/sdl/mouse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import tcod.event
1818
import tcod.sdl.video
1919
from tcod.loader import ffi, lib
20-
from tcod.sdl import _check, _check_p
20+
from tcod.sdl._internal import _check, _check_p
2121

2222

2323
class Cursor:

tcod/sdl/render.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
import tcod.sdl.video
1515
from tcod.loader import ffi, lib
16-
from tcod.sdl import _check, _check_p, _required_version
16+
from tcod.sdl._internal import _check, _check_p, _required_version
1717

1818

1919
class TextureAccess(enum.IntEnum):

tcod/sdl/sys.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from typing import Any
66

77
from tcod.loader import ffi, lib
8-
from tcod.sdl import _check, _get_error
8+
from tcod.sdl._internal import _check, _get_error
99

1010

1111
class Subsystem(enum.IntFlag):

tcod/sdl/video.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from numpy.typing import ArrayLike, NDArray
1717

1818
from tcod.loader import ffi, lib
19-
from tcod.sdl import _check, _check_p, _required_version, _version_at_least
19+
from tcod.sdl._internal import _check, _check_p, _required_version, _version_at_least
2020

2121
__all__ = (
2222
"WindowFlags",

0 commit comments

Comments
 (0)