Drop support for SDL1

This commit is contained in:
Milan Nikolic 2017-01-15 13:43:29 +01:00
parent 0efcbd72d6
commit 68e6f392cf
36 changed files with 46 additions and 8379 deletions

View file

@ -1,9 +1,3 @@
- Included SDL ctypes code is Copyright: Alex Holkner
This code is licensed under the LGPL license, as found here:
http://www.gnu.org/licenses/lgpl.html
- Included SDL2 ctypes code is Copyright: Marcus von Appen
This software is distributed under the Public Domain.

View file

@ -11,7 +11,7 @@
About
-----
M64Py is a Qt5 front-end (GUI) for Mupen64Plus 2.0, a cross-platform
M64Py is a Qt5 front-end (GUI) for Mupen64Plus, a cross-platform
plugin-based Nintendo 64 emulator. Front-end is written in Python and it
provides a user-friendly interface over Mupen64Plus shared library.
@ -28,7 +28,7 @@ Dependencies
------------
* PyQt5
* SDL-1.2 or SDL-2.0
* SDL-2.0
Install
-------

5
dist/debian/m64py.6 vendored
View file

@ -28,16 +28,13 @@ m64py \- Mupen64plus 2.0 frontend
.B m64py [\fIoptions\fP]
.br
.SH DESCRIPTION
m64py is a graphical Qt5 frontend for the Nintendo64 emulator mupen64plus 2.0
m64py is a graphical Qt5 frontend for the Nintendo64 emulator mupen64plus
.PP
.PP
.SH OPTIONS
.TP
\fB\-v\fP, \fB\-\-verbose\fP
Show verbose output.
.TP
\fB\-\-sdl2\fP
Use SDL2 instead of auto-detecting the libmupen64plus2 build type.
.
.SH SEE ALSO
.BR mupen64plus (6),

View file

@ -18,7 +18,7 @@ Url: http://m64py.sourceforge.net
Requires: PyQt5 SDL
%description
M64Py is a Qt5 front-end (GUI) for Mupen64Plus 2.0, a cross-platform plugin-based Nintendo 64 emulator.
M64Py is a Qt5 front-end (GUI) for Mupen64Plus, a cross-platform plugin-based Nintendo 64 emulator.
%prep
%setup -n %{name}-%{unmangled_version}

View file

@ -154,7 +154,6 @@ class build_exe(Command):
def run(self):
self.run_command("build_qt")
set_sdl2()
set_rthook()
self.run_build()
self.copy_emulator()
@ -194,7 +193,6 @@ class build_zip(build_exe):
def run(self):
self.run_command("build_qt")
set_sdl2()
set_rthook()
self.set_config_path()
self.run_build()
@ -269,7 +267,6 @@ class build_dmg(Command):
def run(self):
self.run_command("build_qt")
set_sdl2()
set_rthook()
self.run_build()
self.copy_files()
@ -279,18 +276,6 @@ class build_dmg(Command):
self.run_build_dmg()
def set_sdl2():
opts_file = ""
opts_path = join(BASE_DIR, "src", "m64py", "opts.py")
with open(opts_path, "r") as opts: data = opts.read()
lines = data.split("\n")
for line in lines:
if "sdl2" in line:
line = line.replace("default=False", "default=True")
opts_file += line + "\n"
with open(opts_path, "w") as opts: opts.write(opts_file)
def set_rthook():
import PyInstaller
hook_file = ""
@ -364,12 +349,12 @@ setup(
name = "m64py",
version = FRONTEND_VERSION,
description = "M64Py - A frontend for Mupen64Plus",
long_description = "M64Py is a Qt5 front-end (GUI) for Mupen64Plus 2.0, a cross-platform plugin-based Nintendo 64 emulator.",
long_description = "M64Py is a Qt5 front-end (GUI) for Mupen64Plus, a cross-platform plugin-based Nintendo 64 emulator.",
author = "Milan Nikolic",
author_email = "gen2brain@gmail.com",
license = "GNU GPLv3",
url = "http://m64py.sourceforge.net",
packages = ["m64py", "m64py.core", "m64py.frontend", "m64py.ui", "m64py.SDL", "m64py.SDL2"],
packages = ["m64py", "m64py.core", "m64py.frontend", "m64py.ui", "m64py.SDL2"],
package_dir = {"": "src"},
scripts = ["m64py"],
requires = ["PyQt5"],

View file

@ -1,139 +0,0 @@
#!/usr/bin/env python
'''Main module for importing SDL-ctypes.
This module defines the intialization and cleanup functions:
- `SDL_Init`
- `SDL_InitSubSystem`
- `SDL_WasInit`
- `SDL_QuitSubSystem`
- `SDL_Quit`
It also imports all functions, constants and classes from the package
submodules. Typical usage, then, is to just import this module directly
into your namespace::
from SDL import *
This gives you access to all SDL names exactly as they appear in the C
header files.
:group Non-core modules: ttf, mixer, image, sound
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
import sys
from .dll import private_function, function
from .active import *
from .audio import *
from .cdrom import *
from .constants import *
from .endian import *
from .error import *
from .events import *
from .joystick import *
from .keyboard import *
from .mouse import *
from .quit import *
from .rwops import *
from .timer import *
from .version import *
from .video import *
# SDL.h
_SDL_Init = private_function('SDL_Init',
arg_types=[ctypes.c_uint],
return_type=ctypes.c_int)
def SDL_Init(flags):
'''Initialise the SDL library.
This function loads the SDL dynamically linked library and initializes
the subsystems specified by `flags` (and those satisfying dependencies)
Unless the `SDL_INIT_NOPARACHUTE` flag is set, it will install cleanup
signal handlers for some commonly ignored fatal signals (like SIGSEGV).
The following flags are recognised:
- `SDL_INIT_TIMER`
- `SDL_INIT_AUDIO`
- `SDL_INIT_VIDEO`
- `SDL_INIT_CDROM`
- `SDL_INIT_JOYSTICK`
- `SDL_INIT_NOPARACHUTE`
- `SDL_INIT_EVENTTHREAD`
- `SDL_INIT_EVERYTHING`
:Parameters:
- `flags`: int
:rtype: int
:return: undocumented (FIXME)
:see: `SDL_Quit`
'''
if sys.platform == 'darwin' and flags & SDL_INIT_VIDEO:
import SDL.darwin
SDL.darwin.init()
return _SDL_Init(flags)
_SDL_InitSubSystem = private_function('SDL_InitSubSystem',
arg_types=[ctypes.c_uint],
return_type=ctypes.c_int)
def SDL_InitSubSystem(flags):
'''Initialize specific SDL subsystems.
:Parameters:
- `flags`: int
:rtype: int
:return: undocumented (FIXME)
:see: `SDL_Init`, `SDL_QuitSubSystem`
'''
if sys.platform == 'darwin' and flags & SDL_INIT_VIDEO:
import SDL.darwin
SDL.darwin.init()
return _SDL_InitSubSystem(flags)
SDL_QuitSubSystem = function('SDL_QuitSubSystem',
'''Clean up specific SDL subsystems.
:Parameters:
- `flags`: int
:see: `SDL_InitSubSystem`
''',
args=['flags'],
arg_types=[ctypes.c_uint],
return_type=None)
SDL_WasInit = function('SDL_WasInit',
'''Return a mask of the specified subsystems which have been
initialized.
If `flags` is 0, return a mask of all initialized subsystems.
:Parameters:
- `flags`: int
:rtype: int
:return: undocumented (FIXME)
:see: `SDL_Init`
''',
args=['flags'],
arg_types=[ctypes.c_uint],
return_type=ctypes.c_int)
SDL_Quit = function('SDL_Quit',
'''Clean up all initialized subsystems.
You should call this function upon all exit conditions.
''',
args=[],
arg_types=[],
return_type=None)

View file

@ -1,31 +0,0 @@
#!/usr/bin/env python
'''SDL application focus event handling.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .dll import function
SDL_GetAppState = function('SDL_GetAppState',
'''Return the current state of the application.
The return value is a bitwise combination of `SDL_APPMOUSEFOCUS`,
`SDL_APPINPUTFOCUS`, and `SDL_APPACTIVE`. The meanings are as follows:
`SDL_APPMOUSEFOCUS`
The application has mouse coverage.
`SDL_APPINPUTFOCUS`
The application has input focus.
`SDL_APPACTIVATE`
The user is able to see your application, otherwise it has been
iconified or disabled
:rtype: int
''',
args=[],
arg_types=[],
return_type=c_int)

View file

@ -1,291 +0,0 @@
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
# Arrange these in order of preference
_array_names = ('numpy')
def _import_arrays(array_names, locals):
default_array = None
for array_name in array_names:
try:
array = __import__(array_name, globals(), locals, [])
typemap = {
c_ubyte: array.uint8,
c_ushort: array.uint16,
c_uint: array.uint32
}
locals[array_name] = array
locals['_%s_typemap' % array_name] = typemap
locals['_have_%s' % array_name] = True
if not default_array:
default_array = array
locals['_default_array'] = array
locals['_default_typemap'] = typemap
except ImportError:
locals['_have_%s' % array_name] = False
locals['_have_array'] = default_array is not None
# This sets up local names for the arrays. If numpy is
# available, the following local variables are defined:
# numpy, _numpy_typemap
#
# The following local variables will be set to True or False:
# _have_numpy
#
# If any of the array modules were imported, the following is True:
# _have_array
#
# And if _have_array is True, the following are defined:
# _default_array
# _default_typemap
_import_arrays(_array_names, locals())
class SDL_array:
def __init__(self, ptr, count, ctype):
'''Construct an array at memory location `ptr` with `count` elements
of type `ctype`.
:Parameters:
`ptr` : ctypes.Array, POINTER(ctype) or POINTER(ctypes.Array)
Starting point of the array space. Don't use c_void_p; this
will not cast correctly. If `ptr` is None, the array
will be created (filled with random data).
`count` : int
Number of elements in the array.
`ctype` : type
ctypes type if each element, e.g., c_ubyte, c_int, etc.
'''
count = int(count)
if not ptr:
ptr = (ctype * count)()
self.ptr = ptr
self.count = count
self.ctype = ctype
self._ctypes_array = None
# Casting methods
def as_bytes(self):
'''Access the array as raw bytes, regardless of the underlying
data type.
This can be useful, for example, in accessing a 32-bit colour
buffer by individual components rather than the encoded pixel.
:rtype: SDL_array
'''
return SDL_array(self.ptr, (self.count * sizeof(self.ctype)), c_ubyte)
def as_int16(self):
'''Access the array as 16-bit integers, regardless of the underlying
data type.
:rtype: SDL_array
'''
return SDL_array(self.ptr,
self.count * sizeof(self.ctype) / 2,
c_ushort)
def as_int32(self):
'''Access the array as 32-bit integers, regardless of the underlying
data type.
:rtype: SDL_array
'''
return SDL_array(self.ptr,
self.count * sizeof(self.ctype) / 4,
c_uint)
def as_ctypes(self):
'''Access the array as a ctypes array.
:rtype: ctypes.Array
'''
if not self._ctypes_array:
self._ctypes_array = \
cast(self.ptr, POINTER(self.ctype * self.count)).contents
return self._ctypes_array
# numpy specific methods
def have_numpy(cls):
'''Determine if the numpy array module is available.
:rtype: bool
'''
return _have_numpy
def as_numpy(self, shape=None):
'''Access the array as a numpy array.
The numpy array shares the same underlying memory buffer, so
changes are immediate, and you can use the numpy array as you would
normally. To set the entire contents of the array at once, use a
``[:]`` slice.
If numpy is not installed, an ImportError will be raised.
:rtype: numpy.ndarray
'''
if not _have_numpy:
raise ImportError('numpy could not be imported')
if self.ctype not in _numpy_typemap:
raise TypeError('%s has no numpy compatible type' % self.ctype)
if shape is None:
shape = (self.count,)
ar = numpy.frombuffer(self.as_ctypes(), _numpy_typemap[self.ctype])
ar = ar.reshape(shape)
return ar
# Generic array methods (numpy)
def have_array(cls):
'''Determine if an array module is available.
:rtype: bool
'''
return _have_array
have_array = classmethod(have_array)
def array_module(cls):
'''Determine the default array module.
:rtype: module
:return: one of numpy or None
'''
if _have_array:
return _default_array
else:
return None
array_module = classmethod(array_module)
def to_array(self, shape=None):
'''Convert the array to a numpy array.
The returned array will be a copy of the data. You can retrieve
the module used (numpy) using the `array_module`
method.
If none of numpy could be imported, an
ImportError will be raised.
:rtype: numpy.ndarray.array
'''
if not _have_array:
raise ImportError('no array module could be imported')
if self.ctype not in _default_typemap:
raise TypeError('%s has no array compatible type' % self.ctype)
s = self.to_string()
t = _default_typemap[self.ctype]
if shape is None:
shape = (self.count,)
# Each module has its own shaping interface
if _have_numpy and _default_array is numpy:
return _default_array.fromstring(s, t).reshape(shape)
def from_array(self, array):
'''Copy data from the given numpy array into
this array.
The array sizes must match exactly. No type checking is performed.
:Parameters:
`array` : numpy array object
Array to copy.
'''
s = array.tostring()
memmove(self.ptr, s, len(s))
# General interoperability (string)
def to_string(self):
'''Return a string with the contents of this array.
:rtype: string
'''
count = sizeof(self.ctype) * self.count
s = create_string_buffer(count)
memmove(s, self.ptr, count)
return s.raw
def from_string(self, data):
'''Copy string data into this array.
The string must have exactly the same length of this array (in bytes).
No size checking is performed.
:Parameters:
`data` : str
String data to copy.
'''
memmove(self.ptr, data, len(data))
def __repr__(self):
return 'SDL_array(ctype=%s, count=%r)' % (self.ctype, self.count)
def __len__(self):
return self.count
def __getitem__(self, key):
if type(key) is slice:
if key.step:
raise TypeError('slice step not supported')
return self.as_ctypes()[key.start:key.stop]
else:
return self.as_ctypes()[key]
def __setitem__(self, key, value):
if type(key) is slice:
if key.step:
raise TypeError('slice step not supported')
self.as_ctypes()[key.start:key.stop] = value
else:
self.as_ctypes()[key] = value
def to_ctypes(values, count, ctype):
'''Create a ctypes array of the given count and type, with the contents
of sequence `values`.
:Parameters:
- `values`: sequence of length `count`, or SDL_array instance, or
ctypes.Array, or POINTER(ctypes.Array)
- `count`: int
- `ctype`: type
:rtype: object, ctypes.Array
:return: (ref, array), where ref is an object that must be retained
by the caller for as long as the array is used.
'''
ref = values
# Convert SDL_array instances to ctypes array
if isinstance(values, SDL_array):
values = values.as_ctypes()
# Cast ctypes array to correct type if necessary
if isinstance(values, Array):
if values._type_ is ctype:
return ref, values
else:
return ref, cast(values, POINTER(ctype * count)).contents
# Convert string bytes to array
if type(values) == str:
ref = create_string_buffer(values)
return ref, cast(ref, POINTER(ctype * count)).contents
# Otherwise assume sequence
ar = (ctype * count)(*values)
return ar, ar

View file

@ -1,414 +0,0 @@
#!/usr/bin/env python
'''Access to the raw audio mixing buffer.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .array import SDL_array, to_ctypes
from .constants import AUDIO_U8, AUDIO_S8, AUDIO_U16LSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_S16MSB
from .dll import function, private_function
from .rwops import SDL_RWops, SDL_RWFromFile
_SDL_AudioSpec_fn = \
CFUNCTYPE(POINTER(c_ubyte), POINTER(c_ubyte), POINTER(c_ubyte), c_int)
class SDL_AudioSpec(Structure):
'''Audio format structure.
The calculated values in this structure are calculated by `SDL_OpenAudio`.
:Ivariables:
`freq` : int
DSP frequency, in samples per second
`format` : int
Audio data format. One of AUDIO_U8, AUDIO_S8, AUDIO_U16LSB,
AUDIO_S16LSB, AUDIO_U16MSB or AUDIO_S16MSB
`channels` : int
Number of channels; 1 for mono or 2 for stereo.
`silence` : int
Audio buffer silence value (calculated)
`samples` : int
Audio buffer size in samples (power of 2)
`size` : int
Audio buffer size in bytes (calculated)
'''
_fields_ = [('freq', c_int),
('format', c_ushort),
('channels', c_ubyte),
('silence', c_ubyte),
('samples', c_ushort),
('_padding', c_ushort),
('size', c_uint),
('_callback', _SDL_AudioSpec_fn),
('_userdata', c_void_p)]
_SDL_AudioCVT_p = POINTER('SDL_AudioCVT')
_SDL_AudioCVT_filter_fn = \
CFUNCTYPE(POINTER(c_ubyte), _SDL_AudioCVT_p, c_ushort)
class SDL_AudioCVT(Structure):
'''Set of audio conversion filters and buffers.
:Ivariables:
`needed` : int
1 if conversion is possible
`src_format` : int
Source audio format. See `SDL_AudioSpec.format`
`dst_format` : int
Destination audio format. See `SDL_AudioSpec.format`
`rate_incr` : float
Rate conversion increment
`len` : int
Length of original audio buffer
`len_cvt` : int
Length of converted audio buffer
`len_mult` : int
Buffer must be len * len_mult big
`len_ratio` : float
Given len, final size is len * len_ratio
`filter_index` : int
Current audio conversion function
'''
_fields_ = [('needed', c_int),
('src_format', c_ushort),
('dst_format', c_ushort),
('rate_incr', c_double),
('buf', POINTER(c_ubyte)),
('len', c_int),
('len_cvt', c_int),
('len_mult', c_int),
('len_ratio', c_double),
('filters', _SDL_AudioCVT_filter_fn * 10),
('filter_index', c_int)]
SetPointerType(_SDL_AudioCVT_p, SDL_AudioCVT)
# SDL_AudioInit and SDL_AudioQuit marked private
_SDL_AudioDriverName = private_function('SDL_AudioDriverName',
arg_types=[c_char_p, c_int],
return_type=c_char_p)
def SDL_AudioDriverName(maxlen=1024):
'''
Returns the name of the audio driver. Returns None if no driver has
been initialised.
:Parameters:
`maxlen`
Maximum length of the returned driver name; defaults to 1024.
:rtype: string
'''
buf = create_string_buffer(maxlen)
if _SDL_AudioDriverName(buf, maxlen):
return buf.value
return None
def _ctype_audio_format(fmt):
if fmt == AUDIO_U8:
return c_ubyte
elif fmt == AUDIO_S8:
return c_char
elif fmt in (AUDIO_U16LSB, AUDIO_U16MSB):
return c_ushort
elif fmt in (AUDIO_S16LSB, AUDIO_S16MSB):
return c_short
else:
raise TypeError('Unsupported format %r' % fmt)
_SDL_OpenAudio = private_function('SDL_OpenAudio',
arg_types=[POINTER(SDL_AudioSpec), POINTER(SDL_AudioSpec)],
return_type=c_int,
error_return=-1)
def SDL_OpenAudio(desired, obtained):
'''Open the audio device with the desired parameters.
If successful, the actual hardware parameters will be set in the
instance passed into `obtained`. If `obtained` is None, the audio
data passed to the callback function will be guaranteed to be in
the requested format, and will be automatically converted to the
hardware audio format if necessary.
An exception will be raised if the audio device couldn't be opened,
or the audio thread could not be set up.
The fields of `desired` are interpreted as follows:
`desired.freq`
desired audio frequency in samples per second
`desired.format`
desired audio format, i.e., one of AUDIO_U8, AUDIO_S8,
AUDIO_U16LSB, AUDIO_S16LSB, AUDIO_U16MSB or AUDIO_S16MSB
`desired.samples`
size of the audio buffer, in samples. This number should
be a power of two, and may be adjusted by the audio driver
to a value more suitable for the hardware. Good values seem
to range between 512 and 8096 inclusive, depending on the
application and CPU speed. Smaller values yield faster response
time, but can lead to underflow if the application is doing
heavy processing and cannot fill the audio buffer in time.
A stereo sample consists of both right and left channels in
LR ordering. Note that the number of samples is directly
related to time by the following formula::
ms = (samples * 1000) / freq
`desired.size`
size in bytes of the audio buffer; calculated by SDL_OpenAudio.
`desired.silence`
value used to set the buffer to silence; calculated by
SDL_OpenAudio.
`desired.callback`
a function that will be called when the audio device is ready
for more data. The signature of the function should be::
callback(userdata: any, stream: SDL_array) -> None
The function is called with the userdata you specify (see below),
and an SDL_array of the obtained format which you must fill
with audio data.
This function usually runs in a separate thread, so you should
protect data structures that it accesses by calling
`SDL_LockAudio` and `SDL_UnlockAudio` in your code.
`desired.userdata`
passed as the first parameter to your callback function.
The audio device starts out playing silence when it's opened, and should
be enabled for playing by calling ``SDL_PauseAudio(False)`` when you are
ready for your audio callback function to be called. Since the audio
driver may modify the requested size of the audio buffer, you should
allocate any local mixing buffers after you open the audio device.
:Parameters:
- `desired`: `SDL_AudioSpec`
- `obtained`: `SDL_AudioSpec` or None
'''
if not hasattr(desired, 'callback'):
raise TypeError('Attribute "callback" not set on "desired"')
userdata = getattr(desired, 'userdata', None)
callback = desired.callback
ctype = [_ctype_audio_format(desired.format)] # List, so mutable
def cb(data, stream, len):
ar = SDL_array(stream, len/sizeof(ctype[0]), ctype[0])
callback(userdata, ar)
desired._callback = _SDL_AudioSpec_fn(cb)
_SDL_OpenAudio(desired, obtained)
if obtained:
obtained.userdata = desired.userdata
obtained.callback = desired.callback
ctype[0] = _ctype_audio_format(obtained.format)
SDL_GetAudioStatus = function('SDL_GetAudioStatus',
'''Get the current audio state.
:rtype: int
:return: one of SDL_AUDIO_STOPPED, SDL_AUDIO_PLAYING, SDL_AUDIO_PAUSED
''',
args=[],
arg_types=[],
return_type=c_int)
SDL_PauseAudio = function('SDL_PauseAudio',
'''Pause and unpause the audio callback processing.
It should be called with a parameter of 0 after opening the audio
device to start playing sound. This is so you can safely initalize
data for your callback function after opening the audio device.
Silence will be written to the audio device during the pause.
:Parameters:
- `pause_on`: int
''',
args=['pause_on'],
arg_types=[c_int],
return_type=None)
_SDL_LoadWAV_RW = private_function('SDL_LoadWAV_RW',
arg_types=[POINTER(SDL_RWops),
c_int,
POINTER(SDL_AudioSpec),
POINTER(POINTER(c_ubyte)),
POINTER(c_uint)],
return_type=POINTER(SDL_AudioSpec),
require_return=True)
def SDL_LoadWAV_RW(src, freesrc):
'''Load a WAVE from the data source.
The source is automatically freed if `freesrc` is non-zero. For
example, to load a WAVE file, you could do::
SDL_LoadWAV_RW(SDL_RWFromFile('sample.wav', 'rb'), 1)
You need to free the returned buffer with `SDL_FreeWAV` when you
are done with it.
:Parameters:
- `src`: `SDL_RWops`
- `freesrc`: int
:rtype: (`SDL_AudioSpec`, `SDL_array`)
:return: a tuple (`spec`, `audio_buf`) where `spec` describes the data
format and `audio_buf` is the buffer containing audio data.
'''
spec = SDL_AudioSpec()
audio_buf = POINTER(c_ubyte)()
audio_len = c_uint()
_SDL_LoadWAV_RW(src, freesrc, spec, byref(audio_buf), byref(audio_len))
ctype = _ctype_audio_format(spec.format)
return (spec,
SDL_array(audio_buf, audio_len.value/sizeof(ctype), ctype))
def SDL_LoadWAV(file):
'''Load a WAVE from a file.
:Parameters:
- `file`: str
:rtype: (`SDL_AudioSpec`, `SDL_array`)
:see: `SDL_LoadWAV_RW`
'''
return SDL_LoadWAV_RW(SDL_RWFromFile(file, 'rb'), 1)
_SDL_FreeWAV = private_function('SDL_FreeWAV',
arg_types=[POINTER(c_ubyte)],
return_type=None)
def SDL_FreeWAV(audio_buf):
'''Free a buffer previously allocated with `SDL_LoadWAV_RW` or
`SDL_LoadWAV`.
:Parameters:
- `audio_buf`: `SDL_array`
'''
_SDL_FreeWAV(audio_buf.as_bytes().as_ctypes())
_SDL_BuildAudioCVT = private_function('SDL_BuildAudioCVT',
arg_types=[POINTER(SDL_AudioCVT), c_ushort, c_ubyte, c_uint,
c_ushort, c_ubyte, c_uint],
return_type=c_int,
error_return=-1)
def SDL_BuildAudioCVT(src_format, src_channels, src_rate,
dst_format, dst_channels, dst_rate):
'''Take a source format and rate and a destination format and rate,
and return a `SDL_AudioCVT` structure.
The `SDL_AudioCVT` structure is used by `SDL_ConvertAudio` to convert
a buffer of audio data from one format to the other.
:Parameters:
- `src_format`: int
- `src_channels`: int
- `src_rate`: int
- `dst_format`: int
- `dst_channels`: int
- `dst_rate`: int
:rtype: `SDL_AudioCVT`
'''
cvt = SDL_AudioCVT()
_SDL_BuildAudioCVT(cvt, src_format, src_channels, src_rate,
dst_format, dst_channels, dst_rate)
return cvt
SDL_ConvertAudio = function('SDL_ConvertAudio',
'''Convert audio data in-place.
Once you have initialized the 'cvt' structure using
`SDL_BuildAudioCVT`, created an audio buffer ``cvt.buf``, and filled it
with ``cvt.len`` bytes of audio data in the source format, this
function will convert it in-place to the desired format. The data
conversion may expand the size of the audio data, so the buffer
``cvt.buf`` should be allocated after the cvt structure is initialized
by `SDL_BuildAudioCVT`, and should be ``cvt->len*cvt->len_mult`` bytes
long.
Note that you are responsible for allocating the buffer. The
recommended way is to construct an `SDL_array` of the correct size,
and set ``cvt.buf`` to the result of `SDL_array.as_ctypes`.
:Parameters:
- `cvt`: `SDL_AudioCVT`
:rtype: int
:return: undocumented
''',
args=['cvt'],
arg_types=[POINTER(SDL_AudioCVT)],
return_type=c_int)
_SDL_MixAudio = private_function('SDL_MixAudio',
arg_types=[POINTER(c_ubyte), POINTER(c_ubyte), c_uint, c_int],
return_type=None)
def SDL_MixAudio(dst, src, length, volume):
'''Mix two audio buffers.
This takes two audio buffers of the playing audio format and mixes
them, performing addition, volume adjustment, and overflow clipping.
The volume ranges from 0 - 128, and should be set to SDL_MIX_MAXVOLUME
for full audio volume. Note this does not change hardware volume.
This is provided for convenience -- you can mix your own audio data.
:note: SDL-ctypes doesn't know the current play format, so you must
always pass in byte buffers (SDL_array or sequence) to this function,
rather than of the native data type.
:Parameters:
- `dst`: `SDL_array`
- `src`: `SDL_array`
- `length`: int
- `volume`: int
'''
dstref, dst = to_ctypes(dst, len(dst), c_ubyte)
srcref, src = to_ctypes(src, len(src), c_ubyte)
if len(dst) < length:
raise TypeError('Destination buffer too small')
elif len(src) < length:
raise TypeError('Source buffer too small')
_SDL_MixAudio(dst, src, length, volume)
SDL_LockAudio = function('SDL_LockAudio',
'''Guarantee the callback function is not running.
The lock manipulated by these functions protects the callback function.
During a LockAudio/UnlockAudio pair, you can be guaranteed that the
callback function is not running. Do not call these from the callback
function or you will cause deadlock.
''',
args=[],
arg_types=[],
return_type=None)
SDL_UnlockAudio = function('SDL_UnlockAudio',
'''Release the audio callback lock.
:see: `SDL_LockAudio`
''',
args=[],
arg_types=[],
return_type=None)
SDL_CloseAudio = function('SDL_CloseAudio',
'''Shut down audio processing and close the audio device.
''',
args=[],
arg_types=[],
return_type=None)

View file

@ -1,291 +0,0 @@
#!/usr/bin/env python
'''CD-audio control.
In order to use these functions, `SDL_Init` must have been called with the
`SDL_INIT_CDROM` flag. This causes SDL to scan the system for CD-ROM
drives, and load appropriate drivers.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .constants import SDL_MAX_TRACKS, CD_FPS
from .dll import function
class SDL_CDtrack(Structure):
'''Structure describing a single CD track.
:Ivariables:
`id` : int
Track number
`type` : int
One of SDL_AUDIO_TRACK or SDL_DATA_TRACK
`length` : int
Length, in frames, of this track
`offset` : int
Offset, in frames, from start of disk
'''
_fields_ = [('id', c_ubyte),
('type', c_ubyte),
('_unused', c_ushort),
('length', c_uint),
('offset', c_uint)]
class SDL_CD(Structure):
'''Structure describing a CD.
This structure is only current as of the last call to `SDL_CDStatus`.
:Ivariables:
`id` : int
Private drive identifier
`status` : int
Current drive status. One of CD_TRAYEMPTY, CD_STOPPED,
CD_PLAYING, CD_PAUSED, CD_ERROR.
`numtracks` : int
Number of tracks on disk
`cur_track` : int
Current track position
`cur_frame` : int
Current frame offset within current track
`track` : sequence of `SDL_CDtrack`
Tracks on the disk.
'''
_fields_ = [('id', c_uint),
('status', c_int),
('numtracks', c_int),
('cur_track', c_int),
('cur_frame', c_int),
('track', SDL_CDtrack * (SDL_MAX_TRACKS + 1))]
def CD_INDRIVE(status):
'''Given a status, returns True if there's a disk in the drive.
:Parameters:
- `status`: int
:rtype: bool
'''
return status > 0
def FRAMES_TO_MSF(frames):
'''Convert from frames to minute/second/frame
:Parameters:
- `frames`: int
:rtype: (int, int, int)
:return: tuple of (minutes, seconds, frames)
'''
F = frames % CD_FPS
frames /= CD_FPS
S = frames % 60
frames /= 60
M = frames
return (M, S, F)
def MSF_TO_FRAMES(minutes, seconds, frames):
'''Convert from minute/second/frame to frames
:Parameters:
- `minutes`: int
- `seconds`: int
- `frames`: int
:rtype: int
'''
return CD_FPS(minutes * 60 + seconds) + frames
SDL_CDNumDrives = function('SDL_CDNumDrives',
'''Return the number of CD-ROM drives on the system.
:rtype: int
''',
args=[],
arg_types=[],
return_type=c_int,
error_return=-1)
SDL_CDName = function('SDL_CDName',
'''Return a human-readable, system-dependent identifier for the
CD-ROM.
Example::
'/dev/cdrom'
'E:'
'/dev/disk/ide/1/master'
:Parameters:
`drive` : int
Drive number, starting with 0. Drive 0 is the system default
CD-ROM.
:rtype: string
''',
args=['drive'],
arg_types=[c_int],
return_type=c_char_p,
require_return=True)
SDL_CDOpen = function('SDL_CDOpen',
'''Open a CD-ROM drive for access.
It returns a drive handle on success, or raises an exception if the
drive was invalid or busy. This newly opened CD-ROM becomes the
default CD used when other CD functions are passed None as the CD-ROM
handle.
Drives are numbered starting with 0. Drive 0 is the system default
CD-ROM.
:Parameters:
- `drive`: int
:rtype: `SDL_CD`
''',
args=['drive'],
arg_types=[c_int],
return_type=POINTER(SDL_CD),
dereference_return=True,
require_return=True)
SDL_CDStatus = function('SDL_CDStatus',
'''Return the current status of the given drive.
If the drive has a CD in it, the table of contents of the CD and
current play position of the CD will be updated in the SDL_CD
instance.
Possible return values are
- `CD_TRAYEMPTY`
- `CD_STOPPED`
- `CD_PLAYING`
- `CD_PAUSED`
:Parameters:
- `cdrom`: `SDL_CD`
:rtype: int
''',
args=['cdrom'],
arg_types=[POINTER(SDL_CD)],
return_type=int,
error_return=-1)
SDL_CDPlayTracks = function('SDL_CDPlayTracks',
'''Play the given CD.
Plays the given CD starting at `start_track` and `start_frame` for
`ntracks` tracks and `nframes` frames. If both `ntracks` and `nframes`
are 0, play until the end of the CD. This function will skip data
tracks. This function should only be called after calling
`SDL_CDStatus` to get track information about the CD.
For example::
# Play entire CD:
if CD_INDRIVE(SDL_CDStatus(cdrom)):
SDL_CDPlayTracks(cdrom, 0, 0, 0, 0)
# Play last track:
if CD_INDRIVE(SDL_CDStatus(cdrom)):
SDL_CDPlayTracks(cdrom, cdrom.numtracks-1, 0, 0, 0)
#Play first and second track and 10 seconds of third track:
if CD_INDRIVE(SDL_CDStatus(cdrom)):
SDL_CDPlayTracks(cdrom, 0, 0, 2, 10)
:Parameters:
- `cdrom`: `SDL_CD`
- `start_track`: int
- `start_frame`: int
- `ntracks`: int
- `nframes`: int
''',
args=['cdrom', 'start_track', 'start_frame', 'ntracks', 'nframes'],
arg_types=[POINTER(SDL_CD), c_int, c_int, c_int, c_int],
return_type=c_int,
error_return=-1)
SDL_CDPlay = function('SDL_CDPlay',
'''Play the given CD.
Plays the given CD starting at `start` frame for `length` frames.
:Parameters:
- `cdrom`: `SDL_CD`
- `start`: int
- `length`: int
''',
args=['cdrom', 'start', 'length'],
arg_types=[POINTER(SDL_CD), c_int, c_int],
return_type=c_int,
error_return=-1)
SDL_CDPause = function('SDL_CDPause',
'''Pause play.
:Parameters:
- `cdrom`: `SDL_CD`
''',
args=['cdrom'],
arg_types=[POINTER(SDL_CD)],
return_type=c_int,
error_return=-1)
SDL_CDResume = function('SDL_CDResume',
'''Resume play.
:Parameters:
- `cdrom`: `SDL_CD`
''',
args=['cdrom'],
arg_types=[POINTER(SDL_CD)],
return_type=c_int,
error_return=-1)
SDL_CDStop = function('SDL_CDStop',
'''Stop play.
:Parameters:
- `cdrom`: `SDL_CD`
''',
args=['cdrom'],
arg_types=[POINTER(SDL_CD)],
return_type=c_int,
error_return=-1)
SDL_CDEject = function('SDL_CDEject',
'''Eject CD-ROM.
:Parameters:
- `cdrom`: `SDL_CD`
''',
args=['cdrom'],
arg_types=[POINTER(SDL_CD)],
return_type=c_int,
error_return=-1)
SDL_CDClose = function('SDL_CDClose',
'''Close the handle for the CD-ROM drive.
:Parameters:
- `cdrom`: `SDL_CD`
''',
args=['cdrom'],
arg_types=[POINTER(SDL_CD)],
return_type=c_int,
error_return=-1)

View file

@ -1,565 +0,0 @@
#!/usr/bin/env python
'''Constants and enums for all SDL submodules.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import sys
# enum SDLKey {
# The keyboard syms have been cleverly chosen to map to ASCII
SDLK_UNKNOWN = 0
SDLK_FIRST = 0
SDLK_BACKSPACE = 8
SDLK_TAB = 9
SDLK_CLEAR = 12
SDLK_RETURN = 13
SDLK_PAUSE = 19
SDLK_ESCAPE = 27
SDLK_SPACE = 32
SDLK_EXCLAIM = 33
SDLK_QUOTEDBL = 34
SDLK_HASH = 35
SDLK_DOLLAR = 36
SDLK_AMPERSAND = 38
SDLK_QUOTE = 39
SDLK_LEFTPAREN = 40
SDLK_RIGHTPAREN = 41
SDLK_ASTERISK = 42
SDLK_PLUS = 43
SDLK_COMMA = 44
SDLK_MINUS = 45
SDLK_PERIOD = 46
SDLK_SLASH = 47
SDLK_0 = 48
SDLK_1 = 49
SDLK_2 = 50
SDLK_3 = 51
SDLK_4 = 52
SDLK_5 = 53
SDLK_6 = 54
SDLK_7 = 55
SDLK_8 = 56
SDLK_9 = 57
SDLK_COLON = 58
SDLK_SEMICOLON = 59
SDLK_LESS = 60
SDLK_EQUALS = 61
SDLK_GREATER = 62
SDLK_QUESTION = 63
SDLK_AT = 64
# Skip uppercase letters
SDLK_LEFTBRACKET = 91
SDLK_BACKSLASH = 92
SDLK_RIGHTBRACKET = 93
SDLK_CARET = 94
SDLK_UNDERSCORE = 95
SDLK_BACKQUOTE = 96
SDLK_a = 97
SDLK_b = 98
SDLK_c = 99
SDLK_d = 100
SDLK_e = 101
SDLK_f = 102
SDLK_g = 103
SDLK_h = 104
SDLK_i = 105
SDLK_j = 106
SDLK_k = 107
SDLK_l = 108
SDLK_m = 109
SDLK_n = 110
SDLK_o = 111
SDLK_p = 112
SDLK_q = 113
SDLK_r = 114
SDLK_s = 115
SDLK_t = 116
SDLK_u = 117
SDLK_v = 118
SDLK_w = 119
SDLK_x = 120
SDLK_y = 121
SDLK_z = 122
SDLK_DELETE = 127
# End of ASCII mapped keysyms
# International keyboard syms
SDLK_WORLD_0 = 160 # 0xA0
SDLK_WORLD_1 = 161
SDLK_WORLD_2 = 162
SDLK_WORLD_3 = 163
SDLK_WORLD_4 = 164
SDLK_WORLD_5 = 165
SDLK_WORLD_6 = 166
SDLK_WORLD_7 = 167
SDLK_WORLD_8 = 168
SDLK_WORLD_9 = 169
SDLK_WORLD_10 = 170
SDLK_WORLD_11 = 171
SDLK_WORLD_12 = 172
SDLK_WORLD_13 = 173
SDLK_WORLD_14 = 174
SDLK_WORLD_15 = 175
SDLK_WORLD_16 = 176
SDLK_WORLD_17 = 177
SDLK_WORLD_18 = 178
SDLK_WORLD_19 = 179
SDLK_WORLD_20 = 180
SDLK_WORLD_21 = 181
SDLK_WORLD_22 = 182
SDLK_WORLD_23 = 183
SDLK_WORLD_24 = 184
SDLK_WORLD_25 = 185
SDLK_WORLD_26 = 186
SDLK_WORLD_27 = 187
SDLK_WORLD_28 = 188
SDLK_WORLD_29 = 189
SDLK_WORLD_30 = 190
SDLK_WORLD_31 = 191
SDLK_WORLD_32 = 192
SDLK_WORLD_33 = 193
SDLK_WORLD_34 = 194
SDLK_WORLD_35 = 195
SDLK_WORLD_36 = 196
SDLK_WORLD_37 = 197
SDLK_WORLD_38 = 198
SDLK_WORLD_39 = 199
SDLK_WORLD_40 = 200
SDLK_WORLD_41 = 201
SDLK_WORLD_42 = 202
SDLK_WORLD_43 = 203
SDLK_WORLD_44 = 204
SDLK_WORLD_45 = 205
SDLK_WORLD_46 = 206
SDLK_WORLD_47 = 207
SDLK_WORLD_48 = 208
SDLK_WORLD_49 = 209
SDLK_WORLD_50 = 210
SDLK_WORLD_51 = 211
SDLK_WORLD_52 = 212
SDLK_WORLD_53 = 213
SDLK_WORLD_54 = 214
SDLK_WORLD_55 = 215
SDLK_WORLD_56 = 216
SDLK_WORLD_57 = 217
SDLK_WORLD_58 = 218
SDLK_WORLD_59 = 219
SDLK_WORLD_60 = 220
SDLK_WORLD_61 = 221
SDLK_WORLD_62 = 222
SDLK_WORLD_63 = 223
SDLK_WORLD_64 = 224
SDLK_WORLD_65 = 225
SDLK_WORLD_66 = 226
SDLK_WORLD_67 = 227
SDLK_WORLD_68 = 228
SDLK_WORLD_69 = 229
SDLK_WORLD_70 = 230
SDLK_WORLD_71 = 231
SDLK_WORLD_72 = 232
SDLK_WORLD_73 = 233
SDLK_WORLD_74 = 234
SDLK_WORLD_75 = 235
SDLK_WORLD_76 = 236
SDLK_WORLD_77 = 237
SDLK_WORLD_78 = 238
SDLK_WORLD_79 = 239
SDLK_WORLD_80 = 240
SDLK_WORLD_81 = 241
SDLK_WORLD_82 = 242
SDLK_WORLD_83 = 243
SDLK_WORLD_84 = 244
SDLK_WORLD_85 = 245
SDLK_WORLD_86 = 246
SDLK_WORLD_87 = 247
SDLK_WORLD_88 = 248
SDLK_WORLD_89 = 249
SDLK_WORLD_90 = 250
SDLK_WORLD_91 = 251
SDLK_WORLD_92 = 252
SDLK_WORLD_93 = 253
SDLK_WORLD_94 = 254
SDLK_WORLD_95 = 255 # 0xFF
# Numeric keypad
SDLK_KP0 = 256
SDLK_KP1 = 257
SDLK_KP2 = 258
SDLK_KP3 = 259
SDLK_KP4 = 260
SDLK_KP5 = 261
SDLK_KP6 = 262
SDLK_KP7 = 263
SDLK_KP8 = 264
SDLK_KP9 = 265
SDLK_KP_PERIOD = 266
SDLK_KP_DIVIDE = 267
SDLK_KP_MULTIPLY = 268
SDLK_KP_MINUS = 269
SDLK_KP_PLUS = 270
SDLK_KP_ENTER = 271
SDLK_KP_EQUALS = 272
# Arrows + Home/End pad
SDLK_UP = 273
SDLK_DOWN = 274
SDLK_RIGHT = 275
SDLK_LEFT = 276
SDLK_INSERT = 277
SDLK_HOME = 278
SDLK_END = 279
SDLK_PAGEUP = 280
SDLK_PAGEDOWN = 281
# Function keys
SDLK_F1 = 282
SDLK_F2 = 283
SDLK_F3 = 284
SDLK_F4 = 285
SDLK_F5 = 286
SDLK_F6 = 287
SDLK_F7 = 288
SDLK_F8 = 289
SDLK_F9 = 290
SDLK_F10 = 291
SDLK_F11 = 292
SDLK_F12 = 293
SDLK_F13 = 294
SDLK_F14 = 295
SDLK_F15 = 296
# Key state modifier keys
SDLK_NUMLOCK = 300
SDLK_CAPSLOCK = 301
SDLK_SCROLLOCK = 302
SDLK_RSHIFT = 303
SDLK_LSHIFT = 304
SDLK_RCTRL = 305
SDLK_LCTRL = 306
SDLK_RALT = 307
SDLK_LALT = 308
SDLK_RMETA = 309
SDLK_LMETA = 310
SDLK_LSUPER = 311 # Left "Windows" key
SDLK_RSUPER = 312 # Right "Windows" key
SDLK_MODE = 313 # "Alt Gr" key
SDLK_COMPOSE = 314 # Multi-key compose key
# Miscellaneous function keys
SDLK_HELP = 315
SDLK_PRINT = 316
SDLK_SYSREQ = 317
SDLK_BREAK = 318
SDLK_MENU = 319
SDLK_POWER = 320 # Power Macintosh power key
SDLK_EURO = 321 # Some european keyboards
SDLK_UNDO = 322 # Atari keyboard has Undo
SDLK_LAST = 323 # Keep me updated please.
# end of enum SDLKey
# enum SDLMod
KMOD_NONE = 0x0000
KMOD_LSHIFT = 0x0001
KMOD_RSHIFT = 0x0002
KMOD_LCTRL = 0x0040
KMOD_RCTRL = 0x0080
KMOD_LALT = 0x0100
KMOD_RALT = 0x0200
KMOD_LMETA = 0x0400
KMOD_RMETA = 0x0800
KMOD_NUM = 0x1000
KMOD_CAPS = 0x2000
KMOD_MODE = 0x4000
KMOD_RESERVED = 0x8000
# end of enum SDLMod
KMOD_CTRL = KMOD_LCTRL | KMOD_RCTRL
KMOD_SHIFT = KMOD_LSHIFT | KMOD_RSHIFT
KMOD_ALT = KMOD_LALT | KMOD_RALT
KMOD_META = KMOD_LMETA | KMOD_RMETA
#BEGIN GENERATED CONSTANTS; see support/make_constants.py
#Constants from SDL_mouse.h:
SDL_BUTTON_LEFT = 0x00000001
SDL_BUTTON_MIDDLE = 0x00000002
SDL_BUTTON_RIGHT = 0x00000003
SDL_BUTTON_WHEELUP = 0x00000004
SDL_BUTTON_WHEELDOWN = 0x00000005
#Constants from SDL_version.h:
SDL_MAJOR_VERSION = 0x00000001
SDL_MINOR_VERSION = 0x00000002
SDL_PATCHLEVEL = 0x0000000a
#Constants from SDL.h:
SDL_INIT_TIMER = 0x00000001
SDL_INIT_AUDIO = 0x00000010
SDL_INIT_VIDEO = 0x00000020
SDL_INIT_CDROM = 0x00000100
SDL_INIT_JOYSTICK = 0x00000200
SDL_INIT_NOPARACHUTE = 0x00100000
SDL_INIT_EVENTTHREAD = 0x01000000
SDL_INIT_EVERYTHING = 0x0000ffff
#Constants from SDL_mutex.h:
SDL_MUTEX_TIMEDOUT = 0x00000001
#Constants from SDL_video.h:
SDL_ALPHA_OPAQUE = 0x000000ff
SDL_ALPHA_TRANSPARENT = 0x00000000
SDL_SWSURFACE = 0x00000000
SDL_HWSURFACE = 0x00000001
SDL_ASYNCBLIT = 0x00000004
SDL_ANYFORMAT = 0x10000000
SDL_HWPALETTE = 0x20000000
SDL_DOUBLEBUF = 0x40000000
SDL_FULLSCREEN = 0x80000000
SDL_OPENGL = 0x00000002
SDL_OPENGLBLIT = 0x0000000a
SDL_RESIZABLE = 0x00000010
SDL_NOFRAME = 0x00000020
SDL_HWACCEL = 0x00000100
SDL_SRCCOLORKEY = 0x00001000
SDL_RLEACCELOK = 0x00002000
SDL_RLEACCEL = 0x00004000
SDL_SRCALPHA = 0x00010000
SDL_PREALLOC = 0x01000000
SDL_YV12_OVERLAY = 0x32315659
SDL_IYUV_OVERLAY = 0x56555949
SDL_YUY2_OVERLAY = 0x32595559
SDL_UYVY_OVERLAY = 0x59565955
SDL_YVYU_OVERLAY = 0x55595659
SDL_LOGPAL = 0x00000001
SDL_PHYSPAL = 0x00000002
#Constants from SDL_name.h:
NeedFunctionPrototypes = 0x00000001
#Constants from SDL_endian.h:
SDL_LIL_ENDIAN = 0x000004d2
SDL_BIG_ENDIAN = 0x000010e1
#Constants from SDL_audio.h:
AUDIO_U8 = 0x00000008
AUDIO_S8 = 0x00008008
AUDIO_U16LSB = 0x00000010
AUDIO_S16LSB = 0x00008010
AUDIO_U16MSB = 0x00001010
AUDIO_S16MSB = 0x00009010
SDL_MIX_MAXVOLUME = 0x00000080
#Constants from begin_code.h:
NULL = 0x00000000
#Constants from SDL_cdrom.h:
SDL_MAX_TRACKS = 0x00000063
SDL_AUDIO_TRACK = 0x00000000
SDL_DATA_TRACK = 0x00000004
CD_FPS = 0x0000004b
#Constants from SDL_events.h:
SDL_RELEASED = 0x00000000
SDL_PRESSED = 0x00000001
SDL_ALLEVENTS = 0xffffffff
SDL_IGNORE = 0x00000000
SDL_DISABLE = 0x00000000
SDL_ENABLE = 0x00000001
#Constants from SDL_active.h:
SDL_APPMOUSEFOCUS = 0x00000001
SDL_APPINPUTFOCUS = 0x00000002
SDL_APPACTIVE = 0x00000004
#Constants from SDL_joystick.h:
SDL_HAT_CENTERED = 0x00000000
SDL_HAT_UP = 0x00000001
SDL_HAT_RIGHT = 0x00000002
SDL_HAT_DOWN = 0x00000004
SDL_HAT_LEFT = 0x00000008
#Constants from SDL_keyboard.h:
SDL_ALL_HOTKEYS = 0xffffffff
SDL_DEFAULT_REPEAT_DELAY = 0x000001f4
SDL_DEFAULT_REPEAT_INTERVAL = 0x0000001e
#Constants from SDL_rwops.h:
RW_SEEK_SET = 0x00000000
RW_SEEK_CUR = 0x00000001
RW_SEEK_END = 0x00000002
#Constants from SDL_timer.h:
SDL_TIMESLICE = 0x0000000a
TIMER_RESOLUTION = 0x0000000a
#END GENERATED CONSTANTS
# From SDL_audio.h (inserted manually)
# enum SDL_audiostatus
(SDL_AUDIO_STOPPED,
SDL_AUDIO_PLAYING,
SDL_AUDIO_PAUSED) = range(3)
if sys.byteorder == 'little':
AUDIO_U16SYS = AUDIO_U16LSB
AUDIO_S16SYS = AUDIO_S16LSB
else:
AUDIO_U16SYS = AUDIO_U16MSB
AUDIO_S16SYS = AUDIO_S16MSB
AUDIO_U16 = AUDIO_U16LSB
AUDIO_S16 = AUDIO_S16LSB
# From SDL_cdrom.h (inserted manually)
# enum CDstatus
(CD_TRAYEMPTY,
CD_STOPPED,
CD_PLAYING,
CD_PAUSED) = range(4)
CD_ERROR = -1
# From SDL_events.h (inserted manually)
# enum SDL_EventType
(SDL_NOEVENT,
SDL_ACTIVEEVENT,
SDL_KEYDOWN,
SDL_KEYUP,
SDL_MOUSEMOTION,
SDL_MOUSEBUTTONDOWN,
SDL_MOUSEBUTTONUP,
SDL_JOYAXISMOTION,
SDL_JOYBALLMOTION,
SDL_JOYHATMOTION,
SDL_JOYBUTTONDOWN,
SDL_JOYBUTTONUP,
SDL_QUIT,
SDL_SYSWMEVENT,
SDL_EVENT_RESERVEDA,
SDL_EVENT_RESERVEDB,
SDL_VIDEORESIZE,
SDL_VIDEOEXPOSE,
SDL_EVENT_RESERVED2,
SDL_EVENT_RESERVED3,
SDL_EVENT_RESERVED4,
SDL_EVENT_RESERVED5,
SDL_EVENT_RESERVED6,
SDL_EVENT_RESERVED7) = range(24)
SDL_USEREVENT = 24
SDL_NUMEVENTS = 32
def SDL_EVENTMASK(x):
'''Used for predefining event masks.'''
return 1 << x
# enum SDL_EventMask
SDL_ACTIVEEVENTMASK = SDL_EVENTMASK(SDL_ACTIVEEVENT)
SDL_KEYDOWNMASK = SDL_EVENTMASK(SDL_KEYDOWN)
SDL_KEYUPMASK = SDL_EVENTMASK(SDL_KEYUP)
SDL_KEYEVENTMASK = SDL_KEYUPMASK | \
SDL_KEYDOWNMASK
SDL_MOUSEMOTIONMASK = SDL_EVENTMASK(SDL_MOUSEMOTION)
SDL_MOUSEBUTTONDOWNMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN)
SDL_MOUSEBUTTONUPMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONUP)
SDL_MOUSEEVENTMASK = SDL_MOUSEMOTIONMASK | \
SDL_MOUSEBUTTONDOWNMASK | \
SDL_MOUSEBUTTONUPMASK
SDL_JOYAXISMOTIONMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION)
SDL_JOYBALLMOTIONMASK = SDL_EVENTMASK(SDL_JOYBALLMOTION)
SDL_JOYHATMOTIONMASK = SDL_EVENTMASK(SDL_JOYHATMOTION)
SDL_JOYBUTTONDOWNMASK = SDL_EVENTMASK(SDL_JOYBUTTONDOWN)
SDL_JOYBUTTONUPMASK = SDL_EVENTMASK(SDL_JOYBUTTONUP)
SDL_JOYEVENTMASK = SDL_JOYAXISMOTIONMASK | \
SDL_JOYBALLMOTIONMASK | \
SDL_JOYHATMOTIONMASK | \
SDL_JOYBUTTONDOWNMASK | \
SDL_JOYBUTTONUPMASK
SDL_QUITMASK = SDL_EVENTMASK(SDL_QUIT)
SDL_SYSWMEVENTMASK = SDL_EVENTMASK(SDL_SYSWMEVENT)
SDL_VIDEORESIZEMASK = SDL_EVENTMASK(SDL_VIDEORESIZE)
SDL_VIDEOEXPOSEMASK = SDL_EVENTMASK(SDL_VIDEOEXPOSE)
# enum SDL_eventaction
(SDL_ADDEVENT,
SDL_PEEKEVENT,
SDL_GETEVENT) = range(3)
#From SDL_joystick.h (inserted manually)
SDL_HAT_RIGHTUP = SDL_HAT_RIGHT | SDL_HAT_UP
SDL_HAT_RIGHTDOWN = SDL_HAT_RIGHT | SDL_HAT_DOWN
SDL_HAT_LEFTUP = SDL_HAT_LEFT | SDL_HAT_UP
SDL_HAT_LEFTDOWN = SDL_HAT_LEFT | SDL_HAT_DOWN
# From SDL_video.h (inserted manually)
# enum SDL_GLattr
(SDL_GL_RED_SIZE,
SDL_GL_GREEN_SIZE,
SDL_GL_BLUE_SIZE,
SDL_GL_ALPHA_SIZE,
SDL_GL_BUFFER_SIZE,
SDL_GL_DOUBLEBUFFER,
SDL_GL_DEPTH_SIZE,
SDL_GL_STENCIL_SIZE,
SDL_GL_ACCUM_RED_SIZE,
SDL_GL_ACCUM_GREEN_SIZE,
SDL_GL_ACCUM_BLUE_SIZE,
SDL_GL_ACCUM_ALPHA_SIZE,
SDL_GL_STEREO,
SDL_GL_MULTISAMPLEBUFFERS,
SDL_GL_MULTISAMPLESAMPLES,
SDL_GL_ACCELERATED_VISUAL,
SDL_GL_SWAP_CONTROL) = range(17)
# enum SDL_GrabMode
(SDL_GRAB_QUERY,
SDL_GRAB_OFF,
SDL_GRAB_ON) = range(-1,2)
# From SDL_ttf.h (inserted manually)
TTF_STYLE_NORMAL = 0x00
TTF_STYLE_BOLD = 0x01
TTF_STYLE_ITALIC = 0x02
TTF_STYLE_UNDERLINE = 0x04
# From SDL_mixer.h (inserted manually)
MIX_CHANNELS = 8
MIX_DEFAULT_FREQUENCY = 22050
MIX_MAX_VOLUME = 128
MIX_CHANNEL_POST = -2
MIX_EFFECTSMAXSPEED = 'MIX_EFFECTSMAXSPEED'
MIX_DEFAULT_CHANNELS = 2
if sys.byteorder == 'little':
MIX_DEFAULT_FORMAT = AUDIO_S16LSB
else:
MIX_DEFAULT_FORMAT = AUDIO_S16MSB
# enum Mix_Fading
(MIX_NO_FADING,
MIX_FADING_OUT,
MIX_FADING_IN) = range(3)
# enum Mix_MusicType
(MUS_NONE,
MUS_CMD,
MUS_WAV,
MUS_MOD,
MUS_MID,
MUS_OGG,
MUS_MP3) = range(7)
# From SDL_sound.h (inserted manually):
# enum Sound_SampleFlags
SOUND_SAMPLEFLAG_NONE = 0
SOUND_SAMPLEFLAG_CANSEEK = 1
SOUND_SAMPLEFLAG_EOF = 1 << 29
SOUND_SAMPLEFLAG_ERROR = 1 << 30
SOUND_SAMPLEFLAG_EGAIN = 1 << 31

View file

@ -1,153 +0,0 @@
#!/usr/bin/env python
'''Darwin (OS X) support.
Appropriated from pygame.macosx
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import os
import sys
# SDL-ctypes on OS X requires PyObjC
from Foundation import *
from AppKit import *
import objc
import MacOS
from .dll import version_compatible
from .events import SDL_Event, SDL_PushEvent
__all__ = ['init']
# Need to do this if not running with a nib
def setupAppleMenu(app):
appleMenuController = NSAppleMenuController.alloc().init()
appleMenuController.retain()
appleMenu = NSMenu.alloc().initWithTitle_('')
appleMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('', None, '')
appleMenuItem.setSubmenu_(appleMenu)
app.mainMenu().addItem_(appleMenuItem)
appleMenuController.controlMenu_(appleMenu)
app.mainMenu().removeItem_(appleMenuItem)
# Need to do this if not running with a nib
def setupWindowMenu(app):
windowMenu = NSMenu.alloc().initWithTitle_('Window')
windowMenu.retain()
menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Minimize', 'performMiniaturize:', 'm')
windowMenu.addItem_(menuItem)
windowMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Window', None, '')
windowMenuItem.setSubmenu_(windowMenu)
app.mainMenu().addItem_(windowMenuItem)
app.setWindowsMenu_(windowMenu)
# Used to cleanly terminate
class SDLAppDelegate(NSObject):
def applicationShouldTerminate_(self, app):
event = SDL_Event()
event.type = SDL_QUIT
SDL_PushEvent(event)
return NSTerminateLater
def windowUpdateNotification_(self, notification):
win = notification.object()
if not version_compatible((1, 2, 8)) and isinstance(win, objc.lookUpClass('SDL_QuartzWindow')):
# Seems to be a retain count bug in SDL.. workaround!
win.retain()
NSNotificationCenter.defaultCenter().removeObserver_name_object_(
self, NSWindowDidUpdateNotification, None)
self.release()
def setIcon(app, icon_data):
data = NSData.dataWithBytes_length_(icon_data, len(icon_data))
if data is None:
return
img = NSImage.alloc().initWithData_(data)
if img is None:
return
app.setApplicationIconImage_(img)
def install():
app = NSApplication.sharedApplication()
appDelegate = SDLAppDelegate.alloc().init()
app.setDelegate_(appDelegate)
appDelegate.retain()
NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
appDelegate,
'windowUpdateNotification:',
NSWindowDidUpdateNotification,
None)
if not app.mainMenu():
mainMenu = NSMenu.alloc().init()
app.setMainMenu_(mainMenu)
setupAppleMenu(app)
setupWindowMenu(app)
app.finishLaunching()
app.updateWindows()
app.activateIgnoringOtherApps_(True)
def S(*args):
return ''.join(args)
OSErr = objc._C_SHT
OUTPSN = 'o^{ProcessSerialNumber=LL}'
INPSN = 'n^{ProcessSerialNumber=LL}'
FUNCTIONS=[
# These two are public API
( u'GetCurrentProcess', S(OSErr, OUTPSN) ),
( u'SetFrontProcess', S(OSErr, INPSN) ),
# This is undocumented SPI
( u'CPSSetProcessName', S(OSErr, INPSN, objc._C_CHARPTR) ),
( u'CPSEnableForegroundOperation', S(OSErr, INPSN) ),
]
def WMEnable(name=None):
if name is None:
name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
if isinstance(name, unicode):
name = name.encode()
if not hasattr(objc, 'loadBundleFunctions'):
return False
bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework'))
if bndl is None:
print >>sys.stderr, 'ApplicationServices missing'
return False
d = {}
app = NSApplication.sharedApplication()
objc.loadBundleFunctions(bndl, d, FUNCTIONS)
for (fn, sig) in FUNCTIONS:
if fn not in d:
print >>sys.stderr, 'Missing', fn
return False
err, psn = d['GetCurrentProcess']()
if err:
print >>sys.stderr, 'GetCurrentProcess', (err, psn)
return False
err = d['CPSSetProcessName'](psn, name)
if err:
print >>sys.stderr, 'CPSSetProcessName', (err, psn)
return False
err = d['CPSEnableForegroundOperation'](psn)
if err:
print >>sys.stderr, 'CPSEnableForegroundOperation', (err, psn)
return False
err = d['SetFrontProcess'](psn)
if err:
print >>sys.stderr, 'SetFrontProcess', (err, psn)
return False
return True
def init():
if not (MacOS.WMAvailable() or WMEnable()):
raise ImportError("Can not access the window manager. Use py2app or execute with the pythonw script.")
if not NSApp():
# running outside of a bundle
install()
# running inside a bundle, change dir
if (os.getcwd() == '/') and len(sys.argv) > 1:
os.chdir(os.path.dirname(sys.argv[0]))
return True

View file

@ -1,230 +0,0 @@
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
#from ctypes.util import find_library
from m64py.loader import find_library
import sys
# Private version checking declared before SDL.version can be
# imported.
class _SDL_version(Structure):
_fields_ = [('major', c_ubyte),
('minor', c_ubyte),
('patch', c_ubyte)]
def __repr__(self):
return '%d.%d.%d' % \
(self.major, self.minor, self.patch)
def _version_parts(v):
'''Return a tuple (major, minor, patch) for `v`, which can be
an _SDL_version, string or tuple.'''
if hasattr(v, 'major') and hasattr(v, 'minor') and hasattr(v, 'patch'):
return v.major, v.minor, v.patch
elif type(v) == tuple:
return v
elif type(v) == str:
return tuple([int(i) for i in v.split('.')])
else:
raise TypeError
def _version_string(v):
return '%d.%d.%d' % _version_parts(v)
def _platform_library_name(library):
if sys.platform[:5] == 'linux':
return 'lib%.so' % library
elif sys.platform == 'darwin':
return '%s.dylib' % library
elif sys.platform == 'windows':
return '%s.dll' % library
return library
class SDL_DLL:
def __init__(self, library_name, version_function_name):
if sys.platform[:5] == 'linux':
library_name = '%s-1.2' % library_name
elif sys.platform == 'darwin':
library_name = '%s-1.2.0' % library_name
self.library_name = library_name
library = find_library(library_name)
if not library:
raise ImportError('Dynamic library "%s" was not found' % \
_platform_library_name(library_name))
self._dll = getattr(cdll, library)
# Get the version of the DLL we're using
if version_function_name:
try:
version_function = getattr(self._dll, version_function_name)
version_function.restype = POINTER(_SDL_version)
self._version = _version_parts(version_function().contents)
except AttributeError:
self._version = (0, 0, 0)
else:
self._version = (0, 0, 0)
def version_compatible(self, v):
'''Returns True iff `v` is equal to or later than the loaded library
version.'''
v = _version_parts(v)
for i in range(3):
if self._version[i] < v[i]:
return False
return True
def assert_version_compatible(self, name, since):
'''Raises an exception if `since` is later than the loaded library.'''
if not version_compatible(since):
from .error import SDL_NotImplementedError
raise SDL_NotImplementedError \
('%s requires SDL version %s; currently using version %s' % \
(name, _version_string(since), _version_string(self._version)))
def private_function(self, name, **kwargs):
'''Construct a wrapper function for ctypes with internal documentation
and no argument names.'''
kwargs['doc'] = 'Private wrapper for %s' % name
kwargs['args'] = []
return self.function(name, **kwargs)
def function(self, name, doc, args=[], arg_types=[],
return_type=None,
dereference_return=False,
require_return=False,
success_return=None,
error_return=None,
since=None):
'''Construct a wrapper function for ctypes.
:Parameters:
`name`
The name of the function as it appears in the shared library.
`doc`
Docstring to associate with the wrapper function.
`args`
List of strings giving the argument names.
`arg_types`
List of ctypes classes giving the argument types.
`return_type`
The ctypes class giving the wrapped function's native
return type.
`dereference_return`
If True, the return value is assumed to be a pointer and
will be dereferenced via ``.contents`` before being
returned to the user application.
`require_return`
Used in conjunction with `dereference_return`; if True, an
exception will be raised if the result is NULL; if False
None will be returned when the result is NULL.
`success_return`
If not None, the expected result of the wrapped function.
If the return value does not equal success_return, an
exception will be raised.
`error_return`
If not None, the error result of the wrapped function. If
the return value equals error_return, an exception will be
raised. Cannot be used in conjunction with
`success_return`.
`since`
Tuple (major, minor, patch) or string 'x.y.z' of the first
version of SDL in which this function appears. If the
loaded version predates it, a placeholder function that
raises `SDL_NotImplementedError` will be returned instead.
Set to None if the function is in all versions of SDL.
'''
# Check for version compatibility first
if since and not self.version_compatible(since):
def _f(*args, **kwargs):
from .error import SDL_NotImplementedError
raise SDL_NotImplementedError \
('%s requires %s %s; currently using version %s' % \
(name, self.library_name, _version_string(since),
_version_string(self._version)))
if args:
_f._args = args
_f.__doc__ = doc
try:
_f.func_name = name
except TypeError: # read-only in Python 2.3
pass
return _f
# Ok, get function from ctypes
func = getattr(self._dll, name)
func.argtypes = arg_types
func.restype = return_type
if dereference_return:
if require_return:
# Construct a function which dereferences the pointer result,
# or raises an exception if NULL is returned.
def _f(*args, **kwargs):
result = func(*args, **kwargs)
if result:
return result.contents
from .error import SDL_Exception, SDL_GetError
raise SDL_Exception(SDL_GetError())
else:
# Construct a function which dereferences the pointer result,
# or returns None if NULL is returned.
def _f(*args, **kwargs):
result = func(*args, **kwargs)
if result:
return result.contents
return None
elif success_return is not None:
# Construct a function which returns None, but raises an exception
# if the C function returns a failure code.
def _f(*args, **kwargs):
result = func(*args, **kwargs)
if result != success_return:
from .error import SDL_Exception, SDL_GetError
raise SDL_Exception(SDL_GetError())
return result
elif error_return is not None:
# Construct a function which returns None, but raises an exception
# if the C function returns a failure code.
def _f(*args, **kwargs):
result = func(*args, **kwargs)
if result == error_return:
from .error import SDL_Exception, SDL_GetError
raise SDL_Exception(SDL_GetError())
return result
elif require_return:
# Construct a function which returns the usual result, or returns
# None if NULL is returned.
def _f(*args, **kwargs):
result = func(*args, **kwargs)
if not result:
from .error import SDL_Exception, SDL_GetError
raise SDL_Exception(SDL_GetError())
return result
else:
# Construct a function which returns the C function's return
# value.
def _f(*args, **kwargs):
return func(*args, **kwargs)
if args:
_f._args = args
_f.__doc__ = doc
try:
_f.func_name = name
except TypeError: # read-only in Python 2.3
pass
return _f
# Shortcuts to the SDL core library
_dll = SDL_DLL('SDL', 'SDL_Linked_Version')
version_compatible = _dll.version_compatible
assert_version_compatible = _dll.assert_version_compatible
private_function = _dll.private_function
function = _dll.function

View file

@ -1,46 +0,0 @@
#!/usr/bin/env python
'''Functions for converting to native byte order
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import sys
from .constants import SDL_BIG_ENDIAN, SDL_LIL_ENDIAN
def SDL_Swap16(x):
return (x << 8 & 0xff00) | \
(x >> 8 & 0x00ff)
def SDL_Swap32(x):
return (x << 24 & 0xff000000) | \
(x << 8 & 0x00ff0000) | \
(x >> 8 & 0x0000ff00) | \
(x >> 24 & 0x000000ff)
def SDL_Swap64(x):
return (SDL_Swap32(x & 0xffffffff) << 32) | \
(SDL_Swap32(x >> 32 & 0xffffffff))
def _noop(x):
return x
if sys.byteorder == 'big':
SDL_BYTEORDER = SDL_BIG_ENDIAN
SDL_SwapLE16 = SDL_Swap16
SDL_SwapLE32 = SDL_Swap32
SDL_SwapLE64 = SDL_Swap64
SDL_SwapBE16 = _noop
SDL_SwapBE32 = _noop
SDL_SwapBE64 = _noop
else:
SDL_BYTEORDER = SDL_LIL_ENDIAN
SDL_SwapLE16 = _noop
SDL_SwapLE32 = _noop
SDL_SwapLE64 = _noop
SDL_SwapBE16 = SDL_Swap16
SDL_SwapBE32 = SDL_Swap32
SDL_SwapBE64 = SDL_Swap64

View file

@ -1,57 +0,0 @@
#!/usr/bin/env python
'''Error detection and error handling functions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .dll import function
class SDL_Exception(Exception):
'''Exception raised for all SDL errors.
The message is as returned by `SDL_GetError`.
'''
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class SDL_NotImplementedError(NotImplementedError):
'''Exception raised when the available SDL library predates the
requested function.'''
pass
SDL_SetError = function('SDL_SetError',
'''Set the static error string.
:Parameters:
`fmt`
format string; subsequent integer and string arguments are
interpreted as in printf().
''',
args=['fmt'],
arg_types=[c_char_p],
return_type=None)
SDL_GetError = function('SDL_GetError',
'''Return the last error string set.
:rtype: string
''',
args=[],
arg_types=[],
return_type=c_char_p)
SDL_ClearError = function('SDL_ClearError',
'''Clear any error string set.
''',
args=[],
arg_types=[],
return_type=None)
# SDL_Error not implemented (marked private in SDL_error.h)

View file

@ -1,538 +0,0 @@
#!/usr/bin/env python
'''Event handling.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .constants import *
from .dll import function, private_function
from .keyboard import SDL_keysym
from .error import SDL_Exception, SDL_GetError
class SDL_ActiveEvent(Structure):
'''Application visibility event structure.
:see: `SDL_GetAppState`
:Ivariables:
`type` : int
SDL_ACTIVEEVENT
`gain` : int
1 if states were gained, zero otherwise
`state` : int
A mask of the focus states. A bitwise OR combination of:
SDL_APPMOUSEFOCUS, SDL_APPINPUTFOCUS and SDL_APPACTIVE.
'''
_fields_ = [('type', c_ubyte),
('gain', c_ubyte),
('state', c_ubyte)]
class SDL_KeyboardEvent(Structure):
'''Keyboard event structure.
:Ivariables:
`type` : int
SDL_KEYDOWN or SDL_KEYUP
`which` : int
The keyboard device index
`state` : int
SDL_PRESSED or SDL_RELEASED
`keysym` : `SDL_keysym`
Decoded key information.
'''
_fields_ = [('type', c_ubyte),
('which', c_ubyte),
('state', c_ubyte),
('keysym', SDL_keysym)]
class SDL_MouseMotionEvent(Structure):
'''Mouse motion event structure.
:Ivariables:
`type` : int
SDL_MOUSEMOTION
`which` : int
The mouse device index
`state` : int
The current button state
`x` : int
The X coordinate of the mouse pointer
`y` : int
The Y coordinate of the mouse pointer
`xrel` : int
The relative motion in the X direction
`yrel` : int
The relative motion in the Y direction
'''
_fields_ = [('type', c_ubyte),
('which', c_ubyte),
('state', c_ubyte),
('x', c_ushort),
('y', c_ushort),
('xrel', c_short),
('yrel', c_short)]
class SDL_MouseButtonEvent(Structure):
'''Mouse button event structure.
:Ivariables:
`type` : int
SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP
`which` : int
The mouse device index
`button` : int
The mouse button index
`state` : int
SDL_PRESSED or SDL_RELEASED
`x` : int
The X coordinate of the mouse pointer
`y` : int
The Y coordinate of the mouse pointer
'''
_fields_ = [('type', c_ubyte),
('which', c_ubyte),
('button', c_ubyte),
('state', c_ubyte),
('x', c_ushort),
('y', c_ushort)]
class SDL_JoyAxisEvent(Structure):
'''Joystick axis motion event structure.
:Ivariables:
`type` : int
SDL_JOYAXISMOTION
`which` : int
The joystick device index
`axis` : int
The joystick axis index
`value` : int
The axis value, in range [-32768, 32767]
'''
_fields_ = [('type', c_ubyte),
('which', c_ubyte),
('axis', c_ubyte),
('value', c_short)]
class SDL_JoyBallEvent(Structure):
'''Joystick trackball motion event structure.
:Ivariables:
`type` : int
SDL_JOYBALLMOTION
`which` : int
The joystick device index
`ball` : int
The joystick trackball index
`xrel` : int
The relative motion in the X direction
`yrel` : int
The relative motion in the Y direction
'''
_fields_ = [('type', c_ubyte),
('which', c_ubyte),
('ball', c_ubyte),
('xrel', c_short),
('yrel', c_short)]
class SDL_JoyHatEvent(Structure):
'''Joystick hat position change event structure.
:Ivariables:
`type` : int
SDL_JOYHATMOTION
`which` : int
The joystick device index
`hat` : int
The joystick hat index
`value` : int
The hat position value. One of: SDL_HAT_LEFTUP, SDL_HAT_UP,
SDL_HAT_RIGHTUP, SDL_HAT_LEFT, SDL_HAT_CENTERED, SDL_HAT_RIGHT,
SDL_HAT_LEFTDOWN, SDL_HAT_DOWN, SDL_HAT_RIGHTDOWN. Note that
zero means the POV is centered.
'''
_fields_ = [('type', c_ubyte),
('which', c_ubyte),
('hat', c_ubyte),
('value', c_ubyte)]
class SDL_JoyButtonEvent(Structure):
'''Joystick button event structure.
:Ivariables:
`type` : int
SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP
`which` : int
The joystick device index
`button` : int
The joystick button index
`state` : int
SDL_PRESSED or SDL_RELEASED
'''
_fields_ = [('type', c_ubyte),
('which', c_ubyte),
('button', c_ubyte),
('state', c_ubyte)]
class SDL_ResizeEvent(Structure):
'''The window resized event structure.
:Ivariables:
`type` : int
SDL_VIDEORESIZE
`w` : int
New width
`h` : int
New height
'''
_fields_ = [('type', c_ubyte),
('w', c_int),
('h', c_int)]
class SDL_ExposeEvent(Structure):
'''The screen redraw event structure.
:Ivariables:
`type` : int
SDL_VIDEOEXPOSE
'''
_fields_ = [('type', c_ubyte)]
class SDL_QuitEvent(Structure):
'''The quit requested event structure
:Ivariables:
`type` : int
SDL_QUIT
'''
_fields_ = [('type', c_ubyte)]
class SDL_UserEvent(Structure):
'''A user-defined event structure.
:Ivariables:
`type` : int
SDL_USEREVENT through SDL_NUMEVENTS - 1
`code` : int
User defined event code
'''
# pygame-ctypes needs data1 and data2 to be c_void_p; POINTER(c_ubyte)
# or similar will break it (see pygame/event.py) unless another workaround
# can be found.
_fields_ = [('type', c_ubyte),
('code', c_int),
('data1', c_void_p),
('data2', c_void_p)]
class SDL_SysWMEvent(Structure):
'''System window management event structure.
:Ivariables:
`type` : int
SDL_SYSWMEVENT
'''
_fields_ = [('type', c_ubyte),
('msg', c_void_p)] # TODO with SDL_syswm.h
class SDL_Event(Union):
'''Union event structure.
Events returned from functions are always returned as the
specialised subclass; for example you will receive a
`SDL_MouseMotionEvent` rather than `SDL_Event`. This structure
therefore has limited application use, but is used internally.
:Ivariables:
`type` : int
Type of event
'''
_fields_ = [('type', c_ubyte),
('active', SDL_ActiveEvent),
('key', SDL_KeyboardEvent),
('motion', SDL_MouseMotionEvent),
('button', SDL_MouseButtonEvent),
('jaxis', SDL_JoyAxisEvent),
('jball', SDL_JoyBallEvent),
('jhat', SDL_JoyHatEvent),
('jbutton', SDL_JoyButtonEvent),
('resize', SDL_ResizeEvent),
('expose', SDL_ExposeEvent),
('quit', SDL_QuitEvent),
('user', SDL_UserEvent),
('syswm', SDL_SysWMEvent)]
types = {
SDL_ACTIVEEVENT: (SDL_ActiveEvent, 'active'),
SDL_KEYDOWN: (SDL_KeyboardEvent, 'key'),
SDL_KEYUP: (SDL_KeyboardEvent, 'key'),
SDL_MOUSEMOTION: (SDL_MouseMotionEvent, 'motion'),
SDL_MOUSEBUTTONDOWN: (SDL_MouseButtonEvent, 'button'),
SDL_MOUSEBUTTONUP: (SDL_MouseButtonEvent, 'button'),
SDL_JOYAXISMOTION: (SDL_JoyAxisEvent, 'jaxis'),
SDL_JOYBALLMOTION: (SDL_JoyBallEvent, 'jball'),
SDL_JOYHATMOTION: (SDL_JoyHatEvent, 'jhat'),
SDL_JOYBUTTONDOWN: (SDL_JoyButtonEvent, 'jbutton'),
SDL_JOYBUTTONUP: (SDL_JoyButtonEvent, 'jbutton'),
SDL_VIDEORESIZE: (SDL_ResizeEvent, 'resize'),
SDL_VIDEOEXPOSE: (SDL_ExposeEvent, 'expose'),
SDL_QUIT: (SDL_QuitEvent, 'quit'),
SDL_SYSWMEVENT: (SDL_SysWMEvent, 'syswm')
}
def __init__(self, typecode=0):
self.type = typecode
def __repr__(self):
if self.type in self.types:
return self.types[self.type][0].__repr__(self)
elif self.type >= SDL_USEREVENT:
# SDL_MAXEVENTS not defined
return SDL_UserEvent.__repr__(self)
return 'SDLEvent(type=%d)' % self.type
def specialize(self):
'''Get an instance of the specialized subclass for this event,
based on `self.type`.
:rtype: `SDL_Event` subclass
'''
if self.type in self.types:
return getattr(self, self.types[self.type][1])
elif self.type >= SDL_USEREVENT:
# SDL_MAXEVENTS not defined
return self.user
return self
SDL_PumpEvents = function('SDL_PumpEvents',
'''Pumps the event loop, gathering events from the input devices.
This function updates the event queue and internal input device state.
This should only be run in the thread that sets the video mode.
''',
args=[],
arg_types=[],
return_type=None)
_SDL_PeepEvents = private_function('SDL_PeepEvents',
arg_types=[POINTER(SDL_Event), c_int, c_int, c_uint],
return_type=c_int)
def SDL_PeepEvents(numevents, action, mask):
'''Check the event queue for messages and optionally return them.
The behaviour depends on `action`:
`SDL_ADDEVENT`
Not implemented; will raise an exception. See `SDL_PushEvent`.
`SDL_PEEKEVENT`
Up to `numevents` events at the front of the event queue,
matching `mask`, will be returned and will not be removed
from the queue.
`SDL_GETEVENT`
Up to `numevents` events at the front of the event queue,
matching `mask`, will be returned and will be removed from the
queue.
:Parameters:
`numevents` : int
Maximum number of events to return
`action` : int
Either `SDL_PEEKEVENT` or `SDL_GETEVENT`
`mask` : int
Mask to match type of returned events with.
:rtype: list
:return: list of SDL_Event (or subclass)
:see: `SDL_PushEvent`, `SDL_HaveEvents`
'''
if action == SDL_ADDEVENT:
raise NotImplementedError('Use SDL_PushEvent to add events')
ar = (SDL_Event * numevents)()
num = _SDL_PeepEvents(ar, numevents, action, mask)
if num == -1:
raise SDL_Exception(SDL_GetError())
return list([e.specialize() for e in ar[:num]])
def SDL_HaveEvents(mask):
'''Check the event queue for events matching the given mask.
:note: This function replaces the C function
SDL_PeepEvents(NULL, ...), which had undocumented behaviour.
:Parameters:
`mask` : int
Mask to match type of returned events with.
:rtype: bool
:return: True if at least one event matches the mask in the event
queue.
'''
num = _SDL_PeepEvents(None, 1, SDL_PEEKEVENT, mask)
return num > 0
_SDL_PollEvent = private_function('SDL_PollEvent',
arg_types=[POINTER(SDL_Event)],
return_type=c_int)
def SDL_PollEvent():
'''Poll for currently pending events.
Returns True if there are any pending events, or False if there are none
available.
:see: `SDL_PollEventAndReturn`
:rtype: bool
'''
return _SDL_PollEvent(None) == 1
def SDL_PollEventAndReturn():
'''Poll for currently pending events, and return one off the queue
if possible.
:see: `SDL_PollEvent`
:rtype: `SDL_Event` or subclass
'''
e = SDL_Event()
result = _SDL_PollEvent(byref(e))
if result == 1:
return e.specialize()
return None
_SDL_WaitEvent = private_function('SDL_WaitEvent',
arg_types=[POINTER(SDL_Event)],
return_type=c_int)
def SDL_WaitEvent():
'''Wait indefinitely for an event.
Returns when an event is available on the queue, or raises an exception
if an error occurs while waiting.
:see: `SDL_WaitEventAndReturn`
'''
if _SDL_WaitEvent(None) == 0:
raise SDL_Exception(SDL_GetError())
def SDL_WaitEventAndReturn():
'''Wait indefinitely for the next event and return it.
:see: `SDL_WaitEvent`
:rtype: `SDL_Event` or subclass
'''
ev = SDL_Event()
result = _SDL_WaitEvent(byref(ev))
if result == 1:
return ev.specialize()
else:
raise SDL_Exception(SDL_GetError())
SDL_PushEvent = function('SDL_PushEvent',
'''Add an event to the event queue.
:Parameters:
- `event`: `SDL_Event`
''',
args=['event'],
arg_types=[POINTER(SDL_Event)],
return_type=c_int,
error_return=-1)
_SDL_EventFilter = CFUNCTYPE(c_int, POINTER(SDL_Event))
_SDL_SetEventFilter = private_function('SDL_SetEventFilter',
arg_types=[_SDL_EventFilter],
return_type=None)
_eventfilter_ref = None # keep global to avoid GC of anon func
def SDL_SetEventFilter(filter):
'''Set up a filter to process all events before they change internal
state and are posted to the internal event queue.
:warning: Be very careful of what you do in the event filter function,
as it may run in a different thread.
There is one caveat when dealing with the `SDL_QUITEVENT` event type.
The event filter is only called when the window manager desires to
close the application window. If the event filter returns 1, then the
window will be closed, otherwise the window will remain open if
possible. If the quit event is generated by an interrupt signal, it
will bypass the internal queue and be delivered to the application at
the next event poll.
:Parameters:
`filter` : function
a function that takes an `SDL_Event` as a single argument. If
the function returns 1 the event will be added to the internal
queue. If it returns 0, the event will be dropped from the
queue, but the internal state will still be updated. The event
instance must not be modified.
'''
global _eventfilter_ref
if filter:
def f(e):
return filter(e.contents.specialize())
_eventfilter_ref = _SDL_EventFilter(f)
else:
_eventfilter_ref = _SDL_EventFilter()
_SDL_SetEventFilter(_eventfilter_ref)
SDL_GetEventFilter = function('SDL_GetEventFilter',
'''Return the current event filter.
This can be used to "chain" filters. If there is no event filter set,
this function returns None.
:rtype: function
''',
args=[],
arg_types=[],
return_type=_SDL_EventFilter)
SDL_EventState = function('SDL_EventState',
'''Ignore or enable the processing of certain events.
The behaviour of this function depends on `state`
`SDL_IGNORE`
the event will be automatically dropped from the event queue
and will not be event filtered.
`SDL_ENABLE`
the event will be processed normally.
`SDL_QUERY`
return the current processing state of the event.
:Parameters:
`type` : int
Type of event, e.g. `SDL_KEYDOWN`, `SDL_MOUSEMOTION`, etc.
(see `SDL_Event`)
`state` : int
One of `SDL_IGNORE`, `SDL_ENABLE` or `SDL_QUERY`
:rtype: int
:return: the event processing state: either `SDL_IGNORE or
`SDL_ENABLE`.
''',
args=['type', 'state'],
arg_types=[c_ubyte, c_int],
return_type=c_int)

View file

@ -1,461 +0,0 @@
#!/usr/bin/env python
'''Load images of various formats as SDL surfaces.
This module supports BMP, PNM (PPM/PGM/PBM), XPM, LBM, PCX, GIF, JPEG, PNG,
TGA and TIFF formats.
Typical usage::
from SDL.image import *
surface = IMG_Load('image.png')
:note: Early versions of this library (pre-1.2.5) do not have versioning
information; do not count on `IMG_Linked_Version` being available.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .dll import SDL_DLL
from .error import SDL_NotImplementedError
from .rwops import SDL_RWops
from .version import SDL_version
from .video import SDL_Surface
_dll = SDL_DLL('SDL_image', 'IMG_Linked_Version')
IMG_Linked_Version = _dll.function('IMG_Linked_Version',
'''Get the version of the dynamically linked SDL_image library.
:since: SDL_image 1.2.5
''',
args=[],
arg_types=[],
return_type=POINTER(SDL_version),
dereference_return=True,
require_return=True,
since=(1,2,5))
IMG_LoadTyped_RW = _dll.function('IMG_LoadTyped_RW',
'''Load an image from an SDL data source, specifying a type.
If the image format supports a transparent pixel, SDL will set the
colorkey for the surface. You can enable RLE acceleration on the
surface afterwards by calling::
SDL_SetColorKey(image, SDL_RLEACCEL, image.format.colorkey)
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
`freesrc` : int
If non-zero, the source will be freed after loading.
`type` : string
One of "BMP", "GIF", "PNG", etc.
:rtype: `SDL_Surface`
''',
args=['src', 'freesrc', 'type'],
arg_types=[POINTER(SDL_RWops), c_int, c_char_p],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_Load = _dll.function('IMG_Load',
'''Load an image from a file.
If the image format supports a transparent pixel, SDL will set the
colorkey for the surface. You can enable RLE acceleration on the
surface afterwards by calling::
SDL_SetColorKey(image, SDL_RLEACCEL, image.format.colorkey)
:Parameters:
`file` : string
Filename to load.
:rtype: `SDL_Surface`
''',
args=['file'],
arg_types=[c_char_p],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_Load_RW = _dll.function('IMG_Load_RW',
'''Load an image from an SDL data source.
If the image format supports a transparent pixel, SDL will set the
colorkey for the surface. You can enable RLE acceleration on the
surface afterwards by calling::
SDL_SetColorKey(image, SDL_RLEACCEL, image.format.colorkey)
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
`freesrc` : int
If non-zero, the source will be freed after loading.
:rtype: `SDL_Surface`
''',
args=['src', 'freesrc'],
arg_types=[POINTER(SDL_RWops), c_int],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
# IMG_InvertAlpha is a no-op.
IMG_isBMP = _dll.function('IMG_isBMP',
'''Detect if a seekable source is a BMP image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int)
IMG_isGIF = _dll.function('IMG_isGIF',
'''Detect if a seekable source is a GIF image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int)
IMG_isJPG = _dll.function('IMG_isJPG',
'''Detect if a seekable source is a JPG image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int)
IMG_isLBM = _dll.function('IMG_isLBM',
'''Detect if a seekable source is a LBM image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int)
IMG_isPCX = _dll.function('IMG_isPCX',
'''Detect if a seekable source is a PCX image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int)
IMG_isPNG = _dll.function('IMG_isPNG',
'''Detect if a seekable source is a PNG image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int)
IMG_isPNM = _dll.function('IMG_isPNM',
'''Detect if a seekable source is a PNM image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int)
IMG_isTIF = _dll.function('IMG_isTIF',
'''Detect if a seekable source is a TIF image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int)
IMG_isXCF = _dll.function('IMG_isXCF',
'''Detect if a seekable source is a XCF image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int)
IMG_isXPM = _dll.function('IMG_isXPM',
'''Detect if a seekable source is a XPM image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int)
if hasattr(_dll._dll, 'IMG_isXV'):
IMG_isXV = _dll.function('IMG_isXV',
'''Detect if a seekable source is a XV image.
:Parameters:
`src` : `SDL_RWops`
Source RWops to inspect.
:rtype: int
:since: SDL_image 1.2.5
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=c_int,
since=(1,2,5))
else:
# Broken build of SDL_image 1.2.5 on OS X does define xv.c symbols
def IMG_isXV(src):
raise SDL_NotImplementedError('Linked version of ' + \
'SDL_image does not define IMG_isXV')
IMG_LoadBMP_RW = _dll.function('IMG_LoadBMP_RW',
'''Load a BMP image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_LoadGIF_RW = _dll.function('IMG_LoadGIF_RW',
'''Load a GIF image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_LoadJPG_RW = _dll.function('IMG_LoadJPG_RW',
'''Load a JPG image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_LoadLBM_RW = _dll.function('IMG_LoadLBM_RW',
'''Load a LBM image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_LoadPCX_RW = _dll.function('IMG_LoadPCX_RW',
'''Load a PCX image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_LoadPNG_RW = _dll.function('IMG_LoadPNG_RW',
'''Load a PNG image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_LoadPNM_RW = _dll.function('IMG_LoadPNM_RW',
'''Load a PNM image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_LoadTGA_RW = _dll.function('IMG_LoadTGA_RW',
'''Load a TGA image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_LoadTIF_RW = _dll.function('IMG_LoadTIF_RW',
'''Load a TIF image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_LoadXCF_RW = _dll.function('IMG_LoadXCF_RW',
'''Load a XCF image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
IMG_LoadXPM_RW = _dll.function('IMG_LoadXPM_RW',
'''Load a XPM image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True)
if hasattr(_dll._dll, 'IMG_LoadXV_RW'):
IMG_LoadXV_RW = _dll.function('IMG_LoadXV_RW',
'''Load a XV image from an SDL data source.
:Parameters:
`src` : `SDL_RWops`
Source RWops to load from.
:rtype: `SDL_Surface`
:since: SDL_image 1.2.5
''',
args=['src'],
arg_types=[POINTER(SDL_RWops)],
return_type=POINTER(SDL_Surface),
dereference_return=True,
require_return=True,
since=(1,2,5))
else:
# Broken build of SDL_image 1.2.5 on OS X does define xv.c symbols
def IMG_LoadXV_RW(src):
raise SDL_NotImplementedError('Linked version of ' + \
'SDL_image does not define IMG_LoadXV_RW')
# IMG_ReadXPMFromArray cannot be implemented.

View file

@ -1,249 +0,0 @@
#!/usr/bin/env python
'''Joystick event handling.
TODO: This module is completely untested.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .dll import function, private_function
class _SDL_Joystick(Structure):
_fields_ = [('_dummy', c_void_p)]
SDL_Joystick_p = POINTER(_SDL_Joystick)
SDL_NumJoysticks = function('SDL_NumJoysticks',
'''Count the number of joysticks attached to the system.
:rtype: int
''',
args=[],
arg_types=[],
return_type=c_int)
SDL_JoystickName = function('SDL_JoystickName',
'''Get the implementation dependent name of a joystick.
This can be called before any joysticks are opened. If no name can be
found, this function returns None.
:Parameters:
- `device_index`: int
:rtype: str
''',
args=['device_index'],
arg_types=[c_int],
return_type=c_char_p)
SDL_JoystickOpen = function('SDL_JoystickOpen',
'''Open a joystick for use.
The index passed as an argument refers to the N'th joystick on the
system. This index is the value which will identify this joystick in
future joystick events.
This function returns an opaque joystick identifier.
:Parameters:
- `device_index`: int
:rtype: `SDL_Joystick_p`
''',
args=['device_index'],
arg_types=[c_int],
return_type=SDL_Joystick_p,
require_return=True)
SDL_JoystickOpened = function('SDL_JoystickOpened',
'''Determine if a joystick has been opened.
:Parameters:
- `device_index`: int
:rtype: `int`
:return: 1 if the joystick has been opened, or 0 if it has not.
''',
args=['device_index'],
arg_types=[c_int],
return_type=c_int)
SDL_JoystickIndex = function('SDL_JoystickIndex',
'''Get the device index of an opened joystick.
:Parameters:
- `joystick`: `SDL_Joystick_p`
:rtype: int
''',
args=['joystick'],
arg_types=[SDL_Joystick_p],
return_type=c_int)
SDL_JoystickNumAxes = function('SDL_JoystickNumAxes',
'''Get the number of general axis controls on a joystick.
:Parameters:
- `joystick`: `SDL_Joystick_p`
:rtype: int
''',
args=['joystick'],
arg_types=[SDL_Joystick_p],
return_type=c_int)
SDL_JoystickNumBalls = function('SDL_JoystickNumBalls',
'''Get the number of trackballs on a joystick.
Joystick trackballs have only relative motion events associated with
them and their state cannot be polled.
:Parameters:
- `joystick`: `SDL_Joystick_p`
:rtype: int
''',
args=['joystick'],
arg_types=[SDL_Joystick_p],
return_type=c_int)
SDL_JoystickNumHats = function('SDL_JoystickNumHats',
'''Get the number of POV hats on a joystick.
:Parameters:
- `joystick`: `SDL_Joystick_p`
:rtype: int
''',
args=['joystick'],
arg_types=[SDL_Joystick_p],
return_type=c_int)
SDL_JoystickNumButtons = function('SDL_JoystickNumButtons',
'''Get the number of buttons on a joystick.
:Parameters:
- `joystick`: `SDL_Joystick_p`
:rtype: int
''',
args=['joystick'],
arg_types=[SDL_Joystick_p],
return_type=c_int)
SDL_JoystickUpdate = function('SDL_JoystickUpdate',
'''Update the current state of the open joysticks.
This is called automatically by the event loop if any joystick events
are enabled.
''',
args=[],
arg_types=[],
return_type=None)
SDL_JoystickEventState = function('SDL_JoystickEventState',
'''Enable/disable joystick event polling.
If joystick events are disabled, you must call `SDL_JoystickUpdate`
yourself and check the state of the joystick when you want joystick
information.
:Parameters:
`state` : int
one of SDL_QUERY, SDL_ENABLE or SDL_IGNORE.
:rtype: int
:return: undocumented
''',
args=['state'],
arg_types=[c_int],
return_type=c_int)
SDL_JoystickGetAxis = function('SDL_JoystickGetAxis',
'''Get the current state of an axis control on a joystick.
The axis indices start at index 0.
:Parameters:
- `joystick`: `SDL_Joystick_p`
- `axis`: int
:rtype: int
:return: a value ranging from -32,768 to 32767.
''',
args=['joystick', 'axis'],
arg_types=[SDL_Joystick_p, c_int],
return_type=c_short)
SDL_JoystickGetHat = function('SDL_JoystickGetHat',
'''Get the current state of POV hat on a joystick.
The hat indices start at index 0.
:Parameters:
- `joystick`: `SDL_Joystick_p`
- `hat`: int
:rtype: int
:return: one of `SDL_HAT_CENTERED`, `SDL_HAT_UP`, `SDL_HAT_LEFT`,
`SDL_HAT_DOWN`, `SDL_HAT_RIGHT`, `SDL_HAT_RIGHTUP`,
`SDL_HAT_RIGHTDOWN`, `SDL_HAT_RIGHTUP`, `SDL_HAT_LEFTUP`,
`SDL_HAT_LEFTDOWN`.
''',
args=['joystick', 'hat'],
arg_types=[SDL_Joystick_p, c_int],
return_type=c_ubyte)
_SDL_JoystickGetBall = private_function('SDL_JoystickGetBall',
arg_types=[SDL_Joystick_p, c_int, POINTER(c_int), POINTER(c_int)],
return_type=c_int,
error_return=-1)
def SDL_JoystickGetBall(joystick, ball):
'''Get the ball axis change since the last poll.
The ball indicies start at index 0.
:Parameters:
- `joystick`: `SDL_Joystick_p`
- `ball`: int
:rtype: (int, int)
:return: a tuple (dx, dy) of the relative motion of the ball.
'''
dx, dy = c_int(), c_int()
_SDL_JoystickGetBall(joystick, ball, byref(x), byref(y))
return dx.value, dy.value
SDL_JoystickGetButton = function('SDL_JoystickGetButton',
'''Get the current state of a button on a joystick.
The button indices start at index 0.
:Parameters:
- `joystick`: `SDL_Joystick_p`
- `button`: int
:rtype: int
:return: undocumented
''',
args=['joystick', 'button'],
arg_types=[SDL_Joystick_p, c_int],
return_type=c_ubyte)
SDL_JoystickClose = function('SDL_JoystickClose',
'''Close a joystick previously opened with `SDL_JoystickOpen`.
:Parameters:
- `joystick`: `SDL_Joystick_p`
''',
args=['joystick'],
arg_types=[SDL_Joystick_p],
return_type=None)

View file

@ -1,158 +0,0 @@
#!/usr/bin/env python
'''Keyboard event handling.
You should call `SDL_Init` with `SDL_INIT_VIDEO` before using these functions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .dll import function, private_function
class SDL_keysym(Structure):
'''Keysym structure
* The scancode is hardware dependent, and should not be used by
general applications. If no hardware scancode is available, it will
be 0
* The `unicode` translated character is only available when character
translation is enabled by `SDL_EnableUNICODE`. If non-empty, this is
unicode string of unit length.
:Ivariables:
`scancode` : int
Hardware specific scancode
`sym` : int
SDL virtual keysym (SDLK_*)
`mod` : int
Bitwise OR of current key modifiers
`unicode` : string
Unicode character represented by keypress, or the empty string
if translation is not possible.
'''
_fields_ = [('scancode', c_ubyte),
('sym', c_int),
('mod', c_int),
('_unicode', c_ushort)]
def __getattr__(self, name):
if name == 'unicode':
return unichr(self._unicode)
raise AttributeError
SDL_EnableUNICODE = function('SDL_EnableUNICODE',
'''Enable or disable Unicode translation of keyboard input.
This translation has some overhead, so translation defaults off.
:Parameters:
`enable` : int
* if 1, translation is enabled
* if 0, translation is disabled.
* if -1, the translation is not changed.
:rtype: int
:return: the previous state of keyboard translation
''',
args=['enable'],
arg_types=[c_int],
return_type=c_int)
SDL_EnableKeyRepeat = function('SDL_EnableKeyRepeat',
'''Enable keyboard repeat.
Keyboard repeat defaults to off.
:Parameters:
`delay` : int
the initial delay in milliseconds between the time when a key is
pressed, and keyboard repeat begins. If 0, keyboard repeat is
disabled.
`interval` : int
the time in milliseconds between keyboard repeat events.
:rtype: int
:return: undocumented (FIXME)
''',
args=['delay', 'interval'],
arg_types=[c_int, c_int],
return_type=c_int)
_SDL_GetKeyRepeat = private_function('SDL_GetKeyRepeat',
arg_types=[POINTER(c_int), POINTER(c_int)],
return_type=None,
since=(1,2,10))
def SDL_GetKeyRepeat():
'''Get the keyboard repeat parameters.
:see: `SDL_EnableKeyRepeat`
:rtype: (int, int)
:return: tuple (delay, interval), as defined in `SDL_EnableKeyRepeat`
:since: 1.2.10
'''
delay, interval = c_int(), c_int()
_SDL_GetKeyRepeat(byref(delay), byref(interval))
return delay.value, interval.value
_SDL_GetKeyState = private_function('SDL_GetKeyState',
arg_types=[POINTER(c_int)],
return_type=POINTER(c_ubyte))
def SDL_GetKeyState():
'''Get a snapshot of the current state of the keyboard.
Example::
keystate = SDL_GetKeyState()
if keystate[SDLK_RETURN]:
print '<RETURN> is pressed'
:rtype: list
:return: a list of integers indexed by the SDLK_* symbols
'''
numkeys = c_int()
keystate = _SDL_GetKeyState(byref(numkeys))
keystate_ar = cast(keystate, POINTER(c_ubyte * numkeys.value)).contents
return list(keystate_ar)
SDL_GetModState = function('SDL_GetModState',
'''Get the current key modifier state.
:rtype: int
''',
args=[],
arg_types=[],
return_type=c_int)
SDL_SetModState = function('SDL_SetModState',
'''Set the current key modifier state.
This does not change the keyboard state, only the key modifier flags.
:Parameters:
- `modstate`: int
''',
args=['modstate'],
arg_types=[c_int],
return_type=None)
_SDL_GetKeyName = private_function('SDL_GetKeyName',
arg_types=[c_int],
return_type=c_char_p)
def SDL_GetKeyName(key):
'''Get the name of an SDL virtual keysym.
:Parameters:
- `key`: int
:rtype: string
'''
return _SDL_GetKeyName(key)

File diff suppressed because it is too large Load diff

View file

@ -1,199 +0,0 @@
#!/usr/bin/env python
'''Mouse event handling.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .array import SDL_array, to_ctypes
from .dll import function, private_function
from .video import SDL_Rect
from .constants import SDL_BUTTON_LEFT, SDL_BUTTON_MIDDLE, SDL_BUTTON_RIGHT
class SDL_Cursor(Structure):
'''Cursor structure.
:Ivariables:
`area` : `SDL_Rect`
Area of the mouse cursor
`hot_x` : int
X coordinate of the tip of the cursor
`hot_y` : int
Y coordinate of the tip of the cursor
'''
_fields_ = [('area', SDL_Rect),
('hot_x', c_short),
('hot_y', c_short),
('_data', POINTER(c_ubyte)),
('_mask', POINTER(c_ubyte)),
('save', POINTER(c_ubyte) * 2),
('wm_cursor', c_void_p)]
def __getattr__(self, name):
w, h = self.area.w, self.area.h
if name == 'data':
return SDL_array(self._data, w * h / 8, c_ubyte)
elif name == 'mask':
return SDL_array(self._mask, w * h / 8, c_ubyte)
raise AttributeError(name)
_SDL_GetMouseState = private_function('SDL_GetMouseState',
arg_types=[POINTER(c_int), POINTER(c_int)],
return_type=c_ubyte)
def SDL_GetMouseState():
'''Retrieve the current state of the mouse.
Example::
state, x, y = SDL_GetMouseState()
if state & SDL_BUTTON_LMASK:
print 'Left button pressed.'
:rtype: (int, int, int)
:return: (state, x, y), where
* state is a button bitmask, which can be tested using `SDL_BUTTON`
* x and y are the current mouse cursor position.
'''
x, y = c_int(), c_int()
state = _SDL_GetMouseState(byref(x), byref(y))
return state, x.value, y.value
_SDL_GetRelativeMouseState = \
private_function('SDL_GetRelativeMouseState',
arg_types=[POINTER(c_int), POINTER(c_int)],
return_type=c_ubyte)
def SDL_GetRelativeMouseState():
'''Retrieve the current state of the mouse.
:rtype: (int, int, int)
:return: (state, dx, dy),
where state is a button bitmask, which can be tested using
`SDL_BUTTON`; dx and dy are the mouse deltas since the last call to
`SDL_GetRelativeMouseState`
'''
dx, dy = c_int(), c_int()
state = _SDL_GetRelativeMouseState(byref(dx), byref(dy))
return state, dx.value, dy.value
SDL_WarpMouse = function('SDL_WarpMouse',
'''Set the position of the mouse cursor.
Generates a mouse motion event.
:Parameters:
- `x`: int
- `y`: int
''',
args=['x', 'y'],
arg_types=[c_ushort, c_ushort],
return_type=None)
_SDL_CreateCursor = private_function('SDL_CreateCursor',
arg_types=[POINTER(c_ubyte), POINTER(c_ubyte), c_int, c_int, c_int, c_int],
return_type=POINTER(SDL_Cursor),
dereference_return=True,
require_return=True)
def SDL_CreateCursor(data, mask, w, h, hot_x, hot_y):
'''Create a cursor using the specified data and mask.
The cursor width must be a multiple of 8 bits. Mask and cursor
data may be given as either SDL_array byte buffers or as a sequence
of bytes; in either case the data is in MSB order.
The cursor is created in black and white according to the following:
==== ==== =========================================
data mask resulting pixel on screen
==== ==== =========================================
0 1 White
1 1 Black
0 0 Transparent
1 0 Inverted color if possible, black if not.
==== ==== =========================================
Cursors created with this function must be freed with `SDL_FreeCursor`.
:Parameters:
- `data`: `SDL_array`
- `mask`: `SDL_array`
- `w`: int
- `h`: int
- `hot_x`: int
- `hot_y`: int
:rtype: `SDL_Cursor`
'''
dataref, data = to_ctypes(data, len(data), c_ubyte)
maskref, mask = to_ctypes(mask, len(mask), c_ubyte)
return _SDL_CreateCursor(data, mask, w, h, hot_x, hot_y)
SDL_SetCursor = function('SDL_SetCursor',
'''Set the currently active cursor to the specified one.
If the cursor is currently visible, the change will be immediately
represented on the display.
:Parameters:
- `cursor`: `SDL_Cursor`
''',
args=['cursor'],
arg_types=[POINTER(SDL_Cursor)],
return_type=None)
SDL_GetCursor = function('SDL_GetCursor',
'''Return the currently active cursor.
:rtype: `SDL_Cursor`
''',
args=[],
arg_types=[],
return_type=POINTER(SDL_Cursor),
dereference_return=True)
SDL_FreeCursor = function('SDL_FreeCursor',
'''Deallocate a cursor created with `SDL_CreateCursor`
:Parameters:
- `cursor`: `SDL_Cursor`
''',
args=['cursor'],
arg_types=[POINTER(SDL_Cursor)],
return_type=None)
SDL_ShowCursor = function('SDL_ShowCursor',
'''Toggle whether or not the curosr is shown on the screen.
The cursor starts off displayed, but can be turned off.
:Parameters:
`toggle` : int
if 1, shows the cursor; if 0, hides the cursor, if -1, returns
the current state of the cursor.
:rtype: int
:return: 1 if the cursor was being displayed before the call, otherwise
0.
''',
args=['toggle'],
arg_types=[c_int],
return_type=c_int)
def SDL_BUTTON(X):
'''Used to create a mask for a mouse button.
'''
return 1 << (X-1)
SDL_BUTTON_LMASK = SDL_BUTTON(SDL_BUTTON_LEFT)
SDL_BUTTON_MMASK = SDL_BUTTON(SDL_BUTTON_MIDDLE)
SDL_BUTTON_RMASK = SDL_BUTTON(SDL_BUTTON_RIGHT)

View file

@ -1,30 +0,0 @@
#!/usr/bin/env python
'''Quit event handling.
An `SDL_QUITEVENT` is generated when the user tries to close the application
window. If it is ignored or filtered out, the window will remain open.
If it is not ignored or filtered, it is queued normally and the window
is allowed to close. When the window is closed, screen updates will
complete, but have no effect.
`SDL_Init` installs signal handlers for SIGINT (keyboard interrupt)
and SIGTERM (system termination request), if handlers do not already
exist, that generate `SDL_QUITEVENT` events as well. There is no way
to determine the cause of an `SDL_QUITEVENT`, but setting a signal
handler in your application will override the default generation of
quit events for that signal.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from .events import SDL_PumpEvents, SDL_HaveEvents, SDL_QUITMASK
def SDL_QuitRequested():
'''Return True if there is a quit event in the event queue.
:rtype: bool
'''
SDL_PumpEvents()
return SDL_HaveEvents(SDL_QUITMASK)

View file

@ -1,193 +0,0 @@
#!/usr/bin/env python
'''General interface for SDL to read and write data sources.
For files, use `SDL_RWFromFile`. Other Python file-type objects can be
used with `SDL_RWFromObject`. If another library provides a constant void
pointer to a contiguous region of memory, `SDL_RWFromMem` and
`SDL_RWFromConstMem` can be used.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .dll import function
from .constants import RW_SEEK_CUR
_rwops_p = POINTER('SDL_RWops')
_seek_fn = CFUNCTYPE(c_int, _rwops_p, c_int, c_int)
_read_fn = CFUNCTYPE(c_int, _rwops_p, c_void_p, c_int, c_int)
_write_fn = CFUNCTYPE(c_int, _rwops_p, c_void_p, c_int, c_int)
_close_fn = CFUNCTYPE(c_int, _rwops_p)
class _hidden_mem_t(Structure):
_fields_ = [('base', c_void_p),
('here', c_void_p),
('stop', c_void_p)]
class SDL_RWops(Structure):
'''Read/write operations structure.
:Ivariables:
`seek` : function
seek(context: `SDL_RWops`, offset: int, whence: int) -> int
`read` : function
read(context: `SDL_RWops`, ptr: c_void_p, size: int, maxnum: int)
-> int
`write` : function
write(context: `SDL_RWops`, ptr: c_void_p, size: int, num: int) ->
int
`close` : function
close(context: `SDL_RWops`) -> int
`type` : int
Undocumented
'''
_fields_ = [('seek', _seek_fn),
('read', _read_fn),
('write', _write_fn),
('close', _close_fn),
('type', c_uint),
('_hidden_mem', _hidden_mem_t)]
SetPointerType(_rwops_p, SDL_RWops)
SDL_RWFromFile = function('SDL_RWFromFile',
'''Create an SDL_RWops structure from a file on disk.
:Parameters:
`file` : string
Filename
`mode` : string
Mode to open the file with; as with the built-in function ``open``.
:rtype: `SDL_RWops`
''',
args=['file', 'mode'],
arg_types=[c_char_p, c_char_p],
return_type=POINTER(SDL_RWops),
dereference_return=True,
require_return=True)
SDL_RWFromMem = function('SDL_RWFromMem',
'''Create an SDL_RWops structure from a contiguous region of memory.
:Parameters:
- `mem`: ``c_void_p``
- `size`: int
:rtype: `SDL_RWops`
''',
args=['mem', 'size'],
arg_types=[c_void_p, c_int],
return_type=POINTER(SDL_RWops),
dereference_return=True,
require_return=True)
SDL_RWFromConstMem = function('SDL_RWFromConstMem',
'''Create an SDL_RWops structure from a contiguous region of memory.
:Parameters:
- `mem`: ``c_void_p``
- `size`: int
:rtype: `SDL_RWops`
:since: 1.2.7
''',
args=['mem', 'size'],
arg_types=[c_void_p, c_int],
return_type=POINTER(SDL_RWops),
dereference_return=True,
require_return=True,
since=(1,2,7))
""" These functions shouldn't be useful to Pythoners.
SDL_AllocRW = function('SDL_AllocRW',
'''Allocate a blank SDL_Rwops structure.
:rtype: `SDL_RWops`
'''
args=[],
arg_types=[],
return_type=POINTER(SDL_RWops),
dereference_return=True,
require_return=True)
SDL_FreeRW = function('SDL_FreeRW',
'''Free a SDL_RWops structure.
:param area: `SDL_RWops`
'''
args=['area'],
arg_types=[POINTER(SDL_RWops)],
return_type=None)
"""
# XXX Tested read from open() only so far
def SDL_RWFromObject(obj):
'''Construct an SDL_RWops structure from a Python file-like object.
The object must support the following methods in the same fashion as
the builtin file object:
- ``read(len) -> data``
- ``write(data)``
- ``seek(offset, whence)``
- ``close()``
:Parameters:
- `obj`: Python file-like object to wrap
:rtype: `SDL_RWops`
'''
ctx = SDL_RWops()
def _seek(context, offset, whence):
obj.seek(offset, whence)
return obj.tell()
ctx.seek = _seek_fn(_seek)
def _read(context, ptr, size, maximum):
try:
r = obj.read(maximum * size)
memmove(ptr, r, len(r))
return len(r) / size
except:
return -1
ctx.read = _read_fn(_read)
def _write(context, ptr, size, num):
try:
obj.write(string_at(ptr, size*num))
return num
except:
return -1
ctx.write = _write_fn(_write)
def _close(context):
obj.close()
ctx.close = _close_fn(_close)
return ctx
"""
# XXX Usefulness of the following using raw pointers?
def SDL_RWseek(ctx, offset, whence):
return ctx.seek(ctx, offset, whence)
def SDL_RWtell(ctx):
return ctx.seek(ctx, 0, RW_SEEK_CUR)
def SDL_RWread(ctx, ptr, size, n):
return ctx.read(ctx, ptr, size, n)
def SDL_RWwrite(ctx, ptr, size, n):
return ctx.write(ctx, ptr, size, n)
def SDL_RWclose(ctx):
return ctx.close(ctx)
"""
# XXX not implemented: SDL_Read{BL}E* and SDL_Write{BL}E*

View file

@ -1,577 +0,0 @@
#!/usr/bin/env python
'''An abstract sound format decoding API.
The latest version of SDL_sound can be found at: http://icculus.org/SDL_sound/
The basic gist of SDL_sound is that you use an SDL_RWops to get sound data
into this library, and SDL_sound will take that data, in one of several
popular formats, and decode it into raw waveform data in the format of
your choice. This gives you a nice abstraction for getting sound into your
game or application; just feed it to SDL_sound, and it will handle
decoding and converting, so you can just pass it to your SDL audio
callback (or whatever). Since it gets data from an SDL_RWops, you can get
the initial sound data from any number of sources: file, memory buffer,
network connection, etc.
As the name implies, this library depends on SDL: Simple Directmedia Layer,
which is a powerful, free, and cross-platform multimedia library. It can
be found at http://www.libsdl.org/
Support is in place or planned for the following sound formats:
- .WAV (Microsoft WAVfile RIFF data, internal.)
- .VOC (Creative Labs' Voice format, internal.)
- .MP3 (MPEG-1 Layer 3 support, via the SMPEG and mpglib libraries.)
- .MID (MIDI music converted to Waveform data, internal.)
- .MOD (MOD files, via MikMod and ModPlug.)
- .OGG (Ogg files, via Ogg Vorbis libraries.)
- .SPX (Speex files, via libspeex.)
- .SHN (Shorten files, internal.)
- .RAW (Raw sound data in any format, internal.)
- .AU (Sun's Audio format, internal.)
- .AIFF (Audio Interchange format, internal.)
- .FLAC (Lossless audio compression, via libFLAC.)
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .array import SDL_array, to_ctypes
from .dll import SDL_DLL, _version_parts
from .rwops import SDL_RWops
_dll = SDL_DLL('SDL_sound', None)
class Sound_Version(Structure):
'''Version structure.
:Ivariables:
`major` : int
Major version number
`minor` : int
Minor version number
`patch` : int
Patch revision number
'''
_fields_ = [('major', c_int),
('minor', c_int),
('patch', c_int)]
def __repr__(self):
return '%d.%d.%d' % (self.major, self.minor, self.patch)
_Sound_GetLinkedVersion = _dll.private_function('Sound_GetLinkedVersion',
arg_types=[POINTER(Sound_Version)],
return_type=None)
def Sound_GetLinkedVersion():
'''Get the version of the dynamically linked SDL_sound library
:rtype: `Sound_Version`
'''
version = Sound_Version()
_Sound_GetLinkedVersion(byref(version))
return version
# Fill in non-standard linked version now, so "since" declarations can work
_dll._version = _version_parts(Sound_GetLinkedVersion())
class Sound_AudioInfo(Structure):
'''Information about an existing sample's format.
:Ivariables:
`format` : int
Equivalent to `SDL_AudioSpec.format`
`channels` : int
Number of sound channels. 1 == mono, 2 == stereo.
`rate` : int
Sample rate, in samples per second.
:see: `Sound_SampleNew`
:see: `Sound_SampleNewFromFile`
'''
_fields_ = [('format', c_ushort),
('channels', c_ubyte),
('rate', c_uint)]
class Sound_DecoderInfo(Structure):
'''Information about a sound decoder.
Each decoder sets up one of these structures, which can be retrieved
via the `Sound_AvailableDecoders` function. Fields in this
structure are read-only.
:Ivariables:
`extensions` : list of str
List of file extensions
`description` : str
Human-readable description of the decoder
`author` : str
Author and email address
`url` : str
URL specific to this decoder
'''
_fields_ = [('_extensions', POINTER(c_char_p)),
('description', c_char_p),
('author', c_char_p),
('url', c_char_p)]
def __getattr__(self, name):
if name == 'extensions':
extensions = []
ext_p = self._extensions
i = 0
while ext_p[i]:
extensions.append(ext_p[i])
i += 1
return extensions
raise AttributeError(name)
class Sound_Sample(Structure):
'''Represents sound data in the process of being decoded.
The `Sound_Sample` structure is the heart of SDL_sound. This holds
information about a source of sound data as it is beind decoded. All
fields in this structure are read-only.
:Ivariables:
`decoder` : `Sound_DecoderInfo`
Decoder used for this sample
`desired` : `Sound_AudioInfo`
Desired audio format for conversion
`actual` : `Sound_AudioInfo`
Actual audio format of the sample
`buffer` : `SDL_array`
Buffer of decoded data, as bytes
`buffer_size` : int
Current size of the buffer, in bytes
`flags` : int
Bitwise combination of SOUND_SAMPLEFLAG_CANSEEK,
SOUND_SAMPLEFLAG_EOF, SOUND_SAMPLEFLAG_ERROR,
SOUND_SAMPLEFLAG_EGAIN
'''
_fields_ = [('opaque', c_void_p),
('_decoder', POINTER(Sound_DecoderInfo)),
('desired', Sound_AudioInfo),
('actual', Sound_AudioInfo),
('_buffer', POINTER(c_ubyte)),
('buffer_size', c_uint),
('flags', c_int)]
def __getattr__(self, name):
if name == 'decoder':
return self._decoder.contents
elif name == 'buffer':
return SDL_array(self._buffer, self.buffer_size, c_ubyte)
raise AttributeError(name)
Sound_Init = _dll.function('Sound_Init',
'''Initialize SDL_sound.
This must be called before any other SDL_sound function (except perhaps
`Sound_GetLinkedVersion`). You should call `SDL_Init` before calling
this. `Sound_Init` will attempt to call ``SDL_Init(SDL_INIT_AUDIO)``,
just in case. This is a safe behaviour, but it may not configure SDL
to your liking by itself.
''',
args=[],
arg_types=[],
return_type=c_int,
error_return=0)
Sound_Quit = _dll.function('Sound_Quit',
'''Shutdown SDL_sound.
This closes any SDL_RWops that were being used as sound sources, and
frees any resources in use by SDL_sound.
All Sound_Sample structures existing will become invalid.
Once successfully deinitialized, `Sound_Init` can be called again to
restart the subsystem. All default API states are restored at this
point.
You should call this before `SDL_Quit`. This will not call `SDL_Quit`
for you.
''',
args=[],
arg_types=[],
return_type=c_int,
error_return=0)
_Sound_AvailableDecoders = _dll.private_function('Sound_AvailableDecoders',
arg_types=[],
return_type=POINTER(POINTER(Sound_DecoderInfo)))
def Sound_AvailableDecoders():
'''Get a list of sound formats supported by this version of SDL_sound.
This is for informational purposes only. Note that the extension listed
is merely convention: if we list "MP3", you can open an MPEG-1 Layer 3
audio file with an extension of "XYZ", if you like. The file extensions
are informational, and only required as a hint to choosing the correct
decoder, since the sound data may not be coming from a file at all,
thanks to the abstraction that an SDL_RWops provides.
:rtype: list of `Sound_DecoderInfo`
'''
decoders = []
decoder_p = _Sound_AvailableDecoders()
i = 0
while decoder_p[i]:
decoders.append(decoder_p[i].contents)
i += 1
return decoders
Sound_GetError = _dll.function('Sound_GetError',
'''Get the last SDL_sound error message.
This will be None if there's been no error since the last call to this
function. Each thread has a unique error state associated with it, but
each time a new error message is set, it will overwrite the previous
one associated with that thread. It is safe to call this function at
any time, even before `Sound_Init`.
:rtype: str
''',
args=[],
arg_types=[],
return_type=c_char_p)
Sound_ClearError = _dll.function('Sound_ClearError',
'''Clear the current error message.
The next call to `Sound_GetError` after `Sound_ClearError` will return
None.
''',
args=[],
arg_types=[],
return_type=None)
Sound_NewSample = _dll.function('Sound_NewSample',
'''Start decoding a new sound sample.
The data is read via an SDL_RWops structure, so it may be coming from
memory, disk, network stream, etc. The `ext` parameter is merely a hint
to determining the correct decoder; if you specify, for example, "mp3"
for an extension, and one of the decoders lists that as a handled
extension, then that decoder is given first shot at trying to claim the
data for decoding. If none of the extensions match (or the extension is
None), then every decoder examines the data to determine if it can
handle it, until one accepts it. In such a case your SDL_RWops will
need to be capable of rewinding to the start of the stream.
If no decoders can handle the data, an exception is raised.
Optionally, a desired audio format can be specified. If the incoming data
is in a different format, SDL_sound will convert it to the desired format
on the fly. Note that this can be an expensive operation, so it may be
wise to convert data before you need to play it back, if possible, or
make sure your data is initially in the format that you need it in.
If you don't want to convert the data, you can specify None for a desired
format. The incoming format of the data, preconversion, can be found
in the `Sound_Sample` structure.
Note that the raw sound data "decoder" needs you to specify both the
extension "RAW" and a "desired" format, or it will refuse to handle
the data. This is to prevent it from catching all formats unsupported
by the other decoders.
Finally, specify an initial buffer size; this is the number of bytes that
will be allocated to store each read from the sound buffer. The more you
can safely allocate, the more decoding can be done in one block, but the
more resources you have to use up, and the longer each decoding call will
take. Note that different data formats require more or less space to
store. This buffer can be resized via `Sound_SetBufferSize`.
The buffer size specified must be a multiple of the size of a single
sample point. So, if you want 16-bit, stereo samples, then your sample
point size is (2 channels 16 bits), or 32 bits per sample, which is four
bytes. In such a case, you could specify 128 or 132 bytes for a buffer,
but not 129, 130, or 131 (although in reality, you'll want to specify a
MUCH larger buffer).
When you are done with this `Sound_Sample` instance, you can dispose of
it via `Sound_FreeSample`.
You do not have to keep a reference to `rw` around. If this function
suceeds, it stores `rw` internally (and disposes of it during the call
to `Sound_FreeSample`). If this function fails, it will dispose of the
SDL_RWops for you.
:Parameters:
`rw` : `SDL_RWops`
SDL_RWops with sound data
`ext` : str
File extension normally associated with a data format. Can
usually be None.
`desired` : `Sound_AudioInfo`
Format to convert sound data into. Can usually be None if you
don't need conversion.
`bufferSize` : int
Size, in bytes, to allocate for the decoding buffer
:rtype: `Sound_Sample`
''',
args=['rw', 'ext', 'desired', 'bufferSize'],
arg_types=[POINTER(SDL_RWops), c_char_p,
POINTER(Sound_AudioInfo), c_uint],
return_type=POINTER(Sound_Sample),
dereference_return=True,
require_return=True)
_Sound_NewSampleFromMem = _dll.private_function('Sound_NewSampleFromMem',
arg_types=[POINTER(c_ubyte), c_uint, c_char_p,
POINTER(Sound_AudioInfo), c_uint],
return_type=POINTER(Sound_Sample),
dereference_return=True,
require_return=True,
since=(9,9,9)) # Appears in header only
def Sound_NewSampleFromMem(data, ext, desired, bufferSize):
'''Start decoding a new sound sample from a buffer.
This is identical to `Sound_NewSample`, but it creates an `SDL_RWops`
for you from the buffer.
:Parameters:
`data` : `SDL_array` or sequence
Buffer holding encoded byte sound data
`ext` : str
File extension normally associated with a data format. Can
usually be None.
`desired` : `Sound_AudioInfo`
Format to convert sound data into. Can usually be None if you
don't need conversion.
`bufferSize` : int
Size, in bytes, to allocate for the decoding buffer
:rtype: `Sound_Sample`
:since: Not yet released in SDL_sound
'''
ref, data = to_ctypes(data, len(data), c_ubyte)
return _Sound_NewSampleFromMem(data, len(data), ext, desired, bufferSize)
Sound_NewSampleFromFile = _dll.function('Sound_NewSampleFromFile',
'''Start decoding a new sound sample from a file on disk.
This is identical to `Sound_NewSample`, but it creates an `SDL_RWops
for you from the file located at `filename`.
''',
args=['filename', 'desired', 'bufferSize'],
arg_types=[c_char_p, POINTER(Sound_AudioInfo), c_uint],
return_type=POINTER(Sound_Sample),
dereference_return=True,
require_return=True)
Sound_FreeSample = _dll.function('Sound_FreeSample',
'''Dispose of a `Sound_Sample`.
This will also close/dispose of the `SDL_RWops` that was used at
creation time. The `Sound_Sample` structure is invalid after this
call.
:Parameters:
`sample` : `Sound_Sample`
The sound sample to delete.
''',
args=['sample'],
arg_types=[POINTER(Sound_Sample)],
return_type=None)
Sound_GetDuration = _dll.function('Sound_GetDuration',
'''Retrieve the total play time of a sample, in milliseconds.
Report total time length of sample, in milliseconds. This is a fast
call. Duration is calculated during `Sound_NewSample`, so this is just
an accessor into otherwise opaque data.
Note that not all formats can determine a total time, some can't
be exact without fully decoding the data, and thus will estimate the
duration. Many decoders will require the ability to seek in the data
stream to calculate this, so even if we can tell you how long an .ogg
file will be, the same data set may fail if it's, say, streamed over an
HTTP connection.
:Parameters:
`sample` : `Sound_Sample`
Sample from which to retrieve duration information.
:rtype: int
:return: Sample length in milliseconds, or -1 if duration can't be
determined.
:since: Not yet released in SDL_sound
''',
args=['sample'],
arg_types=[POINTER(Sound_Sample)],
return_type=c_int,
since=(9,9,9))
Sound_SetBufferSize = _dll.function('Sound_SetBufferSize',
'''Change the current buffer size for a sample.
If the buffer size could be changed, then the ``sample.buffer`` and
``sample.buffer_size`` fields will reflect that. If they could not be
changed, then your original sample state is preserved. If the buffer is
shrinking, the data at the end of buffer is truncated. If the buffer is
growing, the contents of the new space at the end is undefined until you
decode more into it or initialize it yourself.
The buffer size specified must be a multiple of the size of a single
sample point. So, if you want 16-bit, stereo samples, then your sample
point size is (2 channels 16 bits), or 32 bits per sample, which is four
bytes. In such a case, you could specify 128 or 132 bytes for a buffer,
but not 129, 130, or 131 (although in reality, you'll want to specify a
MUCH larger buffer).
:Parameters:
`sample` : `Sound_Sample`
Sample to modify
`new_size` : int
The desired size, in bytes of the new buffer
''',
args=['sample', 'new_size'],
arg_types=[POINTER(Sound_Sample), c_uint],
return_type=c_int,
error_return=0)
Sound_Decode = _dll.function('Sound_Decode',
'''Decode more of the sound data in a `Sound_Sample`.
It will decode at most sample->buffer_size bytes into ``sample.buffer``
in the desired format, and return the number of decoded bytes.
If ``sample.buffer_size`` bytes could not be decoded, then refer to
``sample.flags`` to determine if this was an end-of-stream or error
condition.
:Parameters:
`sample` : `Sound_Sample`
Do more decoding to this sample
:rtype: int
:return: number of bytes decoded into ``sample.buffer``
''',
args=['sample'],
arg_types=[POINTER(Sound_Sample)],
return_type=c_uint)
Sound_DecodeAll = _dll.function('Sound_DecodeAll',
'''Decode the remainder of the sound data in a `Sound_Sample`.
This will dynamically allocate memory for the entire remaining sample.
``sample.buffer_size`` and ``sample.buffer`` will be updated to reflect
the new buffer. Refer to ``sample.flags`` to determine if the
decoding finished due to an End-of-stream or error condition.
Be aware that sound data can take a large amount of memory, and that
this function may block for quite awhile while processing. Also note
that a streaming source (for example, from a SDL_RWops that is getting
fed from an Internet radio feed that doesn't end) may fill all available
memory before giving up...be sure to use this on finite sound sources
only.
When decoding the sample in its entirety, the work is done one buffer
at a time. That is, sound is decoded in ``sample.buffer_size`` blocks, and
appended to a continually-growing buffer until the decoding completes.
That means that this function will need enough RAM to hold
approximately ``sample.buffer_size`` bytes plus the complete decoded
sample at most. The larger your buffer size, the less overhead this
function needs, but beware the possibility of paging to disk. Best to
make this user-configurable if the sample isn't specific and small.
:Parameters:
`sample` : `Sound_Sample`
Do all decoding for this sample.
:rtype: int
:return: number of bytes decoded into ``sample.buffer``
''',
args=['sample'],
arg_types=[POINTER(Sound_Sample)],
return_type=c_uint)
Sound_Rewind = _dll.function('Sound_Rewind',
'''Rewind a sample to the start.
Restart a sample at the start of its waveform data, as if newly
created with `Sound_NewSample`. If successful, the next call to
`Sound_Decode` will give audio data from the earliest point in the
stream.
Beware that this function will fail if the SDL_RWops that feeds the
decoder can not be rewound via it's seek method, but this can
theoretically be avoided by wrapping it in some sort of buffering
SDL_RWops.
This function will raise an exception if the RWops is not seekable, or
SDL_sound is not initialized.
If this function fails, the state of the sample is undefined, but it
is still safe to call `Sound_FreeSample` to dispose of it.
:Parameters:
`sample` : `Sound_Sample`
The sample to rewind
''',
args=['sample'],
arg_types=[POINTER(Sound_Sample)],
return_type=c_int,
error_return=0)
Sound_Seek = _dll.function('Sound_Seek',
'''Seek to a different point in a sample.
Reposition a sample's stream. If successful, the next call to
`Sound_Decode` or `Sound_DecodeAll` will give audio data from the
offset you specified.
The offset is specified in milliseconds from the start of the
sample.
Beware that this function can fail for several reasons. If the
SDL_RWops that feeds the decoder can not seek, this call will almost
certainly fail, but this can theoretically be avoided by wrapping it
in some sort of buffering SDL_RWops. Some decoders can never seek,
others can only seek with certain files. The decoders will set a flag
in the sample at creation time to help you determine this.
You should check ``sample.flags & SOUND_SAMPLEFLAG_CANSEEK``
before attempting. `Sound_Seek` reports failure immediately if this
flag isn't set. This function can still fail for other reasons if the
flag is set.
This function can be emulated in the application with `Sound_Rewind`
and predecoding a specific amount of the sample, but this can be
extremely inefficient. `Sound_Seek()` accelerates the seek on a
with decoder-specific code.
If this function fails, the sample should continue to function as if
this call was never made. If there was an unrecoverable error,
``sample.flags & SOUND_SAMPLEFLAG_ERROR`` will be set, which your
regular decoding loop can pick up.
On success, ERROR, EOF, and EAGAIN are cleared from sample->flags.
:Parameters:
`sample` : `Sound_Sample`
The sample to seek
`ms` : int
The new position, in milliseconds, from the start of sample
''',
args=['sample', 'ms'],
arg_types=[POINTER(Sound_Sample), c_uint],
return_type=c_int,
error_return=0)

View file

@ -1,161 +0,0 @@
#!/usr/bin/env python
'''Time management routines.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .dll import function, private_function
from .error import SDL_Exception, SDL_GetError
SDL_GetTicks = function('SDL_GetTicks',
'''Get the number of milliseconds since the SDL library initialization.
Note that this value wraps if the program runs for more than ~49 days.
:rtype: int
''',
args=[],
arg_types=[],
return_type=c_uint)
SDL_Delay = function('SDL_Delay',
'''Wait a specified number of milliseconds before returning.
:Parameters:
`ms` : int
delay in milliseconds
''',
args=['ms'],
arg_types=[c_uint],
return_type=None)
_SDL_TimerCallback = CFUNCTYPE(c_int, c_uint)
_SDL_SetTimer = private_function('SDL_SetTimer',
arg_types=[c_uint, _SDL_TimerCallback],
return_type=c_int)
_timercallback_ref = None # Keep global to avoid possible GC
def SDL_SetTimer(interval, callback):
'''Set a callback to run after the specified number of milliseconds has
elapsed.
The callback function is passed the current timer interval
and returns the next timer interval. If the returned value is the
same as the one passed in, the periodic alarm continues, otherwise a
new alarm is scheduled. If the callback returns 0, the periodic alarm
is cancelled.
To cancel a currently running timer, call ``SDL_SetTimer(0, None)``.
The timer callback function may run in a different thread than your
main code, and so shouldn't call any functions from within itself.
The maximum resolution of this timer is 10 ms, which means that if
you request a 16 ms timer, your callback will run approximately 20 ms
later on an unloaded system. If you wanted to set a flag signaling
a frame update at 30 frames per second (every 33 ms), you might set a
timer for 30 ms::
SDL_SetTimer((33/10)*10, flag_update)
If you use this function, you need to pass `SDL_INIT_TIMER` to
`SDL_Init`.
Under UNIX, you should not use raise or use SIGALRM and this function
in the same program, as it is implemented using ``setitimer``. You
also should not use this function in multi-threaded applications as
signals to multi-threaded apps have undefined behavior in some
implementations.
:Parameters:
`interval` : int
Interval before callback, in milliseconds.
`callback` : function
Callback function should accept one argument, the number of
milliseconds elapsed, and return the next timer interval,
in milliseconds.
'''
# Note SDL_SetTimer actually returns 1 on success, not 0 as documented
# in SDL_timer.h.
global _timercallback_ref
if callback:
_timercallback_ref = _SDL_TimerCallback(callback)
else:
_timercallback_ref = _SDL_TimerCallback()
# XXX if this fails the global ref is incorrect and old one will
# possibly be collected early.
if _SDL_SetTimer(interval, _timercallback_ref) == -1:
raise SDL_Exception(SDL_GetError())
# For the new timer functions, the void *param passed to the callback
# is ignored; using an local function instead. The SDL_TimerID type
# is not defined, we use c_void_p instead.
_SDL_NewTimerCallback = CFUNCTYPE(c_uint, c_int, c_void_p)
_SDL_AddTimer = private_function('SDL_AddTimer',
arg_types=[c_uint, _SDL_NewTimerCallback, c_void_p],
return_type=c_void_p)
_timer_refs = {} # Keep global to manage GC
def SDL_AddTimer(interval, callback, param):
'''Add a new timer to the pool of timers already running.
:Parameters:
`interval` : int
The interval before calling the callback, in milliseconds.
`callback` : function
The callback function. It is passed the current timer
interval, in millseconds, and returns the next timer interval,
in milliseconds. If the returned value is the same as the one
passed in, the periodic alarm continues, otherwise a new alarm
is scheduled. If the callback returns 0, the periodic alarm is
cancelled. An example callback function is::
def timer_callback(interval, param):
print 'timer called after %d ms.' % interval
return 1000 # call again in 1 second
`param` : any
A value passed to the callback function.
:rtype: int
:return: the timer ID
'''
def _callback(interval, _ignored_param):
return callback(interval, param)
func = _SDL_NewTimerCallback(_callback)
result = _SDL_AddTimer(interval, func, None)
if not result:
raise SDL_Exception(SDL_GetError())
_timer_refs[result] = func
return result
_SDL_RemoveTimer = private_function('SDL_RemoveTimer',
args=['t'],
arg_types=[c_void_p],
return_type=c_int,
error_return=0)
def SDL_RemoveTimer(t):
'''Remove one of the multiple timers knowing its ID.
:Parameters:
`t` : int
The timer ID, as returned by `SDL_AddTimer`.
'''
global _timer_refs
_SDL_RemoveTimer(t)
del _timer_refs[t]

View file

@ -1,481 +0,0 @@
#!/usr/bin/env python
'''A companion module to SDL for working with TrueType fonts.
This library is a wrapper around FreeType_ 2.0.
.. _FreeType: http://www.freetype.org
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .dll import SDL_DLL
from .rwops import SDL_RWops
from .version import SDL_version
from .video import SDL_Color, SDL_Surface
_dll = SDL_DLL('SDL_ttf', 'TTF_Linked_Version')
TTF_Linked_Version = _dll.function('TTF_Linked_Version',
'''Get the version of the dynamically linked SDL_ttf library.
:rtype: `SDL_version`
''',
args=[],
arg_types=[],
return_type=POINTER(SDL_version),
dereference_return=True,
require_return=True)
# Opaque type pointer
_TTF_Font = c_void_p
TTF_Init = _dll.function('TTF_Init',
'''Initialize the TTF engine
''',
args=[],
arg_types=[],
return_type=c_int,
error_return=-1)
TTF_OpenFont = _dll.function('TTF_OpenFont',
'''Open a font file and create a font of the specified point size.
:Parameters:
`file` : string
Filename of a Truetype font file to open.
`ptsize` : int
Size of the font face, in points. Type is rendered at 64 DPI.
:rtype: ``TTF_Font``
''',
args=['file', 'ptsize'],
arg_types=[c_char_p, c_int],
return_type=_TTF_Font,
require_return=True)
TTF_OpenFontIndex = _dll.function('TTF_OpenFontIndex',
'''Open a font collection file and create a font of the specified point
size.
:Parameters:
`file` : string
Filename of a Truetype font file to open.
`ptsize` : int
Size of the font face, in points. Type is rendered at 64 DPI.
`index` : int
Zero-based index of the desired font within the file.
:rtype: ``TTF_Font``
''',
args=['file', 'ptsize', 'index'],
arg_types=[c_char_p, c_int, c_int],
return_type=_TTF_Font,
require_return=True)
TTF_OpenFontRW = _dll.function('TTF_OpenFontRW',
'''Create a font of the specified point size from a RWops object.
You can create an SDL_RWops object from any Python file-like object
with `SDL_RWFromObject`.
:Parameters:
`src` : `SDL_RWops`
Readable RWops object.
`freesrc` : int
If non-zero, the source will be closed when the face is closed.
`ptsize` : int
Size of the font face, in points. Type is rendered at 64 DPI.
:rtype: ``TTF_Font``
''',
args=['src', 'freesrc', 'ptsize'],
arg_types=[POINTER(SDL_RWops), c_int, c_int],
return_type=_TTF_Font,
require_return=True)
TTF_OpenFontIndexRW = _dll.function('TTF_OpenFontIndexRW',
'''Create a font of the specified point size from a RWops object.
:Parameters:
`src` : `SDL_RWops`
Readable RWops object.
`freesrc` : int
If non-zero, the source will be closed when the face is closed.
`ptsize` : int
Size of the font face, in points. Type is rendered at 64 DPI.
`index` : int
Zero-based index of the desired font within the file.
:rtype: ``TTF_Font``
''',
args=['src', 'freesrc', 'ptsize', 'index'],
arg_types=[POINTER(SDL_RWops), c_int, c_int, c_int],
return_type=_TTF_Font,
require_return=True)
TTF_GetFontStyle = _dll.function('TTF_GetFontStyle',
'''Get the modified font style.
Note that the modified style has nothing to do with the underlying
style properties of the font, and merely reflects what has been
set in `TTF_SetFontStyle`.
:Parameters:
- `font`: ``TTF_Font``
:rtype: int
:return: A bitwise combination of ``TTF_STYLE_BOLD``, ``TTF_STYLE_ITALIC``
and ``TTF_STYLE_UNDERLINE``.
''',
args=['font'],
arg_types=[_TTF_Font],
return_type=c_int)
TTF_SetFontStyle = _dll.function('TTF_SetFontStyle',
'''Set the modified font style.
This font style is implemented by modifying the font glyphs, and doesn't
reflect any inherent properties of the TrueType font file.
:Parameters:
`font` : ``TTF_Font``
Font object to modify.
`style` : int
Bitwise combination of any of ``TTF_STYLE_BOLD``,
``TTF_STYLE_ITALIC`` and ``TTF_STYLE_UNDERLINE``.
''',
args=['font', 'style'],
arg_types=[_TTF_Font, c_int],
return_type=None)
TTF_FontHeight = _dll.function('TTF_FontHeight',
'''Get the total height of the font, in pixels.
:Parameters:
- `font`: ``TTF_Font``
:rtype: int
''',
args=['font'],
arg_types=[_TTF_Font],
return_type=c_int)
TTF_FontAscent = _dll.function('TTF_FontAscent',
'''Get the ascent of the font, in pixels.
This is the offset from the baseline to the top of the font.
:Parameters:
- `font`: ``TTF_Font``
:rtype: int
''',
args=['font'],
arg_types=[_TTF_Font],
return_type=c_int)
TTF_FontDescent = _dll.function('TTF_FontDescent',
'''Get the descent of the font, in pixels.
This is the offset from the baseline to the lowest point of the font,
and is usually negative.
:Parameters:
- `font`: ``TTF_Font``
:rtype: int
''',
args=['font'],
arg_types=[_TTF_Font],
return_type=c_int)
TTF_FontLineSkip = _dll.function('TTF_FontLineSkip',
'''Get the recommended spacing between lines of text, in pixels.
:Parameters:
- `font`: ``TTF_Font``
:rtype: int
''',
args=['font'],
arg_types=[_TTF_Font],
return_type=c_int)
TTF_FontFaces = _dll.function('TTF_FontFaces',
'''Get the number of fonts in the font collection file.
:Parameters:
- `font`: ``TTF_Font``
:rtype: int
''',
args=['font'],
arg_types=[_TTF_Font],
return_type=c_long)
TTF_FontFaceIsFixedWidth = _dll.function('TTF_FontFaceIsFixedWidth',
'''Determine if a font is monospaced or not.
:Parameters:
- `font`: ``TTF_Font``
:rtype: int
:return: non-zero if monospaced, otherwise zero.
''',
args=['font'],
arg_types=[_TTF_Font],
return_type=c_int)
TTF_FontFaceFamilyName = _dll.function('TTF_FontFaceFamilyName',
'''Get the family name of the font.
For example, "Times New Roman".
:Parameters:
- `font`: ``TTF_Font``
:rtype: string
''',
args=['font'],
arg_types=[_TTF_Font],
return_type=c_char_p)
TTF_FontFaceStyleName = _dll.function('TTF_FontFaceStyleName',
'''Get the style name of the font.
For example, "Regular", "Bold", "Italic", etc.
:Parameters:
- `font`: ``TTF_Font``
:rtype: string
''',
args=['font'],
arg_types=[_TTF_Font],
return_type=c_char_p)
_TTF_GlyphMetrics = _dll.private_function('TTF_GlyphMetrics',
arg_types=[_TTF_Font, c_ushort, POINTER(c_int), POINTER(c_int),
POINTER(c_int), POINTER(c_int), POINTER(c_int)],
return_type=int,
error_return=-1)
def TTF_GlyphMetrics(font, ch):
'''Get the metrics of a glyph.
The character `ch` is used to look up the glyph metrics
for the given font. The metrics returned are:
minx, maxx, miny, maxy
Bounding box for the glyph.
advance
Horizontal advance for the glyph.
All metrics are returned in pixels.
:Parameters:
`font` : ``TTF_Font``
Font object to inspect.
`ch` : string of length 1
Character to look up
:rtype: (int, int, int, int, int)
:return: (minx, maxx, miny, maxy, advance)
'''
minx, maxx, miny, maxy, advance = \
c_int(), c_int(), c_int(), c_int(), c_int()
_TTF_GlyphMetrics(font, ord(ch), byref(minx), byref(maxx), byref(miny),
byref(maxy), byref(advance))
return minx.value, maxx.value, miny.value, maxy.value, advance.value
_TTF_SizeUTF8 = _dll.private_function('TTF_SizeUTF8',
arg_types=[_TTF_Font, c_char_p, POINTER(c_int), POINTER(c_int)],
return_type=c_int,
error_return=-1)
def TTF_SizeText(font, text):
'''Get the dimensions of a rendered string of text, in pixels.
:Parameters:
- `font`: ``TTF_Font``
- `text`: string
:rtype: (int, int)
:return: (width, height)
'''
w, h = c_int(), c_int()
_TTF_SizeUTF8(font, text.encode('utf8'), byref(w), byref(h))
return w.value, h.value
_TTF_RenderUTF8_Solid = _dll.private_function('TTF_RenderUTF8_Solid',
arg_types=[_TTF_Font, c_char_p, SDL_Color],
return_type=POINTER(SDL_Surface),
require_return=True,
dereference_return=True)
def TTF_RenderText_Solid(font, text, fg):
'''Create an 8-bit palettized surface and render the given text at
the fast quality with the given font and color.
The palette has 0 as the colorkey, giving it a transparent background,
with 1 as the text color.
:Parameters:
- `font`: ``TTF_Font``
- `text`: string
- `fg`: `SDL_Color`
:rtype: `SDL_Surface`
'''
return _TTF_RenderUTF8_Solid(font, text.encode('utf8'), fg)
_TTF_RenderGlyph_Solid = _dll.private_function('TTF_RenderGlyph_Solid',
arg_types=[_TTF_Font, c_ushort, SDL_Color],
return_type=POINTER(SDL_Surface),
require_return=True,
dereference_return=True)
def TTF_RenderGlyph_Solid(font, ch, fg):
'''Create an 8-bit palettized surface and render the given character at
the fast quality with the given font and color.
The palette has 0 as the colorkey, giving it a transparent background,
with 1 as the text color.
The glyph is rendered without any padding or centering in the X direction,
and aligned normally in the Y direction.
:Parameters:
- `font`: ``TTF_Font``
- `ch`: string of length 1
- `fg`: `SDL_Color`
:rtype: `SDL_Surface`
'''
return _TTF_RenderGlyph_Solid(font, ord(text), fg)
_TTF_RenderUTF8_Shaded = _dll.private_function('TTF_RenderUTF8_Shaded',
arg_types=[_TTF_Font, c_char_p, SDL_Color, SDL_Color],
return_type=POINTER(SDL_Surface),
require_return=True,
dereference_return=True)
def TTF_RenderText_Shaded(font, text, fg, bg):
'''Create an 8-bit palettized surface and render the given text at
high quality with the given font and colors.
The 0 pixel is background, while other pixels have varying degrees of
the foreground color.
:Parameters:
- `font`: ``TTF_Font``
- `text`: string
- `fg`: `SDL_Color`
- `bg`: `SDL_Color`
:rtype: `SDL_Surface`
'''
return _TTF_RenderUTF8_Shaded(font, text.encode('utf8'), fg, bg)
_TTF_RenderGlyph_Shaded = _dll.private_function('TTF_RenderGlyph_Shaded',
arg_types=[_TTF_Font, c_ushort, SDL_Color, SDL_Color],
return_type=POINTER(SDL_Surface),
require_return=True,
dereference_return=True)
def TTF_RenderGlyph_Shaded(font, ch, fg, bg):
'''Create an 8-bit palettized surface and render the given character at
high quality with the given font and color.
The 0 pixel is background, while other pixels have varying degrees of
the foreground color.
The glyph is rendered without any padding or centering in the X direction,
and aligned normally in the Y direction.
:Parameters:
- `font`: ``TTF_Font``
- `ch`: string of length 1
- `fg`: `SDL_Color`
- `bg`: `SDL_Color`
:rtype: `SDL_Surface`
'''
return _TTF_RenderGlyph_Shaded(font, ord(ch), fg, bg)
_TTF_RenderUTF8_Blended = _dll.private_function('TTF_RenderUTF8_Blended',
arg_types=[_TTF_Font, c_char_p, SDL_Color],
return_type=POINTER(SDL_Surface),
require_return=True,
dereference_return=True)
def TTF_RenderText_Blended(font, text, fg):
'''Create a 32-bit ARGB surface and render the given text at
high quality, using alpha blending to dither the font with the
given color.
:Parameters:
- `font`: ``TTF_Font``
- `text`: string
- `fg`: `SDL_Color`
:rtype: `SDL_Surface`
'''
return _TTF_RenderUTF8_Blended(font, text.encode('utf8'), fg)
_TTF_RenderGlyph_Blended = _dll.private_function('TTF_RenderGlyph_Blended',
arg_types=[_TTF_Font, c_ushort, SDL_Color],
return_type=POINTER(SDL_Surface),
require_return=True,
dereference_return=True)
def TTF_RenderGlyph_Blended(font, ch, fg):
'''Create a 32-bit ARGB surface and render the given character at
high quality, using alpha blending to dither the font with the
given color.
The glyph is rendered without any padding or centering in the X direction,
and aligned normally in the Y direction.
:Parameters:
- `font`: ``TTF_Font``
- `ch`: string of length 1
- `fg`: `SDL_Color`
:rtype: `SDL_Surface`
'''
return _TTF_RenderGlyph_Blended(font, ord(text), fg)
TTF_CloseFont = _dll.function('TTF_CloseFont',
'''Close an opened font file.
:Parameters:
- `font`: ``TTF_Font``
''',
args=['font'],
arg_types=[_TTF_Font],
return_type=None)
TTF_Quit = _dll.function('TTF_Quit',
'''De-initialize the TTF engine.
''',
args=[],
arg_types=[],
return_type=None)
TTF_WasInit = _dll.function('TTF_WasInit',
'''Check if the TTF engine is initialized.
:rtype: int
:return: non-zero if initialized, otherwise zero.
''',
args=[],
arg_types=[],
return_type=c_int)

View file

@ -1,86 +0,0 @@
#!/usr/bin/env python
'''Functions related to the SDL shared library version.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from .dll import function
class SDL_version(Structure):
'''Version structure.
:Ivariables:
`major` : int
Major version number
`minor` : int
Minor version number
`patch` : int
Patch revision number
'''
_fields_ = [('major', c_ubyte),
('minor', c_ubyte),
('patch', c_ubyte)]
def __repr__(self):
return '%d.%d.%d' % \
(self.major, self.minor, self.patch)
def is_since(self, required):
if hasattr(required, 'major'):
return self.major >= required.major and \
self.minor >= required.minor and \
self.patch >= required.patch
else:
return self.major >= required[0] and \
self.minor >= required[1] and \
self.patch >= required[2]
def SDL_VERSIONNUM(major, minor, patch):
'''Turn the version numbers into a numeric value.
For example::
>>> SDL_VERSIONNUM(1, 2, 3)
1203
:Parameters:
- `major`: int
- `minor`: int
- `patch`: int
:rtype: int
'''
return x * 1000 + y * 100 + z
SDL_Linked_Version = function('SDL_Linked_Version',
'''Get the version of the dynamically linked SDL library.
:rtype: `SDL_version`
''',
args=[],
arg_types=[],
return_type=POINTER(SDL_version),
dereference_return=True,
require_return=True)
def SDL_VERSION_ATLEAST(major, minor, patch):
'''Determine if the SDL library is at least the given version.
:Parameters:
- `major`: int
- `minor`: int
- `patch`: int
:rtype: bool
'''
v = SDL_Linked_Version()
return SDL_VERSIONNUM(v.major, v.minor, v.patch) >= \
SDL_VERSIONNUM(major, minor, patch)
# SDL_VERSION and SDL_COMPILEDVERSION not implemented as there is no
# sensible mapping to compiled version numbers.

File diff suppressed because it is too large Load diff

View file

@ -28,7 +28,6 @@ from m64py.frontend.log import log
from m64py.utils import version_split
from m64py.opts import VERBOSE
from m64py.archive import ROM_TYPE
from m64py.platform import LDD_CMD
from m64py.core.vidext import vidext
def debug_callback(context, level, message):
@ -77,7 +76,6 @@ class Core:
self.core_path = ""
self.core_name = "Mupen64Plus Core"
self.core_version = "Unknown"
self.core_sdl2 = False
def get_handle(self):
"""Retrieves core library handle."""
@ -133,14 +131,6 @@ class Core:
self.core_name = plugin_name
self.core_version = plugin_version
if LDD_CMD:
proc = subprocess.Popen(
LDD_CMD % self.core_path, shell=True,
preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL))
proc.communicate()
if proc.returncode == 0:
self.core_sdl2 = True
log.info("attached to library '%s' version %s" %
(self.core_name, version_split(self.core_version)))
if plugin_cap & M64CAPS_DYNAREC:

View file

@ -26,30 +26,20 @@ except ImportError:
glimport = False
from m64py.core.defs import *
from m64py.opts import SDL2
from m64py.frontend.log import log
if SDL2:
from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO
from m64py.SDL2 import SDL_GetNumDisplayModes, SDL_DisplayMode, SDL_GetDisplayMode
else:
from m64py.SDL import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO
from m64py.SDL import SDL_ListModes, SDL_FULLSCREEN, SDL_HWSURFACE
from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO
from m64py.SDL2 import SDL_GetNumDisplayModes, SDL_DisplayMode, SDL_GetDisplayMode
try:
if not SDL_WasInit(SDL_INIT_VIDEO):
SDL_InitSubSystem(SDL_INIT_VIDEO)
MODES = []
if SDL2:
display = SDL_DisplayMode()
for mode in range(SDL_GetNumDisplayModes(0)):
ret = SDL_GetDisplayMode(0, mode, ctypes.byref(display))
if (display.w, display.h) not in MODES:
MODES.append((display.w, display.h))
else:
for mode in SDL_ListModes(None, SDL_FULLSCREEN|SDL_HWSURFACE):
if (mode.w, mode.h) not in MODES:
MODES.append((mode.w, mode.h))
display = SDL_DisplayMode()
for mode in range(SDL_GetNumDisplayModes(0)):
ret = SDL_GetDisplayMode(0, mode, ctypes.byref(display))
if (display.w, display.h) not in MODES:
MODES.append((display.w, display.h))
if SDL_WasInit(SDL_INIT_VIDEO):
SDL_QuitSubSystem(SDL_INIT_VIDEO)
except Exception as err:

View file

@ -18,8 +18,7 @@ from PyQt5.QtCore import Qt, pyqtSignal, QMargins
from PyQt5.QtOpenGL import QGLWidget
from m64py.core.defs import *
from m64py.opts import SDL2
from m64py.frontend.keymap import QT2SDL, QT2SDL2
from m64py.frontend.keymap import QT2SDL2
class GLWidget(QGLWidget):
@ -62,10 +61,7 @@ class GLWidget(QGLWidget):
self.worker.save_snapshot()
else:
try:
if SDL2 or self.worker.core.core_sdl2:
sdl_key = QT2SDL2[key]
else:
sdl_key = QT2SDL[key]
sdl_key = QT2SDL2[key]
self.worker.send_sdl_keydown(sdl_key)
except KeyError:
pass
@ -74,10 +70,7 @@ class GLWidget(QGLWidget):
if self.worker.state == M64EMU_RUNNING:
key = event.key()
try:
if SDL2 or self.worker.core.core_sdl2:
sdl_key = QT2SDL2[key]
else:
sdl_key = QT2SDL[key]
sdl_key = QT2SDL2[key]
self.worker.send_sdl_keyup(sdl_key)
except KeyError:
pass

View file

@ -19,18 +19,15 @@ import re
from PyQt5.QtWidgets import QDialog
from PyQt5.QtGui import QKeySequence
from m64py.opts import SDL2
from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO
from m64py.SDL2.keyboard import SDL_GetScancodeFromName
from m64py.core.defs import *
from m64py.utils import format_tooltip
from m64py.frontend.joystick import Joystick
from m64py.frontend.keymap import QT2SDL, SCANCODE2KEYCODE, KEYCODE2SCANCODE
from m64py.frontend.keymap import SCANCODE2KEYCODE, KEYCODE2SCANCODE
from m64py.ui.input_ui import Ui_InputDialog
if SDL2:
from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO
else:
from m64py.SDL import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO
KEY_RE = re.compile("([a-z]+)\((.*)\)")
AXIS_RE = re.compile("([a-z]+)\((.*?),(.*?)\)")
@ -414,34 +411,24 @@ class Input(QDialog, Ui_InputDialog):
return [0, 0]
def get_sdl_key(self, text):
if SDL2 or self.parent.worker.core.core_sdl2:
from m64py.SDL2.keyboard import SDL_GetScancodeFromName
if "Shift" in text or "Ctrl" in text or "Alt" in text:
text = "Left %s" % text
text = text.encode()
return SCANCODE2KEYCODE[SDL_GetScancodeFromName(text)]
else:
try:
key = QKeySequence(text)[0]
return QT2SDL[key]
except KeyError:
return None
if "Shift" in text or "Ctrl" in text or "Alt" in text:
text = "Left %s" % text
text = text.encode()
return SCANCODE2KEYCODE[SDL_GetScancodeFromName(text)]
def get_key_name(self, sdl_key):
if not sdl_key:
return self.tr("Select...")
if SDL2 or self.parent.worker.core.core_sdl2:
from m64py.SDL2.keyboard import SDL_GetScancodeName
try:
text = SDL_GetScancodeName(KEYCODE2SCANCODE[int(sdl_key)])
except Exception:
return self.tr("Select...")
else:
from m64py.SDL.keyboard import SDL_GetKeyName
text = SDL_GetKeyName(int(sdl_key)).title()
try:
text = SDL_GetScancodeName(KEYCODE2SCANCODE[int(sdl_key)])
except Exception:
return self.tr("Select...")
text = text.decode()
if not text:
return self.tr("Select...")
if "Shift" in text or "Ctrl" in text or "Alt" in text:
text = text.replace("Left ", "")
return text.title()

View file

@ -19,22 +19,15 @@
from PyQt5.QtCore import QObject, pyqtSignal, QTime, QTimer
from m64py.opts import SDL2
from m64py.frontend.log import log
import ctypes
if SDL2:
from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_INIT_JOYSTICK
from m64py.SDL2 import SDL_JoystickOpen, SDL_JoystickClose, SDL_NumJoysticks, SDL_JoystickNameForIndex
from m64py.SDL2 import SDL_JoystickNumAxes, SDL_JoystickNumButtons, SDL_JoystickNumHats, SDL_JoystickNumBalls
from m64py.SDL2 import SDL_JoystickGetAxis, SDL_JoystickGetButton, SDL_JoystickGetHat, SDL_JoystickUpdate, SDL_JoystickInstanceID
from m64py.SDL2 import SDL_Event, SDL_PollEvent
from m64py.SDL2 import SDL_JOYAXISMOTION, SDL_JOYHATMOTION, SDL_JOYBALLMOTION, SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP
else:
from m64py.SDL import SDL_WasInit, SDL_InitSubSystem, SDL_INIT_JOYSTICK
from m64py.SDL import SDL_JoystickOpen, SDL_JoystickClose, SDL_NumJoysticks, SDL_JoystickName
from m64py.SDL import SDL_JoystickNumAxes, SDL_JoystickNumButtons, SDL_JoystickNumHats, SDL_JoystickNumBalls
from m64py.SDL import SDL_JoystickGetAxis, SDL_JoystickGetButton, SDL_JoystickGetHat, SDL_JoystickUpdate
from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_INIT_JOYSTICK
from m64py.SDL2 import SDL_JoystickOpen, SDL_JoystickClose, SDL_NumJoysticks, SDL_JoystickNameForIndex
from m64py.SDL2 import SDL_JoystickNumAxes, SDL_JoystickNumButtons, SDL_JoystickNumHats, SDL_JoystickNumBalls
from m64py.SDL2 import SDL_JoystickGetAxis, SDL_JoystickGetButton, SDL_JoystickGetHat, SDL_JoystickUpdate, SDL_JoystickInstanceID
from m64py.SDL2 import SDL_Event, SDL_PollEvent
from m64py.SDL2 import SDL_JOYAXISMOTION, SDL_JOYHATMOTION, SDL_JOYBALLMOTION, SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP
JOYSTICK_DEADZONE = 0
JOYSTICK_SENSITIVITY = 0
@ -80,23 +73,16 @@ class Joystick(QObject):
if not SDL_WasInit(SDL_INIT_JOYSTICK):
if SDL_InitSubSystem(SDL_INIT_JOYSTICK) == 0:
for i in range(SDL_NumJoysticks()):
if SDL2:
self.joystick_names.append(SDL_JoystickNameForIndex(i))
else:
self.joystick_names.append(SDL_JoystickName(i))
self.joystick_names.append(SDL_JoystickNameForIndex(i))
if SDL2:
self.joystick_timer.timeout.connect(self.process_events_sdl2)
else:
self.joystick_timer.timeout.connect(self.process_events)
self.joystick_timer.timeout.connect(self.process_events)
else:
log.info("couldn't initialize SDL joystick support")
def clear_events(self):
if SDL2:
event = SDL_Event()
while SDL_PollEvent(ctypes.byref(event)) != 0:
pass
event = SDL_Event()
while SDL_PollEvent(ctypes.byref(event)) != 0:
pass
def open(self, stick=0):
if self.joystick:
@ -145,61 +131,6 @@ class Joystick(QObject):
if not self.joystick:
return
SDL_JoystickUpdate()
for i in range(self.num_axes):
moved = SDL_JoystickGetAxis(self.joystick, i)
if abs(moved) >= self.deadzones[i]:
if moved != self.axes[i]:
delta_moved = abs(self.axes[i] - moved)
if delta_moved >= self.sensitivities[i]:
self.axis_value_changed.emit(i, moved)
self.axes[i] = moved
self.axis_repeat_timers[i].restart()
elif self.auto_repeat and moved != 0:
if self.axis_repeat_timers[i].elapsed() >= self.auto_repeat_delay:
self.axis_value_changed.emit(i, moved)
self.axes[i] = moved
else:
self.axis_repeat_timers[i].restart()
else:
self.axis_value_changed.emit(i, 0)
for i in range(self.num_buttons):
changed = SDL_JoystickGetButton(self.joystick, i)
if changed != self.buttons[i]:
self.button_value_changed.emit(i, changed)
self.buttons[i] = changed
self.button_repeat_timers[i].restart()
elif self.auto_repeat and changed != 0:
if self.button_repeat_timers[i].elapsed() >= self.auto_repeat_delay:
self.button_value_changed.emit(i, changed)
self.buttons[i] = changed
else:
self.button_repeat_timers[i].restart()
for i in range(self.num_hats):
changed = SDL_JoystickGetHat(self.joystick, i)
if changed != self.hats[i]:
self.hat_value_changed.emit(i, changed)
self.hats[i] = changed
self.hat_repeat_timers[i].restart()
elif self.auto_repeat and changed != 0:
if self.hat_repeat_timers[i].elapsed() >= self.auto_repeat_delay:
self.hat_value_changed.emit(i, changed)
self.hats[i] = changed
else:
self.hat_repeat_timers[i].restart()
for i in range(self.num_trackballs):
dx, dy = self.joystick.get_ball(i)
if dx != 0 or dy != 0:
self.trackball_value_changed.emit(i, dx, dy)
def process_events_sdl2(self):
if not self.joystick:
return
stickid = SDL_JoystickInstanceID(self.joystick)
event = SDL_Event()
while SDL_PollEvent(ctypes.byref(event)) != 0:

View file

@ -21,8 +21,6 @@ from m64py.core.defs import FRONTEND_VERSION
usage = 'usage: %prog <romfile>'
parser = OptionParser(usage=usage, version="M64Py Version %s" % FRONTEND_VERSION)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="show verbose output")
parser.add_option("--sdl2", action="store_true", dest="sdl2", help="use libSDL2 library", default=False)
opts, args = parser.parse_args()
SDL2 = opts.sdl2
VERBOSE = opts.verbose

View file

@ -18,7 +18,6 @@ import os
import sys
if sys.platform.startswith("linux"):
LDD_CMD = "ldd %s | grep -q SDL2"
DLL_EXT = ".so"
DLL_FILTER = ".so.2"
DEFAULT_DYNLIB = "libmupen64plus.so.2"
@ -33,7 +32,6 @@ if sys.platform.startswith("linux"):
"."
]
elif sys.platform.startswith("openbsd"):
LDD_CMD = "ldd %s | grep -q SDL2"
DLL_EXT = ".so"
DLL_FILTER = ""
DEFAULT_DYNLIB = "libmupen64plus.so"
@ -42,7 +40,6 @@ elif sys.platform.startswith("openbsd"):
"."
]
elif sys.platform == "darwin":
LDD_CMD = "otool -L %s | grep -q SDL2"
DLL_EXT = ".dylib"
DLL_FILTER = ".dylib"
DEFAULT_DYNLIB = "libmupen64plus.dylib"
@ -52,7 +49,6 @@ elif sys.platform == "darwin":
"."
]
elif sys.platform == "win32":
LDD_CMD = ""
DLL_EXT = ".dll"
DLL_FILTER = ".dll"
DEFAULT_DYNLIB = "mupen64plus.dll"

View file

@ -17,8 +17,9 @@
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import Qt
from m64py.opts import SDL2
from m64py.frontend.keymap import QT2SDL, QT2SDL2
from m64py.SDL2.keyboard import SDL_GetScancodeName
from m64py.frontend.keymap import QT2SDL2
SDL_HAT_UP = 0x01
SDL_HAT_RIGHT = 0x02
@ -65,12 +66,7 @@ class InputButton(QPushButton):
text = self.tr("Select...")
self.setCheckable(False)
else:
if SDL2 or self.input.parent.worker.core.core_sdl2:
from m64py.SDL2.keyboard import SDL_GetScancodeName
text = SDL_GetScancodeName(QT2SDL2[key])
else:
from m64py.SDL.keyboard import SDL_GetKeyName
text = SDL_GetKeyName(QT2SDL[key]).title()
text = SDL_GetScancodeName(QT2SDL2[key])
text = text.decode()
text = text.replace("Left ", "")