code
stringlengths
1
1.72M
language
stringclasses
1 value
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' # TODO Tiger and later: need to set kWindowApplicationScaledAttribute for DPI # independence? from ctypes import * import math from sys import byteorder from pyglet.font import base import pyglet.image from pyglet.libs.darwin import * from pyglet.libs.darwin import _oscheck class FixedPoint(Structure): _fields_ = [ ('x', Fixed), ('y', Fixed) ] class ATSTrapezoid(Structure): _fields_ = [ ('upperLeft', FixedPoint), ('upperRight', FixedPoint), ('lowerRight', FixedPoint), ('lowerLeft', FixedPoint) ] # TODO: most of the ATS and CG here not used any more. CGGlyph = c_ushort ATSUFontID = c_uint32 RGBColor = c_short * 3 ATSURGBAlphaColor = c_float * 4 kCGImageAlphaNone = 0 kCGImageAlphaPremultipliedLast = 1 kCGTextFill = 0 kATSUInvalidFontErr = -8796 kATSFontContextUnspecified = 0 kATSFontContextGlobal = 1 kATSFontContextLocal = 2 kATSFontFilterSelectorUnspecified = 0 kATSFontFilterSelectorGeneration = 3 kATSFontFilterSelectorFontFamily = 7 kATSFontFilterSelectorFontFamilyApplierFunction = 8 kATSFontFilterSelectorFontApplierFunction = 9 kATSOptionFlagsDoNotNotify = 0x00000001 << 8 kATSOptionFlagsIterationScopeMask = 0x00000007 << 12 kATSOptionFlagsDefaultScope = 0x00000000 << 12 kATSOptionFlagsUnRestrictedScope = 0x00000001 << 12 kATSOptionFlagsRestrictedScope = 0x00000002 << 12 kATSOptionFlagsProcessSubdirectories = 0x00000001 << 6 kATSUFromTextBeginning = c_ulong(0xFFFFFFFF) kATSUToTextEnd = c_ulong(0xFFFFFFFF) kATSULineAscentTag = 8 kATSULineDescentTag = 9 ATSUTextMeasurement = Fixed kATSUQDBoldfaceTag = 256 kATSUQDItalicTag = 257 kATSUFontTag = 261 kATSUSizeTag = 262 kATSUCGContextTag = 32767 kATSUColorTag = 263 kATSURGBAlphaColorTag = 288 kATSULineWidthTag = 1 kFontFullName = 4 kFontNoPlatformCode = c_ulong(-1) kFontNoScriptCode = c_ulong(-1) kFontNoLanguageCode = c_ulong(-1) kATSUseDeviceOrigins = 1 kATSFontFormatUnspecified = 0 kATSFontContextLocal = 2 carbon.CGColorSpaceCreateWithName.restype = c_void_p carbon.CGBitmapContextCreate.restype = POINTER(c_void_p) UniCharArrayOffset = c_uint32 UniCharCount = c_uint32 kATSULayoutOperationJustification = 1 kATSULayoutOperationPostLayoutAdjustment = 0x20 kATSULayoutOperationCallbackStatusHandled = 0 kATSULayoutOperationCallbackStatusContinue = c_long(1) kATSULayoutOperationOverrideTag = 15 kATSUDirectDataAdvanceDeltaFixedArray = 0 kATSUDirectDataDeviceDeltaSInt16Array = 2 kATSUDirectDataLayoutRecordATSLayoutRecordVersion1 = 100 ATSUDirectLayoutOperationOverrideUPP = CFUNCTYPE(c_int, c_int, c_void_p, c_uint32, c_void_p, POINTER(c_int)) class ATSULayoutOperationOverrideSpecifier(Structure): _fields_ = [ ('operationSelector', c_uint32), ('overrideUPP', ATSUDirectLayoutOperationOverrideUPP) ] class ATSLayoutRecord(Structure): _pack_ = 2 _fields_ = [ ('glyphID', c_uint16), ('flags', c_uint32), ('originalOffset', c_uint32), ('realPos', Fixed), ] def fixed(value): return c_int32(carbon.Long2Fix(c_long(int(value)))) carbon.Fix2X.restype = c_double def fix2float(value): return carbon.Fix2X(value) def create_atsu_style(attributes): # attributes is a dict of ATSUAttributeTag => ctypes value tags, values = zip(*attributes.items()) tags = (c_int * len(tags))(*tags) sizes = (c_uint * len(values))(*[sizeof(v) for v in values]) values = (c_void_p * len(values))(*[cast(pointer(v), c_void_p) \ for v in values]) style = c_void_p() carbon.ATSUCreateStyle(byref(style)) carbon.ATSUSetAttributes(style, len(tags), tags, sizes, values) return style def set_layout_attributes(layout, attributes): if attributes: # attributes is a dict of ATSUAttributeTag => ctypes value tags, values = zip(*attributes.items()) tags = (c_int * len(tags))(*tags) sizes = (c_uint * len(values))(*[sizeof(v) for v in values]) values = (c_void_p * len(values))(*[cast(pointer(v), c_void_p) \ for v in values]) r = carbon.ATSUSetLayoutControls(layout, len(tags), tags, sizes, values) _oscheck(r) def str_ucs2(text): if byteorder == 'big': text = text.encode('utf_16_be') else: text = text.encode('utf_16_le') # explicit endian avoids BOM return create_string_buffer(text + '\0') class CarbonGlyphRenderer(base.GlyphRenderer): _bitmap = None _bitmap_context = None _bitmap_rect = None _glyph_advance = 0 # set through callback def __init__(self, font): super(CarbonGlyphRenderer, self).__init__(font) self._create_bitmap_context(256, 256) self.font = font def __del__(self): try: if self._bitmap_context: carbon.CGContextRelease(self._bitmap_context) except: pass def _layout_callback(self, operation, line, ref, extra, callback_status): if not line: return 0 records = c_void_p() n_records = c_uint() r = carbon.ATSUDirectGetLayoutDataArrayPtrFromLineRef(line, kATSUDirectDataLayoutRecordATSLayoutRecordVersion1, 0, byref(records), byref(n_records)) _oscheck(r) records = cast(records, POINTER(ATSLayoutRecord * n_records.value)).contents self._glyph_advance = fix2float(records[-1].realPos) callback_status.contents = kATSULayoutOperationCallbackStatusContinue return 0 def render(self, text): # Convert text to UCS2 text_len = len(text) text_ucs2 = str_ucs2(text) # Create layout override handler to extract device advance value. override_spec = ATSULayoutOperationOverrideSpecifier() override_spec.operationSelector = \ kATSULayoutOperationPostLayoutAdjustment override_spec.overrideUPP = \ ATSUDirectLayoutOperationOverrideUPP(self._layout_callback) # Create ATSU text layout for this text and font layout = c_void_p() carbon.ATSUCreateTextLayout(byref(layout)) set_layout_attributes(layout, { kATSUCGContextTag: self._bitmap_context, kATSULayoutOperationOverrideTag: override_spec}) carbon.ATSUSetTextPointerLocation(layout, text_ucs2, kATSUFromTextBeginning, kATSUToTextEnd, text_len) carbon.ATSUSetRunStyle(layout, self.font.atsu_style, kATSUFromTextBeginning, kATSUToTextEnd) # Turning on transient font matching screws up font layout # predictability when strange fonts are installed # <ah> Don't believe this. Can't get foreign/special characters # without transient on. carbon.ATSUSetTransientFontMatching(layout, True) # Get bitmap dimensions required rect = Rect() carbon.ATSUMeasureTextImage(layout, kATSUFromTextBeginning, kATSUToTextEnd, 0, 0, byref(rect)) image_width = rect.right - rect.left + 2 image_height = rect.bottom - rect.top + 2 baseline = rect.bottom + 1 lsb = rect.left # Resize Quartz context if necessary if (image_width > self._bitmap_rect.size.width or image_height > self._bitmap_rect.size.height): self._create_bitmap_context( int(max(image_width, self._bitmap_rect.size.width)), int(max(image_height, self._bitmap_rect.size.height))) set_layout_attributes(layout, { kATSUCGContextTag: self._bitmap_context}) # Draw to the bitmap carbon.CGContextClearRect(self._bitmap_context, self._bitmap_rect) carbon.ATSUDrawText(layout, 0, kATSUToTextEnd, fixed(-lsb + 1), fixed(baseline)) advance = self._glyph_advance # Round advance to nearest int. It actually looks good with sub-pixel # advance as well -- Helvetica at 12pt is more tightly spaced, but # Times New Roman at 12pt is too light. With integer positioning # overall look seems darker and perhaps more uniform. It's also more # similar (programmatically) to Win32 and FreeType. Still, worth # messing around with (comment out next line) if you're interested. advance = int(round(advance)) # Fix advance for zero-width space if text == u'\u200b': advance = 0 # A negative pitch is required, but it is much faster to load the # glyph upside-down and flip the tex_coords. Note region used # to start at top of glyph image. pitch = int(4 * self._bitmap_rect.size.width) image = pyglet.image.ImageData(image_width, self._bitmap_rect.size.height, 'RGBA', self._bitmap, pitch) skip_rows = int(self._bitmap_rect.size.height - image_height) image = image.get_region(0, skip_rows, image.width, image_height) glyph = self.font.create_glyph(image) glyph.set_bearings(baseline, lsb - 1, int(advance)) t = list(glyph.tex_coords) glyph.tex_coords = t[9:12] + t[6:9] + t[3:6] + t[:3] return glyph def _create_bitmap_context(self, width, height): '''Create or recreate bitmap and Quartz context.''' if self._bitmap_context: carbon.CGContextRelease(self._bitmap_context) components = 4 pitch = width * components self._bitmap = (c_ubyte * (pitch * height))() color_space = carbon.CGColorSpaceCreateDeviceRGB() context = carbon.CGBitmapContextCreate(self._bitmap, width, height, 8, pitch, color_space, kCGImageAlphaPremultipliedLast) carbon.CGColorSpaceRelease(color_space) # Disable RGB decimated antialiasing, use standard # antialiasing which won't break alpha. carbon.CGContextSetShouldSmoothFonts(context, False) carbon.CGContextSetShouldAntialias(context, True) self._bitmap_context = context self._bitmap_rect = CGRect() self._bitmap_rect.origin.x = 0 self._bitmap_rect.origin.y = 0 self._bitmap_rect.size.width = width self._bitmap_rect.size.height = height class CarbonFont(base.Font): glyph_renderer_class = CarbonGlyphRenderer def __init__(self, name, size, bold=False, italic=False, dpi=None): super(CarbonFont, self).__init__() if not name: name = 'Helvetica' if dpi is None: dpi = 96 # pyglet 1.1; in pyglet 1.0 this was 72. # If application is not DPI-aware, DPI is fixed at 72. Scale # font size to emulate other DPI. This will need to be fixed if issue # #87 is implemented. size = size * dpi / 72. name = name.encode('ascii', 'ignore') font_id = ATSUFontID() carbon.ATSUFindFontFromName( name, len(name), kFontFullName, kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode, byref(font_id)) attributes = { kATSUSizeTag: fixed(size), kATSUFontTag: font_id, kATSURGBAlphaColorTag: ATSURGBAlphaColor(1, 1, 1, 1), kATSUQDBoldfaceTag: c_byte(bold), kATSUQDItalicTag: c_byte(italic) } self.atsu_style = create_atsu_style(attributes) self.calculate_metrics() @classmethod def have_font(cls, name): font_id = ATSUFontID() name = name.encode('ascii', 'ignore') r = carbon.ATSUFindFontFromName( name, len(name), kFontFullName, kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode, byref(font_id)) return r != kATSUInvalidFontErr def calculate_metrics(self): # It seems the only way to get the font's ascent and descent is to lay # out some glyphs and measure them. # fake ucs2 string text = '\0a' layout = c_void_p() carbon.ATSUCreateTextLayout(byref(layout)) carbon.ATSUSetTextPointerLocation(layout, text, kATSUFromTextBeginning, kATSUToTextEnd, 1) carbon.ATSUSetRunStyle(layout, self.atsu_style, kATSUFromTextBeginning, kATSUToTextEnd) # determine the metrics for this font only carbon.ATSUSetTransientFontMatching(layout, False) value = ATSUTextMeasurement() carbon.ATSUGetLineControl(layout, 0, kATSULineAscentTag, sizeof(value), byref(value), None) self.ascent = int(math.ceil(fix2float(value))) carbon.ATSUGetLineControl(layout, 0, kATSULineDescentTag, sizeof(value), byref(value), None) self.descent = -int(math.ceil(fix2float(value))) @classmethod def add_font_data(cls, data): container = c_void_p() r = carbon.ATSFontActivateFromMemory(data, len(data), kATSFontContextLocal, kATSFontFormatUnspecified, None, 0, byref(container)) _oscheck(r)
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Abstract classes used by pyglet.font implementations. These classes should not be constructed directly. Instead, use the functions in `pyglet.font` to obtain platform-specific instances. You can use these classes as a documented interface to the concrete classes. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unicodedata from pyglet.gl import * from pyglet import image _other_grapheme_extend = \ map(unichr, [0x09be, 0x09d7, 0x0be3, 0x0b57, 0x0bbe, 0x0bd7, 0x0cc2, 0x0cd5, 0x0cd6, 0x0d3e, 0x0d57, 0x0dcf, 0x0ddf, 0x200c, 0x200d, 0xff9e, 0xff9f]) # skip codepoints above U+10000 _logical_order_exception = \ map(unichr, range(0xe40, 0xe45) + range(0xec0, 0xec4)) _grapheme_extend = lambda c, cc: \ cc in ('Me', 'Mn') or c in _other_grapheme_extend _CR = u'\u000d' _LF = u'\u000a' _control = lambda c, cc: cc in ('ZI', 'Zp', 'Cc', 'Cf') and not \ c in map(unichr, [0x000d, 0x000a, 0x200c, 0x200d]) _extend = lambda c, cc: _grapheme_extend(c, cc) or \ c in map(unichr, [0xe30, 0xe32, 0xe33, 0xe45, 0xeb0, 0xeb2, 0xeb3]) _prepend = lambda c, cc: c in _logical_order_exception _spacing_mark = lambda c, cc: cc == 'Mc' and c not in _other_grapheme_extend def _grapheme_break(left, right): # GB1 if left is None: return True # GB2 not required, see end of get_grapheme_clusters # GB3 if left == _CR and right == _LF: return False left_cc = unicodedata.category(left) # GB4 if _control(left, left_cc): return True right_cc = unicodedata.category(right) # GB5 if _control(right, right_cc): return True # GB6, GB7, GB8 not implemented # GB9 if _extend(right, right_cc): return False # GB9a if _spacing_mark(right, right_cc): return False # GB9b if _prepend(left, left_cc): return False # GB10 return True def get_grapheme_clusters(text): '''Implements Table 2 of UAX #29: Grapheme Cluster Boundaries. Does not currently implement Hangul syllable rules. :Parameters: `text` : unicode String to cluster. :since: pyglet 1.1.2 :rtype: List of `unicode` :return: List of Unicode grapheme clusters ''' clusters = [] cluster = '' left = None for right in text: if cluster and _grapheme_break(left, right): clusters.append(cluster) cluster = '' elif cluster: # Add a zero-width space to keep len(clusters) == len(text) clusters.append(u'\u200b') cluster += right left = right # GB2 if cluster: clusters.append(cluster) return clusters class Glyph(image.TextureRegion): '''A single glyph located within a larger texture. Glyphs are drawn most efficiently using the higher level APIs, for example `GlyphString`. :Ivariables: `advance` : int The horizontal advance of this glyph, in pixels. `vertices` : (int, int, int, int) The vertices of this glyph, with (0,0) originating at the left-side bearing at the baseline. ''' advance = 0 vertices = (0, 0, 0, 0) def set_bearings(self, baseline, left_side_bearing, advance): '''Set metrics for this glyph. :Parameters: `baseline` : int Distance from the bottom of the glyph to its baseline; typically negative. `left_side_bearing` : int Distance to add to the left edge of the glyph. `advance` : int Distance to move the horizontal advance to the next glyph. ''' self.advance = advance self.vertices = ( left_side_bearing, -baseline, left_side_bearing + self.width, -baseline + self.height) def draw(self): '''Debug method. Use the higher level APIs for performance and kerning. ''' glBindTexture(GL_TEXTURE_2D, self.owner.id) glBegin(GL_QUADS) self.draw_quad_vertices() glEnd() def draw_quad_vertices(self): '''Debug method. Use the higher level APIs for performance and kerning. ''' glTexCoord3f(*self.tex_coords[:3]) glVertex2f(self.vertices[0], self.vertices[1]) glTexCoord3f(*self.tex_coords[3:6]) glVertex2f(self.vertices[2], self.vertices[1]) glTexCoord3f(*self.tex_coords[6:9]) glVertex2f(self.vertices[2], self.vertices[3]) glTexCoord3f(*self.tex_coords[9:12]) glVertex2f(self.vertices[0], self.vertices[3]) def get_kerning_pair(self, right_glyph): '''Not implemented. ''' return 0 class GlyphTextureAtlas(image.Texture): '''A texture within which glyphs can be drawn. ''' region_class = Glyph x = 0 y = 0 line_height = 0 def apply_blend_state(self): '''Set the OpenGL blend state for the glyphs in this texture. ''' glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) def fit(self, image): '''Place `image` within this texture. :Parameters: `image` : `pyglet.image.AbstractImage` Image to place within the texture. :rtype: `Glyph` :return: The glyph representing the image from this texture, or None if the image doesn't fit. ''' if self.x + image.width > self.width: self.x = 0 self.y += self.line_height + 1 self.line_height = 0 if self.y + image.height > self.height: return None self.line_height = max(self.line_height, image.height) region = self.get_region( self.x, self.y, image.width, image.height) if image.width > 0: region.blit_into(image, 0, 0, 0) self.x += image.width + 1 return region class GlyphRenderer(object): '''Abstract class for creating glyph images. ''' def __init__(self, font): pass def render(self, text): raise NotImplementedError('Subclass must override') class FontException(Exception): '''Generic exception related to errors from the font module. Typically these relate to invalid font data.''' pass class Font(object): '''Abstract font class able to produce glyphs. To construct a font, use `pyglet.font.load`, which will instantiate the platform-specific font class. Internally, this class is used by the platform classes to manage the set of textures into which glyphs are written. :Ivariables: `ascent` : int Maximum ascent above the baseline, in pixels. `descent` : int Maximum descent below the baseline, in pixels. Usually negative. ''' texture_width = 256 texture_height = 256 texture_internalformat = GL_ALPHA # These should also be set by subclass when known ascent = 0 descent = 0 glyph_renderer_class = GlyphRenderer texture_class = GlyphTextureAtlas def __init__(self): self.textures = [] self.glyphs = {} @classmethod def add_font_data(cls, data): '''Add font data to the font loader. This is a class method and affects all fonts loaded. Data must be some byte string of data, for example, the contents of a TrueType font file. Subclasses can override this method to add the font data into the font registry. There is no way to instantiate a font given the data directly, you must use `pyglet.font.load` specifying the font name. ''' pass @classmethod def have_font(cls, name): '''Determine if a font with the given name is installed. :Parameters: `name` : str Name of a font to search for :rtype: bool ''' return True def create_glyph(self, image): '''Create a glyph using the given image. This is used internally by `Font` subclasses to add glyph data to the font. Glyphs are packed within large textures maintained by `Font`. This method inserts the image into a font texture and returns a glyph reference; it is up to the subclass to add metadata to the glyph. Applications should not use this method directly. :Parameters: `image` : `pyglet.image.AbstractImage` The image to write to the font texture. :rtype: `Glyph` ''' glyph = None for texture in self.textures: glyph = texture.fit(image) if glyph: break if not glyph: if image.width > self.texture_width or \ image.height > self.texture_height: texture = self.texture_class.create_for_size(GL_TEXTURE_2D, image.width * 2, image.height * 2, self.texture_internalformat) self.texture_width = texture.width self.texture_height = texture.height else: texture = self.texture_class.create_for_size(GL_TEXTURE_2D, self.texture_width, self.texture_height, self.texture_internalformat) self.textures.insert(0, texture) glyph = texture.fit(image) return glyph def get_glyphs(self, text): '''Create and return a list of Glyphs for `text`. If any characters do not have a known glyph representation in this font, a substitution will be made. :Parameters: `text` : str or unicode Text to render. :rtype: list of `Glyph` ''' glyph_renderer = None glyphs = [] # glyphs that are committed. for c in get_grapheme_clusters(unicode(text)): # Get the glyph for 'c'. Hide tabs (Windows and Linux render # boxes) if c == '\t': c = ' ' if c not in self.glyphs: if not glyph_renderer: glyph_renderer = self.glyph_renderer_class(self) self.glyphs[c] = glyph_renderer.render(c) glyphs.append(self.glyphs[c]) return glyphs def get_glyphs_for_width(self, text, width): '''Return a list of glyphs for `text` that fit within the given width. If the entire text is larger than 'width', as much as possible will be used while breaking after a space or zero-width space character. If a newline is encountered in text, only text up to that newline will be used. If no break opportunities (newlines or spaces) occur within `width`, the text up to the first break opportunity will be used (this will exceed `width`). If there are no break opportunities, the entire text will be used. You can assume that each character of the text is represented by exactly one glyph; so the amount of text "used up" can be determined by examining the length of the returned glyph list. :Parameters: `text` : str or unicode Text to render. `width` : int Maximum width of returned glyphs. :rtype: list of `Glyph` :see: `GlyphString` ''' glyph_renderer = None glyph_buffer = [] # next glyphs to be added, as soon as a BP is found glyphs = [] # glyphs that are committed. for c in text: if c == '\n': glyphs += glyph_buffer break # Get the glyph for 'c' if c not in self.glyphs: if not glyph_renderer: glyph_renderer = self.glyph_renderer_class(self) self.glyphs[c] = glyph_renderer.render(c) glyph = self.glyphs[c] # Add to holding buffer and measure glyph_buffer.append(glyph) width -= glyph.advance # If over width and have some committed glyphs, finish. if width <= 0 and len(glyphs) > 0: break # If a valid breakpoint, commit holding buffer if c in u'\u0020\u200b': glyphs += glyph_buffer glyph_buffer = [] # If nothing was committed, commit everything (no breakpoints found). if len(glyphs) == 0: glyphs = glyph_buffer return glyphs
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' # TODO Tiger and later: need to set kWindowApplicationScaledAttribute for DPI # independence? import math from pyglet.font import base import pyglet.image from pyglet.libs.darwin.cocoapy import * class QuartzGlyphRenderer(base.GlyphRenderer): def __init__(self, font): super(QuartzGlyphRenderer, self).__init__(font) self.font = font def render(self, text): # Using CTLineDraw seems to be the only way to make sure that the text # is drawn with the specified font when that font is a graphics font loaded from # memory. For whatever reason, [NSAttributedString drawAtPoint:] ignores # the graphics font if it not registered with the font manager. # So we just use CTLineDraw for both graphics fonts and installed fonts. ctFont = self.font.ctFont # Create an attributed string using text and font. attributes = c_void_p(cf.CFDictionaryCreateMutable(None, 1, cf.kCFTypeDictionaryKeyCallBacks, cf.kCFTypeDictionaryValueCallBacks)) cf.CFDictionaryAddValue(attributes, kCTFontAttributeName, ctFont) string = c_void_p(cf.CFAttributedStringCreate(None, CFSTR(text), attributes)) # Create a CTLine object to render the string. line = c_void_p(ct.CTLineCreateWithAttributedString(string)) cf.CFRelease(string) cf.CFRelease(attributes) # Get a bounding rectangle for glyphs in string. count = len(text) chars = (UniChar * count)(*map(ord,unicode(text))) glyphs = (CGGlyph * count)() ct.CTFontGetGlyphsForCharacters(ctFont, chars, glyphs, count) rect = ct.CTFontGetBoundingRectsForGlyphs(ctFont, 0, glyphs, None, count) # Get advance for all glyphs in string. advance = ct.CTFontGetAdvancesForGlyphs(ctFont, 0, glyphs, None, count) # Set image parameters: # We add 2 pixels to the bitmap width and height so that there will be a 1-pixel border # around the glyph image when it is placed in the texture atlas. This prevents # weird artifacts from showing up around the edges of the rendered glyph textures. # We adjust the baseline and lsb of the glyph by 1 pixel accordingly. width = max(int(math.ceil(rect.size.width) + 2), 1) height = max(int(math.ceil(rect.size.height) + 2), 1) baseline = -int(math.floor(rect.origin.y)) + 1 lsb = int(math.floor(rect.origin.x)) - 1 advance = int(round(advance)) # Create bitmap context. bitsPerComponent = 8 bytesPerRow = 4*width colorSpace = c_void_p(quartz.CGColorSpaceCreateDeviceRGB()) bitmap = c_void_p(quartz.CGBitmapContextCreate( None, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast)) # Draw text to bitmap context. quartz.CGContextSetShouldAntialias(bitmap, True) quartz.CGContextSetTextPosition(bitmap, -lsb, baseline) ct.CTLineDraw(line, bitmap) cf.CFRelease(line) # Create an image to get the data out. imageRef = c_void_p(quartz.CGBitmapContextCreateImage(bitmap)) bytesPerRow = quartz.CGImageGetBytesPerRow(imageRef) dataProvider = c_void_p(quartz.CGImageGetDataProvider(imageRef)) imageData = c_void_p(quartz.CGDataProviderCopyData(dataProvider)) buffersize = cf.CFDataGetLength(imageData) buffer = (c_byte * buffersize)() byteRange = CFRange(0, buffersize) cf.CFDataGetBytes(imageData, byteRange, buffer) quartz.CGImageRelease(imageRef) quartz.CGDataProviderRelease(imageData) cf.CFRelease(bitmap) cf.CFRelease(colorSpace) glyph_image = pyglet.image.ImageData(width, height, 'RGBA', buffer, bytesPerRow) glyph = self.font.create_glyph(glyph_image) glyph.set_bearings(baseline, lsb, advance) t = list(glyph.tex_coords) glyph.tex_coords = t[9:12] + t[6:9] + t[3:6] + t[:3] return glyph class QuartzFont(base.Font): glyph_renderer_class = QuartzGlyphRenderer _loaded_CGFont_table = {} def _lookup_font_with_family_and_traits(self, family, traits): # This method searches the _loaded_CGFont_table to find a loaded # font of the given family with the desired traits. If it can't find # anything with the exact traits, it tries to fall back to whatever # we have loaded that's close. If it can't find anything in the # given family at all, it returns None. # Check if we've loaded the font with the specified family. if family not in self._loaded_CGFont_table: return None # Grab a dictionary of all fonts in the family, keyed by traits. fonts = self._loaded_CGFont_table[family] if not fonts: return None # Return font with desired traits if it is available. if traits in fonts: return fonts[traits] # Otherwise try to find a font with some of the traits. for (t, f) in fonts.items(): if traits & t: return f # Otherwise try to return a regular font. if 0 in fonts: return fonts[0] # Otherwise return whatever we have. return fonts.values()[0] def _create_font_descriptor(self, family_name, traits): # Create an attribute dictionary. attributes = c_void_p(cf.CFDictionaryCreateMutable(None, 0, cf.kCFTypeDictionaryKeyCallBacks, cf.kCFTypeDictionaryValueCallBacks)) # Add family name to attributes. cfname = CFSTR(family_name) cf.CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, cfname) cf.CFRelease(cfname) # Construct a CFNumber to represent the traits. itraits = c_int32(traits) symTraits = c_void_p(cf.CFNumberCreate(None, kCFNumberSInt32Type, byref(itraits))) if symTraits: # Construct a dictionary to hold the traits values. traitsDict = c_void_p(cf.CFDictionaryCreateMutable(None, 0, cf.kCFTypeDictionaryKeyCallBacks, cf.kCFTypeDictionaryValueCallBacks)) if traitsDict: # Add CFNumber traits to traits dictionary. cf.CFDictionaryAddValue(traitsDict, kCTFontSymbolicTrait, symTraits) # Add traits dictionary to attributes. cf.CFDictionaryAddValue(attributes, kCTFontTraitsAttribute, traitsDict) cf.CFRelease(traitsDict) cf.CFRelease(symTraits) # Create font descriptor with attributes. descriptor = c_void_p(ct.CTFontDescriptorCreateWithAttributes(attributes)) cf.CFRelease(attributes) return descriptor def __init__(self, name, size, bold=False, italic=False, dpi=None): super(QuartzFont, self).__init__() if not name: name = 'Helvetica' # I don't know what is the right thing to do here. if dpi is None: dpi = 96 size = size * dpi / 72.0 # Construct traits value. traits = 0 if bold: traits |= kCTFontBoldTrait if italic: traits |= kCTFontItalicTrait name = unicode(name) # First see if we can find an appropriate font from our table of loaded fonts. cgFont = self._lookup_font_with_family_and_traits(name, traits) if cgFont: # Use cgFont from table to create a CTFont object with the specified size. self.ctFont = c_void_p(ct.CTFontCreateWithGraphicsFont(cgFont, size, None, None)) else: # Create a font descriptor for given name and traits and use it to create font. descriptor = self._create_font_descriptor(name, traits) self.ctFont = c_void_p(ct.CTFontCreateWithFontDescriptor(descriptor, size, None)) assert self.ctFont, "Couldn't load font: " + name self.ascent = int(math.ceil(ct.CTFontGetAscent(self.ctFont))) self.descent = -int(math.ceil(ct.CTFontGetDescent(self.ctFont))) @classmethod def have_font(cls, name): name = unicode(name) if name in cls._loaded_CGFont_table: return True # Try to create the font to see if it exists. # TODO: Find a better way to check. cfstring = CFSTR(name) cgfont = c_void_p(quartz.CGFontCreateWithFontName(cfstring)) cf.CFRelease(cfstring) if cgfont: cf.CFRelease(cgfont) return True return False @classmethod def add_font_data(cls, data): # Create a cgFont with the data. There doesn't seem to be a way to # register a font loaded from memory such that the operating system will # find it later. So instead we just store the cgFont in a table where # it can be found by our __init__ method. # Note that the iOS CTFontManager *is* able to register graphics fonts, # however this method is missing from CTFontManager on MacOS 10.6 dataRef = c_void_p(cf.CFDataCreate(None, data, len(data))) provider = c_void_p(quartz.CGDataProviderCreateWithCFData(dataRef)) cgFont = c_void_p(quartz.CGFontCreateWithDataProvider(provider)) cf.CFRelease(dataRef) quartz.CGDataProviderRelease(provider) # Create a template CTFont from the graphics font so that we can get font info. ctFont = c_void_p(ct.CTFontCreateWithGraphicsFont(cgFont, 1, None, None)) # Get info about the font to use as key in our font table. string = c_void_p(ct.CTFontCopyFamilyName(ctFont)) familyName = unicode(cfstring_to_string(string)) cf.CFRelease(string) string = c_void_p(ct.CTFontCopyFullName(ctFont)) fullName = unicode(cfstring_to_string(string)) cf.CFRelease(string) traits = ct.CTFontGetSymbolicTraits(ctFont) cf.CFRelease(ctFont) # Store font in table. We store it under both its family name and its # full name, since its not always clear which one will be looked up. if familyName not in cls._loaded_CGFont_table: cls._loaded_CGFont_table[familyName] = {} cls._loaded_CGFont_table[familyName][traits] = cgFont if fullName not in cls._loaded_CGFont_table: cls._loaded_CGFont_table[fullName] = {} cls._loaded_CGFont_table[fullName][traits] = cgFont
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Load fonts and render text. This is a fairly-low level interface to text rendering. Obtain a font using `load`:: from pyglet import font arial = font.load('Arial', 14, bold=True, italic=False) pyglet will load any system-installed fonts. You can add additional fonts (for example, from your program resources) using `add_file` or `add_directory`. Obtain a list of `Glyph` objects for a string of text using the `Font` object:: text = 'Hello, world!' glyphs = arial.get_glyphs(text) The most efficient way to render these glyphs is with a `GlyphString`:: glyph_string = GlyphString(text, glyphs) glyph_string.draw() There are also a variety of methods in both `Font` and `GlyphString` to facilitate word-wrapping. A convenient way to render a string of text is with a `Text`:: text = Text(font, text) text.draw() See the `pyglet.font.base` module for documentation on the base classes used by this package. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import sys import os import math import weakref import pyglet from pyglet.gl import * from pyglet import gl from pyglet import image from pyglet import window class GlyphString(object): '''An immutable string of glyphs that can be rendered quickly. This class is ideal for quickly rendering single or multi-line strings of text that use the same font. To wrap text using a glyph string, call `get_break_index` to find the optimal breakpoint for each line, the repeatedly call `draw` for each breakpoint. :deprecated: Use `pyglet.text.layout` classes. ''' def __init__(self, text, glyphs, x=0, y=0): '''Create a glyph string. The `text` string is used to determine valid breakpoints; all glyphs must have already been determined using `pyglet.font.base.Font.get_glyphs`. The string will be positioned with the baseline of the left-most glyph at the given coordinates. :Parameters: `text` : str or unicode String to represent. `glyphs` : list of `pyglet.font.base.Glyph` Glyphs representing `text`. `x` : float X coordinate of the left-side bearing of the left-most glyph. `y` : float Y coordinate of the baseline. ''' # Create an interleaved array in GL_T2F_V3F format and determine # state changes required. lst = [] texture = None self.text = text self.states = [] self.cumulative_advance = [] # for fast post-string breaking state_from = 0 state_length = 0 for i, glyph in enumerate(glyphs): if glyph.owner != texture: if state_length: self.states.append((state_from, state_length, texture)) texture = glyph.owner state_from = i state_length = 0 state_length += 1 t = glyph.tex_coords lst += [t[0], t[1], t[2], 1., x + glyph.vertices[0], y + glyph.vertices[1], 0., 1., t[3], t[4], t[5], 1., x + glyph.vertices[2], y + glyph.vertices[1], 0., 1., t[6], t[7], t[8], 1., x + glyph.vertices[2], y + glyph.vertices[3], 0., 1., t[9], t[10], t[11], 1., x + glyph.vertices[0], y + glyph.vertices[3], 0., 1.] x += glyph.advance self.cumulative_advance.append(x) self.states.append((state_from, state_length, texture)) self.array = (c_float * len(lst))(*lst) self.width = x def get_break_index(self, from_index, width): '''Find a breakpoint within the text for a given width. Returns a valid breakpoint after `from_index` so that the text between `from_index` and the breakpoint fits within `width` pixels. This method uses precomputed cumulative glyph widths to give quick answer, and so is much faster than `pyglet.font.base.Font.get_glyphs_for_width`. :Parameters: `from_index` : int Index of text to begin at, or 0 for the beginning of the string. `width` : float Maximum width to use. :rtype: int :return: the index of text which will be used as the breakpoint, or `from_index` if there is no valid breakpoint. ''' to_index = from_index if from_index >= len(self.text): return from_index if from_index: width += self.cumulative_advance[from_index-1] for i, (c, w) in enumerate( zip(self.text[from_index:], self.cumulative_advance[from_index:])): if c in u'\u0020\u200b': to_index = i + from_index + 1 if c == '\n': return i + from_index + 1 if w > width: return to_index return to_index def get_subwidth(self, from_index, to_index): '''Return the width of a slice of this string. :Parameters: `from_index` : int The start index of the string to measure. `to_index` : int The end index (exclusive) of the string to measure. :rtype: float ''' if to_index <= from_index: return 0 width = self.cumulative_advance[to_index-1] if from_index: width -= self.cumulative_advance[from_index-1] return width def draw(self, from_index=0, to_index=None): '''Draw a region of the glyph string. Assumes texture state is enabled. To enable the texture state:: from pyglet.gl import * glEnable(GL_TEXTURE_2D) :Parameters: `from_index` : int Start index of text to render. `to_index` : int End index (exclusive) of text to render. ''' if from_index >= len(self.text) or \ from_index == to_index or \ not self.text: return # XXX Safe to assume all required textures will use same blend state I # think. (otherwise move this into loop) self.states[0][2].apply_blend_state() if from_index: glPushMatrix() glTranslatef(-self.cumulative_advance[from_index-1], 0, 0) if to_index is None: to_index = len(self.text) glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glInterleavedArrays(GL_T4F_V4F, 0, self.array) for state_from, state_length, texture in self.states: if state_from + state_length < from_index: continue state_from = max(state_from, from_index) state_length = min(state_length, to_index - state_from) if state_length <= 0: break glBindTexture(GL_TEXTURE_2D, texture.id) glDrawArrays(GL_QUADS, state_from * 4, state_length * 4) glPopClientAttrib() if from_index: glPopMatrix() class _TextZGroup(pyglet.graphics.Group): z = 0 def set_state(self): glTranslatef(0, 0, self.z) def unset_state(self): glTranslatef(0, 0, -self.z) class Text(object): '''Simple displayable text. This is a convenience class for rendering strings of text. It takes care of caching the vertices so the text can be rendered every frame with little performance penalty. Text can be word-wrapped by specifying a `width` to wrap into. If the width is not specified, it gives the width of the text as laid out. :Ivariables: `x` : int X coordinate of the text `y` : int Y coordinate of the text :deprecated: Use `pyglet.text.Label`. ''' # Alignment constants #: Align the left edge of the text to the given X coordinate. LEFT = 'left' #: Align the horizontal center of the text to the given X coordinate. CENTER = 'center' #: Align the right edge of the text to the given X coordinate. RIGHT = 'right' #: Align the bottom of the descender of the final line of text with the #: given Y coordinate. BOTTOM = 'bottom' #: Align the baseline of the first line of text with the given Y #: coordinate. BASELINE = 'baseline' #: Align the top of the ascender of the first line of text with the given #: Y coordinate. TOP = 'top' # None: no multiline # 'width': multiline, wrapped to width # 'multiline': multiline, no wrap _wrap = None # Internal bookkeeping for wrap only. _width = None def __init__(self, font, text='', x=0, y=0, z=0, color=(1,1,1,1), width=None, halign=LEFT, valign=BASELINE): '''Create displayable text. :Parameters: `font` : `Font` Font to render the text in. `text` : str Initial string to render. `x` : float X coordinate of the left edge of the text. `y` : float Y coordinate of the baseline of the text. If the text is word-wrapped, this refers to the first line of text. `z` : float Z coordinate of the text plane. `color` : 4-tuple of float Color to render the text in. Alpha values can be specified in the fourth component. `width` : float Width to limit the rendering to. Text will be word-wrapped if necessary. `halign` : str Alignment of the text. See `Text.halign` for details. `valign` : str Controls positioning of the text based off the y coordinate. One of BASELINE, BOTTOM, CENTER or TOP. Defaults to BASELINE. ''' multiline = False if width is not None: self._width = width self._wrap = 'width' multiline = True elif '\n' in text: self._wrap = 'multiline' multiline = True self._group = _TextZGroup() self._document = pyglet.text.decode_text(text) self._layout = pyglet.text.layout.TextLayout(self._document, width=width, multiline=multiline, wrap_lines=width is not None, dpi=font.dpi, group=self._group) self._layout.begin_update() if self._wrap == 'multiline': self._document.set_style(0, len(text), dict(wrap=False)) self.font = font self.color = color self._x = x self.y = y self.z = z self.width = width self.halign = halign self.valign = valign self._update_layout_halign() self._layout.end_update() def _get_font(self): return self._font def _set_font(self, font): self._font = font self._layout.begin_update() self._document.set_style(0, len(self._document.text), { 'font_name': font.name, 'font_size': font.size, 'bold': font.bold, 'italic': font.italic, }) self._layout._dpi = font.dpi self._layout.end_update() font = property(_get_font, _set_font) def _get_color(self): color = self._document.get_style('color') if color is None: return (1., 1., 1., 1.) return tuple([c/255. for c in color]) def _set_color(self, color): color = [int(c * 255) for c in color] self._document.set_style(0, len(self._document.text), { 'color': color, }) color = property(_get_color, _set_color) def _update_layout_halign(self): if self._layout.multiline: # TextLayout has a different interpretation of halign that doesn't # consider the width to be a special factor; here we emulate the # old behaviour by fudging the layout x value. if self._layout.anchor_x == 'left': self._layout.x = self.x elif self._layout.anchor_x == 'center': self._layout.x = self.x + self._layout.width - \ self._layout.content_width // 2 elif self._layout.anchor_x == 'right': self._layout.x = self.x + 2 * self._layout.width - \ self._layout.content_width else: self._layout.x = self.x def _get_x(self): return self._x def _set_x(self, x): self._x = x self._update_layout_halign() x = property(_get_x, _set_x) def _get_y(self): return self._layout.y def _set_y(self, y): self._layout.y = y y = property(_get_y, _set_y) def _get_z(self): return self._group.z def _set_z(self, z): self._group.z = z z = property(_get_z, _set_z) def _update_wrap(self): if self._width is not None: self._wrap = 'width' elif '\n' in self.text: self._wrap = 'multiline' self._layout.begin_update() if self._wrap == None: self._layout.multiline = False elif self._wrap == 'width': self._layout.width = self._width self._layout.multiline = True self._document.set_style(0, len(self.text), dict(wrap=True)) elif self._wrap == 'multiline': self._layout.multiline = True self._document.set_style(0, len(self.text), dict(wrap=False)) self._update_layout_halign() self._layout.end_update() def _get_width(self): if self._wrap == 'width': return self._layout.width else: return self._layout.content_width def _set_width(self, width): self._width = width self._layout._wrap_lines_flag = width is not None self._update_wrap() width = property(_get_width, _set_width, doc='''Width of the text. When set, this enables word-wrapping to the specified width. Otherwise, the width of the text as it will be rendered can be determined. :type: float ''') def _get_height(self): return self._layout.content_height height = property(_get_height, doc='''Height of the text. This property is the ascent minus the descent of the font, unless there is more than one line of word-wrapped text, in which case the height takes into account the line leading. Read-only. :type: float ''') def _get_text(self): return self._document.text def _set_text(self, text): self._document.text = text self._update_wrap() text = property(_get_text, _set_text, doc='''Text to render. The glyph vertices are only recalculated as needed, so multiple changes to the text can be performed with no performance penalty. :type: str ''') def _get_halign(self): return self._layout.anchor_x def _set_halign(self, halign): self._layout.anchor_x = halign self._update_layout_halign() halign = property(_get_halign, _set_halign, doc='''Horizontal alignment of the text. The text is positioned relative to `x` and `width` according to this property, which must be one of the alignment constants `LEFT`, `CENTER` or `RIGHT`. :type: str ''') def _get_valign(self): return self._layout.anchor_y def _set_valign(self, valign): self._layout.anchor_y = valign valign = property(_get_valign, _set_valign, doc='''Vertical alignment of the text. The text is positioned relative to `y` according to this property, which must be one of the alignment constants `BOTTOM`, `BASELINE`, `CENTER` or `TOP`. :type: str ''') def _get_leading(self): return self._document.get_style('leading') or 0 def _set_leading(self, leading): self._document.set_style(0, len(self._document.text), { 'leading': leading, }) leading = property(_get_leading, _set_leading, doc='''Vertical space between adjacent lines, in pixels. :type: int ''') def _get_line_height(self): return self._font.ascent - self._font.descent + self.leading def _set_line_height(self, line_height): self.leading = line_height - (self._font.ascent - self._font.descent) line_height = property(_get_line_height, _set_line_height, doc='''Vertical distance between adjacent baselines, in pixels. :type: int ''') def draw(self): self._layout.draw() if not getattr(sys, 'is_epydoc', False): if sys.platform == 'darwin': if pyglet.options['darwin_cocoa']: from pyglet.font.quartz import QuartzFont _font_class = QuartzFont else: from pyglet.font.carbon import CarbonFont _font_class = CarbonFont elif sys.platform in ('win32', 'cygwin'): if pyglet.options['font'][0] == 'win32': from pyglet.font.win32 import Win32Font _font_class = Win32Font elif pyglet.options['font'][0] == 'gdiplus': from pyglet.font.win32 import GDIPlusFont _font_class = GDIPlusFont else: assert False, 'Unknown font driver' else: from pyglet.font.freetype import FreeTypeFont _font_class = FreeTypeFont def load(name=None, size=None, bold=False, italic=False, dpi=None): '''Load a font for rendering. :Parameters: `name` : str, or list of str Font family, for example, "Times New Roman". If a list of names is provided, the first one matching a known font is used. If no font can be matched to the name(s), a default font is used. In pyglet 1.1, the name may be omitted. `size` : float Size of the font, in points. The returned font may be an exact match or the closest available. In pyglet 1.1, the size may be omitted, and defaults to 12pt. `bold` : bool If True, a bold variant is returned, if one exists for the given family and size. `italic` : bool If True, an italic variant is returned, if one exists for the given family and size. `dpi` : float The assumed resolution of the display device, for the purposes of determining the pixel size of the font. Defaults to 96. :rtype: `Font` ''' # Arbitrary default size if size is None: size = 12 if dpi is None: dpi = 96 # Find first matching name if type(name) in (tuple, list): for n in name: if _font_class.have_font(n): name = n break else: name = None # Locate or create font cache shared_object_space = gl.current_context.object_space if not hasattr(shared_object_space, 'pyglet_font_font_cache'): shared_object_space.pyglet_font_font_cache = \ weakref.WeakValueDictionary() shared_object_space.pyglet_font_font_hold = [] font_cache = shared_object_space.pyglet_font_font_cache font_hold = shared_object_space.pyglet_font_font_hold # Look for font name in font cache descriptor = (name, size, bold, italic, dpi) if descriptor in font_cache: return font_cache[descriptor] # Not in cache, create from scratch font = _font_class(name, size, bold=bold, italic=italic, dpi=dpi) # Save parameters for new-style layout classes to recover font.name = name font.size = size font.bold = bold font.italic = italic font.dpi = dpi # Cache font in weak-ref dictionary to avoid reloading while still in use font_cache[descriptor] = font # Hold onto refs of last three loaded fonts to prevent them being # collected if momentarily dropped. del font_hold[3:] font_hold.insert(0, font) return font def add_file(font): '''Add a font to pyglet's search path. In order to load a font that is not installed on the system, you must call this method to tell pyglet that it exists. You can supply either a filename or any file-like object. The font format is platform-dependent, but is typically a TrueType font file containing a single font face. Note that to load this file after adding it you must specify the face name to `load`, not the filename. :Parameters: `font` : str or file Filename or file-like object to load fonts from. ''' if type(font) in (str, unicode): font = open(font, 'rb') if hasattr(font, 'read'): font = font.read() _font_class.add_font_data(font) def add_directory(dir): '''Add a directory of fonts to pyglet's search path. This function simply calls `add_file` for each file with a ``.ttf`` extension in the given directory. Subdirectories are not searched. :Parameters: `dir` : str Directory that contains font files. ''' for file in os.listdir(dir): if file[-4:].lower() == '.ttf': add_file(os.path.join(dir, file))
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' from ctypes import * from base import FontException import pyglet.lib _libfreetype = pyglet.lib.load_library('freetype') _font_data = {} def _get_function(name, argtypes, rtype): try: func = getattr(_libfreetype, name) func.argtypes = argtypes func.restype = rtype return func except AttributeError, e: raise ImportError(e) FT_Done_FreeType = _get_function('FT_Done_FreeType', [c_void_p], None) FT_Done_Face = _get_function('FT_Done_Face', [c_void_p], None) class FT_LibraryRec(Structure): _fields_ = [ ('dummy', c_int), ] def __del__(self): global _library try: FT_Done_FreeType(byref(self)) _library = None except: pass FT_Library = POINTER(FT_LibraryRec) class FT_Glyph_Metrics(Structure): _fields_ = [ ('width', c_long), ('height', c_long), ('horiBearingX', c_long), ('horiBearingY', c_long), ('horiAdvance', c_long), ('vertBearingX', c_long), ('vertBearingY', c_long), ('vertAdvance', c_long), ] def dump(self): for (name, type) in self._fields_: print 'FT_Glyph_Metrics', name, `getattr(self, name)` class FT_Generic(Structure): _fields_ = [('data', c_void_p), ('finalizer', c_void_p)] class FT_BBox(Structure): _fields_ = [('xMin', c_long), ('yMin', c_long), ('xMax', c_long), ('yMax', c_long)] class FT_Vector(Structure): _fields_ = [('x', c_long), ('y', c_long)] class FT_Bitmap(Structure): _fields_ = [ ('rows', c_int), ('width', c_int), ('pitch', c_int), # declaring buffer as c_char_p confuses ctypes, poor dear ('buffer', POINTER(c_ubyte)), ('num_grays', c_short), ('pixel_mode', c_ubyte), ('palette_mode', c_char), ('palette', c_void_p), ] class FT_Outline(Structure): _fields_ = [ ('n_contours', c_short), # number of contours in glyph ('n_points', c_short), # number of points in the glyph ('points', POINTER(FT_Vector)), # the outline's points ('tags', c_char_p), # the points flags ('contours', POINTER(c_short)), # the contour end points ('flags', c_int), # outline masks ] class FT_GlyphSlotRec(Structure): _fields_ = [ ('library', FT_Library), ('face', c_void_p), ('next', c_void_p), ('reserved', c_uint), ('generic', FT_Generic), ('metrics', FT_Glyph_Metrics), ('linearHoriAdvance', c_long), ('linearVertAdvance', c_long), ('advance', FT_Vector), ('format', c_int), ('bitmap', FT_Bitmap), ('bitmap_left', c_int), ('bitmap_top', c_int), ('outline', FT_Outline), ('num_subglyphs', c_uint), ('subglyphs', c_void_p), ('control_data', c_void_p), ('control_len', c_long), ('lsb_delta', c_long), ('rsb_delta', c_long), ('other', c_void_p), ('internal', c_void_p), ] FT_GlyphSlot = POINTER(FT_GlyphSlotRec) class FT_Size_Metrics(Structure): _fields_ = [ ('x_ppem', c_ushort), # horizontal pixels per EM ('y_ppem', c_ushort), # vertical pixels per EM ('x_scale', c_long), # two scales used to convert font units ('y_scale', c_long), # to 26.6 frac. pixel coordinates ('ascender', c_long), # ascender in 26.6 frac. pixels ('descender', c_long), # descender in 26.6 frac. pixels ('height', c_long), # text height in 26.6 frac. pixels ('max_advance', c_long), # max horizontal advance, in 26.6 pixels ] class FT_SizeRec(Structure): _fields_ = [ ('face', c_void_p), ('generic', FT_Generic), ('metrics', FT_Size_Metrics), ('internal', c_void_p), ] FT_Size = POINTER(FT_SizeRec) class FT_Bitmap_Size(Structure): _fields_ = [ ('height', c_ushort), ('width', c_ushort), ('size', c_long), ('x_ppem', c_long), ('y_ppem', c_long), ] # face_flags values FT_FACE_FLAG_SCALABLE = 1 << 0 FT_FACE_FLAG_FIXED_SIZES = 1 << 1 FT_FACE_FLAG_FIXED_WIDTH = 1 << 2 FT_FACE_FLAG_SFNT = 1 << 3 FT_FACE_FLAG_HORIZONTAL = 1 << 4 FT_FACE_FLAG_VERTICAL = 1 << 5 FT_FACE_FLAG_KERNING = 1 << 6 FT_FACE_FLAG_FAST_GLYPHS = 1 << 7 FT_FACE_FLAG_MULTIPLE_MASTERS = 1 << 8 FT_FACE_FLAG_GLYPH_NAMES = 1 << 9 FT_FACE_FLAG_EXTERNAL_STREAM = 1 << 10 FT_FACE_FLAG_HINTER = 1 << 11 class FT_FaceRec(Structure): _fields_ = [ ('num_faces', c_long), ('face_index', c_long), ('face_flags', c_long), ('style_flags', c_long), ('num_glyphs', c_long), ('family_name', c_char_p), ('style_name', c_char_p), ('num_fixed_sizes', c_int), ('available_sizes', POINTER(FT_Bitmap_Size)), ('num_charmaps', c_int), ('charmaps', c_void_p), ('generic', FT_Generic), ('bbox', FT_BBox), ('units_per_EM', c_ushort), ('ascender', c_short), ('descender', c_short), ('height', c_short), ('max_advance_width', c_short), ('max_advance_height', c_short), ('underline_position', c_short), ('underline_thickness', c_short), ('glyph', FT_GlyphSlot), ('size', FT_Size), ('charmap', c_void_p), ('driver', c_void_p), ('memory', c_void_p), ('stream', c_void_p), ('sizes_list_head', c_void_p), ('sizes_list_tail', c_void_p), ('autohint', FT_Generic), ('extensions', c_void_p), ('internal', c_void_p), ] def dump(self): for (name, type) in self._fields_: print 'FT_FaceRec', name, `getattr(self, name)` def has_kerning(self): return self.face_flags & FT_FACE_FLAG_KERNING FT_Face = POINTER(FT_FaceRec) class Error(Exception): def __init__(self, message, errcode): self.message = message self.errcode = errcode def __str__(self): return '%s: %s (%s)'%(self.__class__.__name__, self.message, self._ft_errors.get(self.errcode, 'unknown error')) _ft_errors = { 0x00: "no error" , 0x01: "cannot open resource" , 0x02: "unknown file format" , 0x03: "broken file" , 0x04: "invalid FreeType version" , 0x05: "module version is too low" , 0x06: "invalid argument" , 0x07: "unimplemented feature" , 0x08: "broken table" , 0x09: "broken offset within table" , 0x10: "invalid glyph index" , 0x11: "invalid character code" , 0x12: "unsupported glyph image format" , 0x13: "cannot render this glyph format" , 0x14: "invalid outline" , 0x15: "invalid composite glyph" , 0x16: "too many hints" , 0x17: "invalid pixel size" , 0x20: "invalid object handle" , 0x21: "invalid library handle" , 0x22: "invalid module handle" , 0x23: "invalid face handle" , 0x24: "invalid size handle" , 0x25: "invalid glyph slot handle" , 0x26: "invalid charmap handle" , 0x27: "invalid cache manager handle" , 0x28: "invalid stream handle" , 0x30: "too many modules" , 0x31: "too many extensions" , 0x40: "out of memory" , 0x41: "unlisted object" , 0x51: "cannot open stream" , 0x52: "invalid stream seek" , 0x53: "invalid stream skip" , 0x54: "invalid stream read" , 0x55: "invalid stream operation" , 0x56: "invalid frame operation" , 0x57: "nested frame access" , 0x58: "invalid frame read" , 0x60: "raster uninitialized" , 0x61: "raster corrupted" , 0x62: "raster overflow" , 0x63: "negative height while rastering" , 0x70: "too many registered caches" , 0x80: "invalid opcode" , 0x81: "too few arguments" , 0x82: "stack overflow" , 0x83: "code overflow" , 0x84: "bad argument" , 0x85: "division by zero" , 0x86: "invalid reference" , 0x87: "found debug opcode" , 0x88: "found ENDF opcode in execution stream" , 0x89: "nested DEFS" , 0x8A: "invalid code range" , 0x8B: "execution context too long" , 0x8C: "too many function definitions" , 0x8D: "too many instruction definitions" , 0x8E: "SFNT font table missing" , 0x8F: "horizontal header (hhea, table missing" , 0x90: "locations (loca, table missing" , 0x91: "name table missing" , 0x92: "character map (cmap, table missing" , 0x93: "horizontal metrics (hmtx, table missing" , 0x94: "PostScript (post, table missing" , 0x95: "invalid horizontal metrics" , 0x96: "invalid character map (cmap, format" , 0x97: "invalid ppem value" , 0x98: "invalid vertical metrics" , 0x99: "could not find context" , 0x9A: "invalid PostScript (post, table format" , 0x9B: "invalid PostScript (post, table" , 0xA0: "opcode syntax error" , 0xA1: "argument stack underflow" , 0xA2: "ignore" , 0xB0: "`STARTFONT' field missing" , 0xB1: "`FONT' field missing" , 0xB2: "`SIZE' field missing" , 0xB3: "`CHARS' field missing" , 0xB4: "`STARTCHAR' field missing" , 0xB5: "`ENCODING' field missing" , 0xB6: "`BBX' field missing" , 0xB7: "`BBX' too big" , } FT_LOAD_RENDER = 0x4 FT_F26Dot6 = c_long FT_Init_FreeType = _get_function('FT_Init_FreeType', [POINTER(FT_Library)], c_int) FT_New_Memory_Face = _get_function('FT_New_Memory_Face', [FT_Library, POINTER(c_byte), c_long, c_long, POINTER(FT_Face)], c_int) FT_New_Face = _get_function('FT_New_Face', [FT_Library, c_char_p, c_long, POINTER(FT_Face)], c_int) FT_Set_Pixel_Sizes = _get_function('FT_Set_Pixel_Sizes', [FT_Face, c_uint, c_uint], c_int) FT_Set_Char_Size = _get_function('FT_Set_Char_Size', [FT_Face, FT_F26Dot6, FT_F26Dot6, c_uint, c_uint], c_int) FT_Load_Glyph = _get_function('FT_Load_Glyph', [FT_Face, c_uint, c_int32], c_int) FT_Get_Char_Index = _get_function('FT_Get_Char_Index', [FT_Face, c_ulong], c_uint) FT_Load_Char = _get_function('FT_Load_Char', [FT_Face, c_ulong, c_int], c_int) FT_Get_Kerning = _get_function('FT_Get_Kerning', [FT_Face, c_uint, c_uint, c_uint, POINTER(FT_Vector)], c_int) # SFNT interface class FT_SfntName(Structure): _fields_ = [ ('platform_id', c_ushort), ('encoding_id', c_ushort), ('language_id', c_ushort), ('name_id', c_ushort), ('string', POINTER(c_byte)), ('string_len', c_uint) ] FT_Get_Sfnt_Name_Count = _get_function('FT_Get_Sfnt_Name_Count', [FT_Face], c_uint) FT_Get_Sfnt_Name = _get_function('FT_Get_Sfnt_Name', [FT_Face, c_uint, POINTER(FT_SfntName)], c_int) TT_PLATFORM_MICROSOFT = 3 TT_MS_ID_UNICODE_CS = 1 TT_NAME_ID_COPYRIGHT = 0 TT_NAME_ID_FONT_FAMILY = 1 TT_NAME_ID_FONT_SUBFAMILY = 2 TT_NAME_ID_UNIQUE_ID = 3 TT_NAME_ID_FULL_NAME = 4 TT_NAME_ID_VERSION_STRING = 5 TT_NAME_ID_PS_NAME = 6 TT_NAME_ID_TRADEMARK = 7 TT_NAME_ID_MANUFACTURER = 8 TT_NAME_ID_DESIGNER = 9 TT_NAME_ID_DESCRIPTION = 10 TT_NAME_ID_VENDOR_URL = 11 TT_NAME_ID_DESIGNER_URL = 12 TT_NAME_ID_LICENSE = 13 TT_NAME_ID_LICENSE_URL = 14 TT_NAME_ID_PREFERRED_FAMILY = 16 TT_NAME_ID_PREFERRED_SUBFAMILY= 17 TT_NAME_ID_MAC_FULL_NAME = 18 TT_NAME_ID_CID_FINDFONT_NAME = 20 _library = None def ft_get_library(): global _library if not _library: _library = FT_Library() error = FT_Init_FreeType(byref(_library)) if error: raise FontException( 'an error occurred during library initialization', error) return _library
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * from warnings import warn import pyglet.lib from pyglet.font import base from pyglet import image from pyglet.font.freetype_lib import * from pyglet.compat import asbytes # fontconfig library definitions fontconfig = pyglet.lib.load_library('fontconfig') FcResult = c_int fontconfig.FcPatternBuild.restype = c_void_p fontconfig.FcPatternCreate.restype = c_void_p fontconfig.FcFontMatch.restype = c_void_p fontconfig.FcFreeTypeCharIndex.restype = c_uint fontconfig.FcPatternAddDouble.argtypes = [c_void_p, c_char_p, c_double] fontconfig.FcPatternAddInteger.argtypes = [c_void_p, c_char_p, c_int] fontconfig.FcPatternAddString.argtypes = [c_void_p, c_char_p, c_char_p] fontconfig.FcConfigSubstitute.argtypes = [c_void_p, c_void_p, c_int] fontconfig.FcDefaultSubstitute.argtypes = [c_void_p] fontconfig.FcFontMatch.argtypes = [c_void_p, c_void_p, c_void_p] fontconfig.FcPatternDestroy.argtypes = [c_void_p] fontconfig.FcPatternGetFTFace.argtypes = [c_void_p, c_char_p, c_int, c_void_p] fontconfig.FcPatternGet.argtypes = [c_void_p, c_char_p, c_int, c_void_p] FC_FAMILY = asbytes('family') FC_SIZE = asbytes('size') FC_SLANT = asbytes('slant') FC_WEIGHT = asbytes('weight') FC_FT_FACE = asbytes('ftface') FC_FILE = asbytes('file') FC_WEIGHT_REGULAR = 80 FC_WEIGHT_BOLD = 200 FC_SLANT_ROMAN = 0 FC_SLANT_ITALIC = 100 FT_STYLE_FLAG_ITALIC = 1 FT_STYLE_FLAG_BOLD = 2 (FT_RENDER_MODE_NORMAL, FT_RENDER_MODE_LIGHT, FT_RENDER_MODE_MONO, FT_RENDER_MODE_LCD, FT_RENDER_MODE_LCD_V) = range(5) def FT_LOAD_TARGET_(x): return (x & 15) << 16 FT_LOAD_TARGET_NORMAL = FT_LOAD_TARGET_(FT_RENDER_MODE_NORMAL) FT_LOAD_TARGET_LIGHT = FT_LOAD_TARGET_(FT_RENDER_MODE_LIGHT) FT_LOAD_TARGET_MONO = FT_LOAD_TARGET_(FT_RENDER_MODE_MONO) FT_LOAD_TARGET_LCD = FT_LOAD_TARGET_(FT_RENDER_MODE_LCD) FT_LOAD_TARGET_LCD_V = FT_LOAD_TARGET_(FT_RENDER_MODE_LCD_V) (FT_PIXEL_MODE_NONE, FT_PIXEL_MODE_MONO, FT_PIXEL_MODE_GRAY, FT_PIXEL_MODE_GRAY2, FT_PIXEL_MODE_GRAY4, FT_PIXEL_MODE_LCD, FT_PIXEL_MODE_LCD_V) = range(7) (FcTypeVoid, FcTypeInteger, FcTypeDouble, FcTypeString, FcTypeBool, FcTypeMatrix, FcTypeCharSet, FcTypeFTFace, FcTypeLangSet) = range(9) FcType = c_int (FcMatchPattern, FcMatchFont) = range(2) FcMatchKind = c_int class _FcValueUnion(Union): _fields_ = [ ('s', c_char_p), ('i', c_int), ('b', c_int), ('d', c_double), ('m', c_void_p), ('c', c_void_p), ('f', c_void_p), ('p', c_void_p), ('l', c_void_p), ] class FcValue(Structure): _fields_ = [ ('type', FcType), ('u', _FcValueUnion) ] # End of library definitions def f16p16_to_float(value): return float(value) / (1 << 16) def float_to_f16p16(value): return int(value * (1 << 16)) def f26p6_to_float(value): return float(value) / (1 << 6) def float_to_f26p6(value): return int(value * (1 << 6)) class FreeTypeGlyphRenderer(base.GlyphRenderer): def __init__(self, font): super(FreeTypeGlyphRenderer, self).__init__(font) self.font = font def render(self, text): face = self.font.face FT_Set_Char_Size(face, 0, self.font._face_size, self.font._dpi, self.font._dpi) glyph_index = fontconfig.FcFreeTypeCharIndex(byref(face), ord(text[0])) error = FT_Load_Glyph(face, glyph_index, FT_LOAD_RENDER) if error != 0: raise base.FontException( 'Could not load glyph for "%c"' % text[0], error) glyph_slot = face.glyph.contents width = glyph_slot.bitmap.width height = glyph_slot.bitmap.rows baseline = height - glyph_slot.bitmap_top lsb = glyph_slot.bitmap_left advance = int(f26p6_to_float(glyph_slot.advance.x)) mode = glyph_slot.bitmap.pixel_mode pitch = glyph_slot.bitmap.pitch if mode == FT_PIXEL_MODE_MONO: # BCF fonts always render to 1 bit mono, regardless of render # flags. (freetype 2.3.5) bitmap_data = cast(glyph_slot.bitmap.buffer, POINTER(c_ubyte * (pitch * height))).contents data = (c_ubyte * (pitch * 8 * height))() data_i = 0 for byte in bitmap_data: # Data is MSB; left-most pixel in a byte has value 128. data[data_i + 0] = (byte & 0x80) and 255 or 0 data[data_i + 1] = (byte & 0x40) and 255 or 0 data[data_i + 2] = (byte & 0x20) and 255 or 0 data[data_i + 3] = (byte & 0x10) and 255 or 0 data[data_i + 4] = (byte & 0x08) and 255 or 0 data[data_i + 5] = (byte & 0x04) and 255 or 0 data[data_i + 6] = (byte & 0x02) and 255 or 0 data[data_i + 7] = (byte & 0x01) and 255 or 0 data_i += 8 pitch <<= 3 elif mode == FT_PIXEL_MODE_GRAY: # Usual case data = glyph_slot.bitmap.buffer else: raise base.FontException('Unsupported render mode for this glyph') # pitch should be negative, but much faster to just swap tex_coords img = image.ImageData(width, height, 'A', data, pitch) glyph = self.font.create_glyph(img) glyph.set_bearings(baseline, lsb, advance) t = list(glyph.tex_coords) glyph.tex_coords = t[9:12] + t[6:9] + t[3:6] + t[:3] return glyph class FreeTypeMemoryFont(object): def __init__(self, data): self.buffer = (ctypes.c_byte * len(data))() ctypes.memmove(self.buffer, data, len(data)) ft_library = ft_get_library() self.face = FT_Face() r = FT_New_Memory_Face(ft_library, self.buffer, len(self.buffer), 0, self.face) if r != 0: raise base.FontException('Could not load font data') self.name = self.face.contents.family_name self.bold = self.face.contents.style_flags & FT_STYLE_FLAG_BOLD != 0 self.italic = self.face.contents.style_flags & FT_STYLE_FLAG_ITALIC != 0 # Replace Freetype's generic family name with TTF/OpenType specific # name if we can find one; there are some instances where Freetype # gets it wrong. if self.face.contents.face_flags & FT_FACE_FLAG_SFNT: name = FT_SfntName() for i in range(FT_Get_Sfnt_Name_Count(self.face)): result = FT_Get_Sfnt_Name(self.face, i, name) if result != 0: continue if not (name.platform_id == TT_PLATFORM_MICROSOFT and name.encoding_id == TT_MS_ID_UNICODE_CS): continue if name.name_id == TT_NAME_ID_FONT_FAMILY: string = string_at(name.string, name.string_len) self.name = string.decode('utf-16be', 'ignore') def __del__(self): try: FT_Done_Face(self.face) except: pass class FreeTypeFont(base.Font): glyph_renderer_class = FreeTypeGlyphRenderer # Map font (name, bold, italic) to FreeTypeMemoryFont _memory_fonts = {} def __init__(self, name, size, bold=False, italic=False, dpi=None): super(FreeTypeFont, self).__init__() if dpi is None: dpi = 96 # as of pyglet 1.1; pyglet 1.0 had 72. # Check if font name/style matches a font loaded into memory by user lname = name and name.lower() or '' if (lname, bold, italic) in self._memory_fonts: font = self._memory_fonts[lname, bold, italic] self._set_face(font.face, size, dpi) return # Use fontconfig to match the font (or substitute a default). ft_library = ft_get_library() match = self.get_fontconfig_match(name, size, bold, italic) if not match: raise base.FontException('Could not match font "%s"' % name) f = FT_Face() if fontconfig.FcPatternGetFTFace(match, FC_FT_FACE, 0, byref(f)) != 0: value = FcValue() result = fontconfig.FcPatternGet(match, FC_FILE, 0, byref(value)) if result != 0: raise base.FontException('No filename or FT face for "%s"' % \ name) result = FT_New_Face(ft_library, value.u.s, 0, byref(f)) if result: raise base.FontException('Could not load "%s": %d' % \ (name, result)) fontconfig.FcPatternDestroy(match) self._set_face(f, size, dpi) def _set_face(self, face, size, dpi): self.face = face.contents self._face_size = float_to_f26p6(size) self._dpi = dpi FT_Set_Char_Size(self.face, 0, float_to_f26p6(size), dpi, dpi) metrics = self.face.size.contents.metrics if metrics.ascender == 0 and metrics.descender == 0: # Workaround broken fonts with no metrics. Has been observed with # courR12-ISO8859-1.pcf.gz: "Courier" "Regular" # # None of the metrics fields are filled in, so render a glyph and # grab its height as the ascent, and make up an arbitrary # descent. i = fontconfig.FcFreeTypeCharIndex(byref(self.face), ord('X')) FT_Load_Glyph(self.face, i, FT_LOAD_RENDER) self.ascent = self.face.available_sizes.contents.height self.descent = -self.ascent // 4 # arbitrary. else: self.ascent = int(f26p6_to_float(metrics.ascender)) self.descent = int(f26p6_to_float(metrics.descender)) @staticmethod def get_fontconfig_match(name, size, bold, italic): if bold: bold = FC_WEIGHT_BOLD else: bold = FC_WEIGHT_REGULAR if italic: italic = FC_SLANT_ITALIC else: italic = FC_SLANT_ROMAN fontconfig.FcInit() if isinstance(name, unicode): name = name.encode('utf8') pattern = fontconfig.FcPatternCreate() fontconfig.FcPatternAddDouble(pattern, FC_SIZE, c_double(size)) fontconfig.FcPatternAddInteger(pattern, FC_WEIGHT, bold) fontconfig.FcPatternAddInteger(pattern, FC_SLANT, italic) fontconfig.FcPatternAddString(pattern, FC_FAMILY, name) fontconfig.FcConfigSubstitute(0, pattern, FcMatchPattern) fontconfig.FcDefaultSubstitute(pattern) # Look for a font that matches pattern result = FcResult() match = fontconfig.FcFontMatch(0, pattern, byref(result)) fontconfig.FcPatternDestroy(pattern) return match @classmethod def have_font(cls, name): value = FcValue() match = cls.get_fontconfig_match(name, 12, False, False) #result = fontconfig.FcPatternGet(match, FC_FAMILY, 0, byref(value)) if value.u.s == name: return True else: name = name.lower() for font in cls._memory_fonts.values(): if font.name.lower() == name: return True return False @classmethod def add_font_data(cls, data): font = FreeTypeMemoryFont(data) cls._memory_fonts[font.name.lower(), font.bold, font.italic] = font
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Load application resources from a known path. Loading resources by specifying relative paths to filenames is often problematic in Python, as the working directory is not necessarily the same directory as the application's script files. This module allows applications to specify a search path for resources. Relative paths are taken to be relative to the application's __main__ module. ZIP files can appear on the path; they will be searched inside. The resource module also behaves as expected when applications are bundled using py2exe or py2app. As well as providing file references (with the `file` function), the resource module also contains convenience functions for loading images, textures, fonts, media and documents. 3rd party modules or packages not bound to a specific application should construct their own `Loader` instance and override the path to use the resources in the module's directory. Path format ^^^^^^^^^^^ The resource path `path` (see also `Loader.__init__` and `Loader.path`) is a list of locations to search for resources. Locations are searched in the order given in the path. If a location is not valid (for example, if the directory does not exist), it is skipped. Locations in the path beginning with an ampersand (''@'' symbol) specify Python packages. Other locations specify a ZIP archive or directory on the filesystem. Locations that are not absolute are assumed to be relative to the script home. Some examples:: # Search just the `res` directory, assumed to be located alongside the # main script file. path = ['res'] # Search the directory containing the module `levels.level1`, followed # by the `res/images` directory. path = ['@levels.level1', 'res/images'] Paths are always case-sensitive and forward slashes are always used as path separators, even in cases when the filesystem or platform does not do this. This avoids a common programmer error when porting applications between platforms. The default path is ``['.']``. If you modify the path, you must call `reindex`. :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import os import weakref import sys import zipfile import pyglet from pyglet.compat import BytesIO class ResourceNotFoundException(Exception): '''The named resource was not found on the search path.''' def __init__(self, name): message = ('Resource "%s" was not found on the path. ' 'Ensure that the filename has the correct captialisation.') % name Exception.__init__(self, message) def get_script_home(): '''Get the directory containing the program entry module. For ordinary Python scripts, this is the directory containing the ``__main__`` module. For executables created with py2exe the result is the directory containing the running executable file. For OS X bundles created using Py2App the result is the Resources directory within the running bundle. If none of the above cases apply and the file for ``__main__`` cannot be determined the working directory is returned. :rtype: str ''' frozen = getattr(sys, 'frozen', None) if frozen in ('windows_exe', 'console_exe'): return os.path.dirname(sys.executable) elif frozen == 'macosx_app': return os.environ['RESOURCEPATH'] else: main = sys.modules['__main__'] if hasattr(main, '__file__'): return os.path.dirname(main.__file__) # Probably interactive return '' def get_settings_path(name): '''Get a directory to save user preferences. Different platforms have different conventions for where to save user preferences, saved games, and settings. This function implements those conventions. Note that the returned path may not exist: applications should use ``os.makedirs`` to construct it if desired. On Linux, a hidden directory `name` in the user's home directory is returned. On Windows (including under Cygwin) the `name` directory in the user's ``Application Settings`` directory is returned. On Mac OS X the `name` directory under ``~/Library/Application Support`` is returned. :Parameters: `name` : str The name of the application. :rtype: str ''' if sys.platform in ('cygwin', 'win32'): if 'APPDATA' in os.environ: return os.path.join(os.environ['APPDATA'], name) else: return os.path.expanduser('~/%s' % name) elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/%s' % name) else: return os.path.expanduser('~/.%s' % name) class Location(object): '''Abstract resource location. Given a location, a file can be loaded from that location with the `open` method. This provides a convenient way to specify a path to load files from, and not necessarily have that path reside on the filesystem. ''' def open(self, filename, mode='rb'): '''Open a file at this location. :Parameters: `filename` : str The filename to open. Absolute paths are not supported. Relative paths are not supported by most locations (you should specify only a filename with no path component). `mode` : str The file mode to open with. Only files opened on the filesystem make use of this parameter; others ignore it. :rtype: file object ''' raise NotImplementedError('abstract') class FileLocation(Location): '''Location on the filesystem. ''' def __init__(self, path): '''Create a location given a relative or absolute path. :Parameters: `path` : str Path on the filesystem. ''' self.path = path def open(self, filename, mode='rb'): return open(os.path.join(self.path, filename), mode) class ZIPLocation(Location): '''Location within a ZIP file. ''' def __init__(self, zip, dir): '''Create a location given an open ZIP file and a path within that file. :Parameters: `zip` : ``zipfile.ZipFile`` An open ZIP file from the ``zipfile`` module. `dir` : str A path within that ZIP file. Can be empty to specify files at the top level of the ZIP file. ''' self.zip = zip self.dir = dir def open(self, filename, mode='rb'): if self.dir: path = self.dir + '/' + filename else: path = filename text = self.zip.read(path) return BytesIO(text) class URLLocation(Location): '''Location on the network. This class uses the ``urlparse`` and ``urllib2`` modules to open files on the network given a URL. ''' def __init__(self, base_url): '''Create a location given a base URL. :Parameters: `base_url` : str URL string to prepend to filenames. ''' self.base = base_url def open(self, filename, mode='rb'): import urlparse import urllib2 url = urlparse.urljoin(self.base, filename) return urllib2.urlopen(url) class Loader(object): '''Load program resource files from disk. The loader contains a search path which can include filesystem directories, ZIP archives and Python packages. :Ivariables: `path` : list of str List of search locations. After modifying the path you must call the `reindex` method. `script_home` : str Base resource location, defaulting to the location of the application script. ''' def __init__(self, path=None, script_home=None): '''Create a loader for the given path. If no path is specified it defaults to ``['.']``; that is, just the program directory. See the module documentation for details on the path format. :Parameters: `path` : list of str List of locations to search for resources. `script_home` : str Base location of relative files. Defaults to the result of `get_script_home`. ''' if path is None: path = ['.'] if type(path) in (str, unicode): path = [path] self.path = list(path) if script_home is None: script_home = get_script_home() self._script_home = script_home self._index = None # Map name to image self._cached_textures = weakref.WeakValueDictionary() self._cached_images = weakref.WeakValueDictionary() self._cached_animations = weakref.WeakValueDictionary() # Map bin size to list of atlases self._texture_atlas_bins = {} def _require_index(self): if self._index is None: self.reindex() def reindex(self): '''Refresh the file index. You must call this method if `path` is changed or the filesystem layout changes. ''' self._index = {} for path in self.path: if path.startswith('@'): # Module name = path[1:] try: module = __import__(name) except: continue for component in name.split('.')[1:]: module = getattr(module, component) if hasattr(module, '__file__'): path = os.path.dirname(module.__file__) else: path = '' # interactive elif not os.path.isabs(path): # Add script base unless absolute assert '\\' not in path, \ 'Backslashes not permitted in relative path' path = os.path.join(self._script_home, path) if os.path.isdir(path): # Filesystem directory path = path.rstrip(os.path.sep) location = FileLocation(path) for dirpath, dirnames, filenames in os.walk(path): dirpath = dirpath[len(path) + 1:] # Force forward slashes for index if dirpath: parts = filter(None, dirpath.split(os.sep)) dirpath = '/'.join(parts) for filename in filenames: if dirpath: index_name = dirpath + '/' + filename else: index_name = filename self._index_file(index_name, location) else: # Find path component that is the ZIP file. dir = '' old_path = None while path and not os.path.isfile(path): old_path = path path, tail_dir = os.path.split(path) if path == old_path: break dir = '/'.join((tail_dir, dir)) if path == old_path: continue dir = dir.rstrip('/') # path is a ZIP file, dir resides within ZIP if path and zipfile.is_zipfile(path): zip = zipfile.ZipFile(path, 'r') location = ZIPLocation(zip, dir) for zip_name in zip.namelist(): #zip_name_dir, zip_name = os.path.split(zip_name) #assert '\\' not in name_dir #assert not name_dir.endswith('/') if zip_name.startswith(dir): if dir: zip_name = zip_name[len(dir)+1:] self._index_file(zip_name, location) def _index_file(self, name, location): if name not in self._index: self._index[name] = location def file(self, name, mode='rb'): '''Load a resource. :Parameters: `name` : str Filename of the resource to load. `mode` : str Combination of ``r``, ``w``, ``a``, ``b`` and ``t`` characters with the meaning as for the builtin ``open`` function. :rtype: file object ''' self._require_index() try: location = self._index[name] return location.open(name, mode) except KeyError: raise ResourceNotFoundException(name) def location(self, name): '''Get the location of a resource. This method is useful for opening files referenced from a resource. For example, an HTML file loaded as a resource might reference some images. These images should be located relative to the HTML file, not looked up individually in the loader's path. :Parameters: `name` : str Filename of the resource to locate. :rtype: `Location` ''' self._require_index() try: return self._index[name] except KeyError: raise ResourceNotFoundException(name) def add_font(self, name): '''Add a font resource to the application. Fonts not installed on the system must be added to pyglet before they can be used with `font.load`. Although the font is added with its filename using this function, it is loaded by specifying its family name. For example:: resource.add_font('action_man.ttf') action_man = font.load('Action Man') :Parameters: `name` : str Filename of the font resource to add. ''' self._require_index() from pyglet import font file = self.file(name) font.add_file(file) def _alloc_image(self, name, atlas=True): file = self.file(name) img = pyglet.image.load(name, file=file) if not atlas: return img.get_texture(True) # find an atlas suitable for the image bin = self._get_texture_atlas_bin(img.width, img.height) if bin is None: return img.get_texture(True) return bin.add(img) def _get_texture_atlas_bin(self, width, height): '''A heuristic for determining the atlas bin to use for a given image size. Returns None if the image should not be placed in an atlas (too big), otherwise the bin (a list of TextureAtlas). ''' # Large images are not placed in an atlas if width > 128 or height > 128: return None # Group images with small height separately to larger height (as the # allocator can't stack within a single row). bin_size = 1 if height > 32: bin_size = 2 try: bin = self._texture_atlas_bins[bin_size] except KeyError: bin = self._texture_atlas_bins[bin_size] = \ pyglet.image.atlas.TextureBin() return bin def image(self, name, flip_x=False, flip_y=False, rotate=0, atlas=True): '''Load an image with optional transformation. This is similar to `texture`, except the resulting image will be packed into a `TextureBin` if it is an appropriate size for packing. This is more efficient than loading images into separate textures. :Parameters: `name` : str Filename of the image source to load. `flip_x` : bool If True, the returned image will be flipped horizontally. `flip_y` : bool If True, the returned image will be flipped vertically. `rotate` : int The returned image will be rotated clockwise by the given number of degrees (a multiple of 90). `atlas` : bool If True, the image will be loaded into an atlas managed by pyglet. If atlas loading is not appropriate for specific texturing reasons (e.g. border control is required) then set this argument to False. :rtype: `Texture` :return: A complete texture if the image is large or not in an atlas, otherwise a `TextureRegion` of a texture atlas. ''' self._require_index() if name in self._cached_images: identity = self._cached_images[name] else: identity = self._cached_images[name] = self._alloc_image(name, atlas=atlas) if not rotate and not flip_x and not flip_y: return identity return identity.get_transform(flip_x, flip_y, rotate) def animation(self, name, flip_x=False, flip_y=False, rotate=0): '''Load an animation with optional transformation. Animations loaded from the same source but with different transformations will use the same textures. :Parameters: `name` : str Filename of the animation source to load. `flip_x` : bool If True, the returned image will be flipped horizontally. `flip_y` : bool If True, the returned image will be flipped vertically. `rotate` : int The returned image will be rotated clockwise by the given number of degrees (a multiple of 90). :rtype: `Animation` ''' self._require_index() try: identity = self._cached_animations[name] except KeyError: animation = pyglet.image.load_animation(name, self.file(name)) bin = self._get_texture_atlas_bin(animation.get_max_width(), animation.get_max_height()) if bin: animation.add_to_texture_bin(bin) identity = self._cached_animations[name] = animation if not rotate and not flip_x and not flip_y: return identity return identity.get_transform(flip_x, flip_y, rotate) def get_cached_image_names(self): '''Get a list of image filenames that have been cached. This is useful for debugging and profiling only. :rtype: list :return: List of str ''' self._require_index() return self._cached_images.keys() def get_cached_animation_names(self): '''Get a list of animation filenames that have been cached. This is useful for debugging and profiling only. :rtype: list :return: List of str ''' self._require_index() return self._cached_animations.keys() def get_texture_bins(self): '''Get a list of texture bins in use. This is useful for debugging and profiling only. :rtype: list :return: List of `TextureBin` ''' self._require_index() return self._texture_atlas_bins.values() def media(self, name, streaming=True): '''Load a sound or video resource. The meaning of `streaming` is as for `media.load`. Compressed sources cannot be streamed (that is, video and compressed audio cannot be streamed from a ZIP archive). :Parameters: `name` : str Filename of the media source to load. `streaming` : bool True if the source should be streamed from disk, False if it should be entirely decoded into memory immediately. :rtype: `media.Source` ''' self._require_index() from pyglet import media try: location = self._index[name] if isinstance(location, FileLocation): # Don't open the file if it's streamed from disk -- AVbin # needs to do it. path = os.path.join(location.path, name) return media.load(path, streaming=streaming) else: file = location.open(name) return media.load(name, file=file, streaming=streaming) except KeyError: raise ResourceNotFoundException(name) def texture(self, name): '''Load a texture. The named image will be loaded as a single OpenGL texture. If the dimensions of the image are not powers of 2 a `TextureRegion` will be returned. :Parameters: `name` : str Filename of the image resource to load. :rtype: `Texture` ''' self._require_index() if name in self._cached_textures: return self._cached_textures[name] file = self.file(name) texture = pyglet.image.load(name, file=file).get_texture() self._cached_textures[name] = texture return texture def html(self, name): '''Load an HTML document. :Parameters: `name` : str Filename of the HTML resource to load. :rtype: `FormattedDocument` ''' self._require_index() file = self.file(name) return pyglet.text.decode_html(file.read(), self.location(name)) def attributed(self, name): '''Load an attributed text document. See `pyglet.text.formats.attributed` for details on this format. :Parameters: `name` : str Filename of the attribute text resource to load. :rtype: `FormattedDocument` ''' self._require_index() file = self.file(name) return pyglet.text.load(name, file, 'text/vnd.pyglet-attributed') def text(self, name): '''Load a plain text document. :Parameters: `name` : str Filename of the plain text resource to load. :rtype: `UnformattedDocument` ''' self._require_index() file = self.file(name) return pyglet.text.load(name, file, 'text/plain') def get_cached_texture_names(self): '''Get the names of textures currently cached. :rtype: list of str ''' self._require_index() return self._cached_textures.keys() #: Default resource search path. #: #: Locations in the search path are searched in order and are always #: case-sensitive. After changing the path you must call `reindex`. #: #: See the module documentation for details on the path format. #: #: :type: list of str path = [] class _DefaultLoader(Loader): def _get_path(self): return path def _set_path(self, value): global path path = value path = property(_get_path, _set_path) _default_loader = _DefaultLoader() reindex = _default_loader.reindex file = _default_loader.file location = _default_loader.location add_font = _default_loader.add_font image = _default_loader.image animation = _default_loader.animation get_cached_image_names = _default_loader.get_cached_image_names get_cached_animation_names = _default_loader.get_cached_animation_names get_texture_bins = _default_loader.get_texture_bins media = _default_loader.media texture = _default_loader.texture html = _default_loader.html attributed = _default_loader.attributed text = _default_loader.text get_cached_texture_names = _default_loader.get_cached_texture_names
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import pyglet from pyglet.input.base import Tablet, TabletCanvas, TabletCursor from pyglet.window.carbon import CarbonEventHandler from pyglet.libs.darwin import * from pyglet.libs.darwin import _oscheck class CarbonTablet(Tablet): name = 'OS X System Tablet' def open(self, window): return CarbonTabletCanvas(window) _carbon_tablet = CarbonTablet() class CarbonTabletCanvas(TabletCanvas): def __init__(self, window): super(CarbonTabletCanvas, self).__init__(window) for funcname in dir(self): func = getattr(self, funcname) if hasattr(func, '_platform_event'): window._install_event_handler(func) self._cursors = {} self._cursor = None def close(self): # XXX TODO remove event handlers. pass def _get_cursor(self, proximity_rec): key = (proximity_rec.vendorID, proximity_rec.tabletID, proximity_rec.pointerID, proximity_rec.deviceID, proximity_rec.systemTabletID, proximity_rec.vendorPointerType, proximity_rec.pointerSerialNumber, proximity_rec.uniqueID, proximity_rec.pointerType) if key in self._cursors: cursor = self._cursors[key] else: self._cursors[key] = cursor = \ CarbonTabletCursor(proximity_rec.pointerType) self._cursor = cursor return cursor @CarbonEventHandler(kEventClassTablet, kEventTabletProximity) @CarbonEventHandler(kEventClassTablet, kEventTabletPoint) @CarbonEventHandler(kEventClassMouse, kEventMouseDragged) @CarbonEventHandler(kEventClassMouse, kEventMouseDown) @CarbonEventHandler(kEventClassMouse, kEventMouseUp) @CarbonEventHandler(kEventClassMouse, kEventMouseMoved) def _tablet_event(self, next_handler, ev, data): '''Process tablet event and return True if some event was processed. Return True if no tablet event found. ''' event_type = ctypes.c_uint32() r = carbon.GetEventParameter(ev, kEventParamTabletEventType, typeUInt32, None, ctypes.sizeof(event_type), None, ctypes.byref(event_type)) if r != noErr: return False if event_type.value == kEventTabletProximity: proximity_rec = TabletProximityRec() _oscheck( carbon.GetEventParameter(ev, kEventParamTabletProximityRec, typeTabletProximityRec, None, ctypes.sizeof(proximity_rec), None, ctypes.byref(proximity_rec)) ) cursor = self._get_cursor(proximity_rec) if proximity_rec.enterProximity: self.dispatch_event('on_enter', cursor) else: self.dispatch_event('on_leave', cursor) elif event_type.value == kEventTabletPoint: point_rec = TabletPointRec() _oscheck( carbon.GetEventParameter(ev, kEventParamTabletPointRec, typeTabletPointRec, None, ctypes.sizeof(point_rec), None, ctypes.byref(point_rec)) ) #x = point_rec.absX #y = point_rec.absY x, y = self.window._get_mouse_position(ev) pressure = point_rec.pressure / float(0xffff) #point_rec.tiltX, #point_rec.tiltY, #point_rec.rotation, #point_rec.tangentialPressure, self.dispatch_event('on_motion', self._cursor, x, y, pressure, 0., 0.) carbon.CallNextEventHandler(next_handler, ev) return noErr class CarbonTabletCursor(TabletCursor): def __init__(self, cursor_type): # First approximation based on my results from a Wacom consumer # tablet if cursor_type == 1: name = 'Stylus' elif cursor_type == 3: name = 'Eraser' super(CarbonTabletCursor, self).__init__(name) def get_tablets(display=None): return [_carbon_tablet]
Python
# Uses the HID API introduced in Mac OS X version 10.5 # http://developer.apple.com/library/mac/#technotes/tn2007/tn2187.html import sys __LP64__ = (sys.maxint > 2**32) from pyglet.libs.darwin.cocoapy import * # Load iokit framework iokit = cdll.LoadLibrary(util.find_library('IOKit')) # IOKit constants from # /System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDKeys.h kIOHIDOptionsTypeNone = 0x00 kIOHIDOptionsTypeSeizeDevice = 0x01 kIOHIDElementTypeInput_Misc = 1 kIOHIDElementTypeInput_Button = 2 kIOHIDElementTypeInput_Axis = 3 kIOHIDElementTypeInput_ScanCodes = 4 kIOHIDElementTypeOutput = 129 kIOHIDElementTypeFeature = 257 kIOHIDElementTypeCollection = 513 # /System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDUsageTables.h kHIDPage_GenericDesktop = 0x01 kHIDPage_Consumer = 0x0C kHIDUsage_GD_SystemSleep = 0x82 kHIDUsage_GD_SystemWakeUp = 0x83 kHIDUsage_GD_SystemAppMenu = 0x86 kHIDUsage_GD_SystemMenu = 0x89 kHIDUsage_GD_SystemMenuRight = 0x8A kHIDUsage_GD_SystemMenuLeft = 0x8B kHIDUsage_GD_SystemMenuUp = 0x8C kHIDUsage_GD_SystemMenuDown = 0x8D kHIDUsage_Csmr_Menu = 0x40 kHIDUsage_Csmr_FastForward = 0xB3 kHIDUsage_Csmr_Rewind = 0xB4 kHIDUsage_Csmr_Eject = 0xB8 kHIDUsage_Csmr_Mute = 0xE2 kHIDUsage_Csmr_VolumeIncrement = 0xE9 kHIDUsage_Csmr_VolumeDecrement = 0xEA IOReturn = c_int # IOReturn.h IOOptionBits = c_uint32 # IOTypes.h # IOHIDKeys.h IOHIDElementType = c_int IOHIDElementCollectionType = c_int if __LP64__: IOHIDElementCookie = c_uint32 else: IOHIDElementCookie = c_void_p iokit.IOHIDDeviceClose.restype = IOReturn iokit.IOHIDDeviceClose.argtypes = [c_void_p, IOOptionBits] iokit.IOHIDDeviceConformsTo.restype = c_ubyte iokit.IOHIDDeviceConformsTo.argtypes = [c_void_p, c_uint32, c_uint32] iokit.IOHIDDeviceCopyMatchingElements.restype = c_void_p iokit.IOHIDDeviceCopyMatchingElements.argtypes = [c_void_p, c_void_p, IOOptionBits] iokit.IOHIDDeviceGetProperty.restype = c_void_p iokit.IOHIDDeviceGetProperty.argtypes = [c_void_p, c_void_p] iokit.IOHIDDeviceGetTypeID.restype = CFTypeID iokit.IOHIDDeviceGetTypeID.argtypes = [] iokit.IOHIDDeviceGetValue.restype = IOReturn iokit.IOHIDDeviceGetValue.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDDeviceOpen.restype = IOReturn iokit.IOHIDDeviceOpen.argtypes = [c_void_p, IOOptionBits] iokit.IOHIDDeviceRegisterInputValueCallback.restype = None iokit.IOHIDDeviceRegisterInputValueCallback.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDDeviceRegisterRemovalCallback.restype = None iokit.IOHIDDeviceRegisterRemovalCallback.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDDeviceScheduleWithRunLoop.restype = None iokit.IOHIDDeviceScheduleWithRunLoop.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDDeviceUnscheduleFromRunLoop.restype = None iokit.IOHIDDeviceUnscheduleFromRunLoop.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDElementGetCollectionType.restype = IOHIDElementCollectionType iokit.IOHIDElementGetCollectionType.argtypes = [c_void_p] iokit.IOHIDElementGetCookie.restype = IOHIDElementCookie iokit.IOHIDElementGetCookie.argtypes = [c_void_p] iokit.IOHIDElementGetLogicalMax.restype = CFIndex iokit.IOHIDElementGetLogicalMax.argtypes = [c_void_p] iokit.IOHIDElementGetLogicalMin.restype = CFIndex iokit.IOHIDElementGetLogicalMin.argtypes = [c_void_p] iokit.IOHIDElementGetName.restype = c_void_p iokit.IOHIDElementGetName.argtypes = [c_void_p] iokit.IOHIDElementGetPhysicalMax.restype = CFIndex iokit.IOHIDElementGetPhysicalMax.argtypes = [c_void_p] iokit.IOHIDElementGetPhysicalMin.restype = CFIndex iokit.IOHIDElementGetPhysicalMin.argtypes = [c_void_p] iokit.IOHIDElementGetReportCount.restype = c_uint32 iokit.IOHIDElementGetReportCount.argtypes = [c_void_p] iokit.IOHIDElementGetReportID.restype = c_uint32 iokit.IOHIDElementGetReportID.argtypes = [c_void_p] iokit.IOHIDElementGetReportSize.restype = c_uint32 iokit.IOHIDElementGetReportSize.argtypes = [c_void_p] iokit.IOHIDElementGetType.restype = IOHIDElementType iokit.IOHIDElementGetType.argtypes = [c_void_p] iokit.IOHIDElementGetTypeID.restype = CFTypeID iokit.IOHIDElementGetTypeID.argtypes = [] iokit.IOHIDElementGetUnit.restype = c_uint32 iokit.IOHIDElementGetUnit.argtypes = [c_void_p] iokit.IOHIDElementGetUnitExponent.restype = c_uint32 iokit.IOHIDElementGetUnitExponent.argtypes = [c_void_p] iokit.IOHIDElementGetUsage.restype = c_uint32 iokit.IOHIDElementGetUsage.argtypes = [c_void_p] iokit.IOHIDElementGetUsagePage.restype = c_uint32 iokit.IOHIDElementGetUsagePage.argtypes = [c_void_p] iokit.IOHIDElementHasNullState.restype = c_bool iokit.IOHIDElementHasNullState.argtypes = [c_void_p] iokit.IOHIDElementHasPreferredState.restype = c_bool iokit.IOHIDElementHasPreferredState.argtypes = [c_void_p] iokit.IOHIDElementIsArray.restype = c_bool iokit.IOHIDElementIsArray.argtypes = [c_void_p] iokit.IOHIDElementIsNonLinear.restype = c_bool iokit.IOHIDElementIsNonLinear.argtypes = [c_void_p] iokit.IOHIDElementIsRelative.restype = c_bool iokit.IOHIDElementIsRelative.argtypes = [c_void_p] iokit.IOHIDElementIsVirtual.restype = c_bool iokit.IOHIDElementIsVirtual.argtypes = [c_void_p] iokit.IOHIDElementIsWrapping.restype = c_bool iokit.IOHIDElementIsWrapping.argtypes = [c_void_p] iokit.IOHIDManagerCreate.restype = c_void_p iokit.IOHIDManagerCreate.argtypes = [CFAllocatorRef, IOOptionBits] iokit.IOHIDManagerCopyDevices.restype = c_void_p iokit.IOHIDManagerCopyDevices.argtypes = [c_void_p] iokit.IOHIDManagerGetTypeID.restype = CFTypeID iokit.IOHIDManagerGetTypeID.argtypes = [] iokit.IOHIDManagerRegisterDeviceMatchingCallback.restype = None iokit.IOHIDManagerRegisterDeviceMatchingCallback.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDManagerScheduleWithRunLoop.restype = c_void_p iokit.IOHIDManagerScheduleWithRunLoop.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDManagerSetDeviceMatching.restype = None iokit.IOHIDManagerSetDeviceMatching.argtypes = [c_void_p, c_void_p] iokit.IOHIDValueGetElement.restype = c_void_p iokit.IOHIDValueGetElement.argtypes = [c_void_p] iokit.IOHIDValueGetIntegerValue.restype = CFIndex iokit.IOHIDValueGetIntegerValue.argtypes = [c_void_p] iokit.IOHIDValueGetTimeStamp.restype = c_uint64 iokit.IOHIDValueGetTimeStamp.argtypes = [c_void_p] iokit.IOHIDValueGetTypeID.restype = CFTypeID iokit.IOHIDValueGetTypeID.argtypes = [] # Callback function types HIDManagerCallback = CFUNCTYPE(None, c_void_p, c_int, c_void_p, c_void_p) HIDDeviceCallback = CFUNCTYPE(None, c_void_p, c_int, c_void_p) HIDDeviceValueCallback = CFUNCTYPE(None, c_void_p, c_int, c_void_p, c_void_p) ###################################################################### # HID Class Wrappers # Lookup tables cache python objects for the devices and elements so that # we can avoid creating multiple wrapper objects for the same device. _device_lookup = {} # IOHIDDeviceRef to python HIDDevice object _element_lookup = {} # IOHIDElementRef to python HIDDeviceElement object class HIDValue: def __init__(self, valueRef): # Check that this is a valid IOHIDValue. assert(valueRef) assert(cf.CFGetTypeID(valueRef) == iokit.IOHIDValueGetTypeID()) self.valueRef = valueRef self.timestamp = iokit.IOHIDValueGetTimeStamp(valueRef) self.intvalue = iokit.IOHIDValueGetIntegerValue(valueRef) elementRef = c_void_p(iokit.IOHIDValueGetElement(valueRef)) self.element = HIDDeviceElement.get_element(elementRef) class HIDDevice: @classmethod def get_device(cls, deviceRef): # deviceRef is a c_void_p pointing to an IOHIDDeviceRef if deviceRef.value in _device_lookup: return _device_lookup[deviceRef.value] else: device = HIDDevice(deviceRef) return device def __init__(self, deviceRef): # Check that we've got a valid IOHIDDevice. assert(deviceRef) assert(cf.CFGetTypeID(deviceRef) == iokit.IOHIDDeviceGetTypeID()) _device_lookup[deviceRef.value] = self self.deviceRef = deviceRef # Set attributes from device properties. self.transport = self.get_property("Transport") self.vendorID = self.get_property("VendorID") self.vendorIDSource = self.get_property("VendorIDSource") self.productID = self.get_property("ProductID") self.versionNumber = self.get_property("VersionNumber") self.manufacturer = self.get_property("Manufacturer") self.product = self.get_property("Product") self.serialNumber = self.get_property("SerialNumber") # always returns None; apple bug? self.locationID = self.get_property("LocationID") self.primaryUsage = self.get_property("PrimaryUsage") self.primaryUsagePage = self.get_property("PrimaryUsagePage") # Populate self.elements with our device elements. self.get_elements() # Set up callback functions. self.value_observers = set() self.removal_observers = set() self.register_removal_callback() self.register_input_value_callback() def dump_info(self): for x in ('manufacturer', 'product', 'transport', 'vendorID', 'vendorIDSource', 'productID', 'versionNumber', 'serialNumber', 'locationID', 'primaryUsage', 'primaryUsagePage'): value = getattr(self, x) print x + ":", value def unique_identifier(self): # Since we can't rely on the serial number, create our own identifier. # Can use this to find devices when they are plugged back in. return (self.manufacturer, self.product, self.vendorID, self.productID, self.versionNumber, self.primaryUsage, self.primaryUsagePage) def get_property(self, name): cfname = CFSTR(name) cfvalue = c_void_p(iokit.IOHIDDeviceGetProperty(self.deviceRef, cfname)) cf.CFRelease(cfname) return cftype_to_value(cfvalue) def open(self, exclusive_mode=False): if exclusive_mode: options = kIOHIDOptionsTypeSeizeDevice else: options = kIOHIDOptionsTypeNone return bool(iokit.IOHIDDeviceOpen(self.deviceRef, options)) def close(self): return bool(iokit.IOHIDDeviceClose(self.deviceRef, kIOHIDOptionsTypeNone)) def schedule_with_run_loop(self): iokit.IOHIDDeviceScheduleWithRunLoop( self.deviceRef, c_void_p(cf.CFRunLoopGetCurrent()), kCFRunLoopDefaultMode) def unschedule_from_run_loop(self): iokit.IOHIDDeviceUnscheduleFromRunLoop( self.deviceRef, c_void_p(cf.CFRunLoopGetCurrent()), kCFRunLoopDefaultMode) def get_elements(self): cfarray = c_void_p(iokit.IOHIDDeviceCopyMatchingElements(self.deviceRef, None, 0)) self.elements = cfarray_to_list(cfarray) cf.CFRelease(cfarray) # Page and usage IDs are from the HID usage tables located at # http://www.usb.org/developers/devclass_docs/Hut1_12.pdf def conforms_to(self, page, usage): return bool(iokit.IOHIDDeviceConformsTo(self.deviceRef, page, usage)) def is_pointer(self): return self.conforms_to(0x01, 0x01) def is_mouse(self): return self.conforms_to(0x01, 0x02) def is_joystick(self): return self.conforms_to(0x01, 0x04) def is_gamepad(self): return self.conforms_to(0x01, 0x05) def is_keyboard(self): return self.conforms_to(0x01, 0x06) def is_keypad(self): return self.conforms_to(0x01, 0x07) def is_multi_axis(self): return self.conforms_to(0x01, 0x08) def py_removal_callback(self, context, result, sender): self = _device_lookup[sender] # avoid wonky python context issues # Dispatch removal message to all observers. for x in self.removal_observers: if hasattr(x, 'device_removed'): x.device_removed(self) # Remove self from device lookup table. del _device_lookup[sender] # Remove device elements from lookup table. for key, value in _element_lookup.items(): if value in self.elements: del _element_lookup[key] def register_removal_callback(self): self.removal_callback = HIDDeviceCallback(self.py_removal_callback) iokit.IOHIDDeviceRegisterRemovalCallback( self.deviceRef, self.removal_callback, None) def add_removal_observer(self, observer): self.removal_observers.add(observer) def py_value_callback(self, context, result, sender, value): v = HIDValue(c_void_p(value)) # Dispatch value changed message to all observers. for x in self.value_observers: if hasattr(x, 'device_value_changed'): x.device_value_changed(self, v) def register_input_value_callback(self): self.value_callback = HIDDeviceValueCallback(self.py_value_callback) iokit.IOHIDDeviceRegisterInputValueCallback( self.deviceRef, self.value_callback, None) def add_value_observer(self, observer): self.value_observers.add(observer) def get_value(self, element): # If the device is not open, then returns None valueRef = c_void_p() iokit.IOHIDDeviceGetValue(self.deviceRef, element.elementRef, byref(valueRef)) if valueRef: return HIDValue(valueRef) else: return None class HIDDeviceElement: @classmethod def get_element(cls, elementRef): # elementRef is a c_void_p pointing to an IOHIDDeviceElementRef if elementRef.value in _element_lookup: return _element_lookup[elementRef.value] else: element = HIDDeviceElement(elementRef) return element def __init__(self, elementRef): # Check that we've been passed a valid IOHIDElement. assert(elementRef) assert(cf.CFGetTypeID(elementRef) == iokit.IOHIDElementGetTypeID()) _element_lookup[elementRef.value] = self self.elementRef = elementRef # Set element properties as attributes. self.cookie = iokit.IOHIDElementGetCookie(elementRef) self.type = iokit.IOHIDElementGetType(elementRef) if self.type == kIOHIDElementTypeCollection: self.collectionType = iokit.IOHIDElementGetCollectionType(elementRef) else: self.collectionType = None self.usagePage = iokit.IOHIDElementGetUsagePage(elementRef) self.usage = iokit.IOHIDElementGetUsage(elementRef) self.isVirtual = bool(iokit.IOHIDElementIsVirtual(elementRef)) self.isRelative = bool(iokit.IOHIDElementIsRelative(elementRef)) self.isWrapping = bool(iokit.IOHIDElementIsWrapping(elementRef)) self.isArray = bool(iokit.IOHIDElementIsArray(elementRef)) self.isNonLinear = bool(iokit.IOHIDElementIsNonLinear(elementRef)) self.hasPreferredState = bool(iokit.IOHIDElementHasPreferredState(elementRef)) self.hasNullState = bool(iokit.IOHIDElementHasNullState(elementRef)) self.name = cftype_to_value(iokit.IOHIDElementGetName(elementRef)) self.reportID = iokit.IOHIDElementGetReportID(elementRef) self.reportSize = iokit.IOHIDElementGetReportSize(elementRef) self.reportCount = iokit.IOHIDElementGetReportCount(elementRef) self.unit = iokit.IOHIDElementGetUnit(elementRef) self.unitExponent = iokit.IOHIDElementGetUnitExponent(elementRef) self.logicalMin = iokit.IOHIDElementGetLogicalMin(elementRef) self.logicalMax = iokit.IOHIDElementGetLogicalMax(elementRef) self.physicalMin = iokit.IOHIDElementGetPhysicalMin(elementRef) self.physicalMax = iokit.IOHIDElementGetPhysicalMax(elementRef) class HIDManager: def __init__(self): # Create the HID Manager. self.managerRef = c_void_p(iokit.IOHIDManagerCreate(None, kIOHIDOptionsTypeNone)) assert(self.managerRef) assert cf.CFGetTypeID(self.managerRef) == iokit.IOHIDManagerGetTypeID() self.schedule_with_run_loop() self.matching_observers = set() self.register_matching_callback() self.get_devices() def get_devices(self): # Tell manager that we are willing to match *any* device. # (Alternatively, we could restrict by device usage, or usage page.) iokit.IOHIDManagerSetDeviceMatching(self.managerRef, None) # Copy the device set and convert it to python. cfset = c_void_p(iokit.IOHIDManagerCopyDevices(self.managerRef)) self.devices = cfset_to_set(cfset) cf.CFRelease(cfset) def open(self): iokit.IOHIDManagerOpen(self.managerRef, kIOHIDOptionsTypeNone) def close(self): iokit.IOHIDManagerClose(self.managerRef, kIOHIDOptionsTypeNone) def schedule_with_run_loop(self): iokit.IOHIDManagerScheduleWithRunLoop( self.managerRef, c_void_p(cf.CFRunLoopGetCurrent()), kCFRunLoopDefaultMode) def unschedule_from_run_loop(self): iokit.IOHIDManagerUnscheduleFromRunLoop( self.managerRef, c_void_p(cf.CFRunLoopGetCurrent()), kCFRunLoopDefaultMode) def py_matching_callback(self, context, result, sender, device): d = HIDDevice.get_device(c_void_p(device)) if d not in self.devices: self.devices.add(d) for x in self.matching_observers: if hasattr(x, 'device_discovered'): x.device_discovered(d) def register_matching_callback(self): self.matching_callback = HIDManagerCallback(self.py_matching_callback) iokit.IOHIDManagerRegisterDeviceMatchingCallback( self.managerRef, self.matching_callback, None) ###################################################################### # Add conversion methods for IOHIDDevices and IOHIDDeviceElements # to the list of known types used by cftype_to_value. known_cftypes[iokit.IOHIDDeviceGetTypeID()] = HIDDevice.get_device known_cftypes[iokit.IOHIDElementGetTypeID()] = HIDDeviceElement.get_element ###################################################################### # Pyglet interface to HID from base import Device, Control, AbsoluteAxis, RelativeAxis, Button from base import Joystick, AppleRemote from base import DeviceExclusiveException _axis_names = { (0x01, 0x30): 'x', (0x01, 0x31): 'y', (0x01, 0x32): 'z', (0x01, 0x33): 'rx', (0x01, 0x34): 'ry', (0x01, 0x35): 'rz', (0x01, 0x38): 'wheel', (0x01, 0x39): 'hat', } _button_names = { (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemSleep): 'sleep', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemWakeUp): 'wakeup', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemAppMenu): 'menu', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenu): 'select', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuRight): 'right', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuLeft): 'left', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuUp): 'up', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuDown): 'down', (kHIDPage_Consumer, kHIDUsage_Csmr_FastForward): 'right_hold', (kHIDPage_Consumer, kHIDUsage_Csmr_Rewind): 'left_hold', (kHIDPage_Consumer, kHIDUsage_Csmr_Menu): 'menu_hold', (0xff01, 0x23): 'select_hold', (kHIDPage_Consumer, kHIDUsage_Csmr_Eject): 'eject', (kHIDPage_Consumer, kHIDUsage_Csmr_Mute): 'mute', (kHIDPage_Consumer, kHIDUsage_Csmr_VolumeIncrement): 'volume_up', (kHIDPage_Consumer, kHIDUsage_Csmr_VolumeDecrement): 'volume_down' } class PygletDevice(Device): def __init__(self, display, device, manager): super(PygletDevice, self).__init__(display, device.product) self.device = device self.device_identifier = self.device.unique_identifier() self.device.add_value_observer(self) self.device.add_removal_observer(self) manager.matching_observers.add(self) self._create_controls() self._is_open = False self._is_exclusive = False def open(self, window=None, exclusive=False): super(PygletDevice, self).open(window, exclusive) self.device.open(exclusive) self.device.schedule_with_run_loop() self._is_open = True self._is_exclusive = exclusive self._set_initial_control_values() def close(self): super(PygletDevice, self).close() self.device.close() self._is_open = False def get_controls(self): return self._controls.values() def device_removed(self, hid_device): # Called by device when it is unplugged. # Set device to None, but Keep self._controls around # in case device is plugged back in. self.device = None def device_discovered(self, hid_device): # Called by HID manager when new device is found. # If our device was disconnected, reconnect when it is plugged back in. if not self.device and self.device_identifier == hid_device.unique_identifier(): self.device = hid_device self.device.add_value_observer(self) self.device.add_removal_observer(self) # Don't need to recreate controls since this is same device. # They are indexed by cookie, which is constant. if self._is_open: self.device.open(self._is_exclusive) self.device.schedule_with_run_loop() def device_value_changed(self, hid_device, hid_value): # Called by device when input value changes. control = self._controls[hid_value.element.cookie] control._set_value(hid_value.intvalue) def _create_controls(self): self._controls = {} for element in self.device.elements: raw_name = element.name or '0x%x:%x' % (element.usagePage, element.usage) if element.type in (kIOHIDElementTypeInput_Misc, kIOHIDElementTypeInput_Axis): name = _axis_names.get((element.usagePage, element.usage)) if element.isRelative: control = RelativeAxis(name, raw_name) else: control = AbsoluteAxis(name, element.logicalMin, element.logicalMax, raw_name) elif element.type == kIOHIDElementTypeInput_Button: name = _button_names.get((element.usagePage, element.usage)) control = Button(name, raw_name) else: continue control._cookie = element.cookie self._controls[control._cookie] = control def _set_initial_control_values(self): # Must be called AFTER the device has been opened. for element in self.device.elements: if element.cookie in self._controls: control = self._controls[element.cookie] hid_value = self.device.get_value(element) if hid_value: control._set_value(hid_value.intvalue) ###################################################################### _manager = HIDManager() def get_devices(display=None): return [ PygletDevice(display, device, _manager) for device in _manager.devices ] def get_joysticks(display=None): return [ Joystick(PygletDevice(display, device, _manager)) for device in _manager.devices if device.is_joystick() or device.is_gamepad() or device.is_multi_axis() ] def get_apple_remote(display=None): for device in _manager.devices: if device.product == 'Apple IR': return AppleRemote(PygletDevice(display, device, _manager))
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes import errno import os import pyglet from pyglet.app.xlib import XlibSelectDevice from base import Device, Control, RelativeAxis, AbsoluteAxis, Button, Joystick from base import DeviceOpenException from evdev_constants import * from evdev_constants import _rel_raw_names, _abs_raw_names, _key_raw_names c = pyglet.lib.load_library('c') _IOC_NRBITS = 8 _IOC_TYPEBITS = 8 _IOC_SIZEBITS = 14 _IOC_DIRBITS = 2 _IOC_NRMASK = ((1 << _IOC_NRBITS)-1) _IOC_TYPEMASK = ((1 << _IOC_TYPEBITS)-1) _IOC_SIZEMASK = ((1 << _IOC_SIZEBITS)-1) _IOC_DIRMASK = ((1 << _IOC_DIRBITS)-1) _IOC_NRSHIFT = 0 _IOC_TYPESHIFT = (_IOC_NRSHIFT+_IOC_NRBITS) _IOC_SIZESHIFT = (_IOC_TYPESHIFT+_IOC_TYPEBITS) _IOC_DIRSHIFT = (_IOC_SIZESHIFT+_IOC_SIZEBITS) _IOC_NONE = 0 _IOC_WRITE = 1 _IOC_READ = 2 def _IOC(dir, type, nr, size): return ((dir << _IOC_DIRSHIFT) | (type << _IOC_TYPESHIFT) | (nr << _IOC_NRSHIFT) | (size << _IOC_SIZESHIFT)) def _IOR(type, nr, struct): request = _IOC(_IOC_READ, ord(type), nr, ctypes.sizeof(struct)) def f(fileno): buffer = struct() if c.ioctl(fileno, request, ctypes.byref(buffer)) < 0: err = ctypes.c_int.in_dll(c, 'errno').value raise OSError(err, errno.errorcode[err]) return buffer return f def _IOR_len(type, nr): def f(fileno, buffer): request = _IOC(_IOC_READ, ord(type), nr, ctypes.sizeof(buffer)) if c.ioctl(fileno, request, ctypes.byref(buffer)) < 0: err = ctypes.c_int.in_dll(c, 'errno').value raise OSError(err, errno.errorcode[err]) return buffer return f def _IOR_str(type, nr): g = _IOR_len(type, nr) def f(fileno, len=256): return g(fileno, ctypes.create_string_buffer(len)).value return f time_t = ctypes.c_long suseconds_t = ctypes.c_long class timeval(ctypes.Structure): _fields_ = ( ('tv_sec', time_t), ('tv_usec', suseconds_t) ) class input_event(ctypes.Structure): _fields_ = ( ('time', timeval), ('type', ctypes.c_uint16), ('code', ctypes.c_uint16), ('value', ctypes.c_int32) ) class input_id(ctypes.Structure): _fields_ = ( ('bustype', ctypes.c_uint16), ('vendor', ctypes.c_uint16), ('product', ctypes.c_uint16), ('version', ctypes.c_uint16), ) class input_absinfo(ctypes.Structure): _fields_ = ( ('value', ctypes.c_int32), ('minimum', ctypes.c_int32), ('maximum', ctypes.c_int32), ('fuzz', ctypes.c_int32), ('flat', ctypes.c_int32), ) EVIOCGVERSION = _IOR('E', 0x01, ctypes.c_int) EVIOCGID = _IOR('E', 0x02, input_id) EVIOCGNAME = _IOR_str('E', 0x06) EVIOCGPHYS = _IOR_str('E', 0x07) EVIOCGUNIQ = _IOR_str('E', 0x08) def EVIOCGBIT(fileno, ev, buffer): return _IOR_len('E', 0x20 + ev)(fileno, buffer) def EVIOCGABS(fileno, abs): buffer = input_absinfo() return _IOR_len('E', 0x40 + abs)(fileno, buffer) def get_set_bits(bytes): bits = set() j = 0 for byte in bytes: for i in range(8): if byte & 1: bits.add(j + i) byte >>= 1 j += 8 return bits _abs_names = { ABS_X: AbsoluteAxis.X, ABS_Y: AbsoluteAxis.Y, ABS_Z: AbsoluteAxis.Z, ABS_RX: AbsoluteAxis.RX, ABS_RY: AbsoluteAxis.RY, ABS_RZ: AbsoluteAxis.RZ, ABS_HAT0X: AbsoluteAxis.HAT_X, ABS_HAT0Y: AbsoluteAxis.HAT_Y, } _rel_names = { REL_X: RelativeAxis.X, REL_Y: RelativeAxis.Y, REL_Z: RelativeAxis.Z, REL_RX: RelativeAxis.RX, REL_RY: RelativeAxis.RY, REL_RZ: RelativeAxis.RZ, REL_WHEEL: RelativeAxis.WHEEL, } def _create_control(fileno, event_type, event_code): if event_type == EV_ABS: raw_name = _abs_raw_names.get(event_code, 'EV_ABS(%x)' % event_code) name = _abs_names.get(event_code) absinfo = EVIOCGABS(fileno, event_code) value = absinfo.value min = absinfo.minimum max = absinfo.maximum control = AbsoluteAxis(name, min, max, raw_name) control._set_value(value) if name == 'hat_y': control.inverted = True elif event_type == EV_REL: raw_name = _rel_raw_names.get(event_code, 'EV_REL(%x)' % event_code) name = _rel_names.get(event_code) # TODO min/max? control = RelativeAxis(name, raw_name) elif event_type == EV_KEY: raw_name = _key_raw_names.get(event_code, 'EV_KEY(%x)' % event_code) name = None control = Button(name, raw_name) else: value = min = max = 0 # TODO return None control._event_type = event_type control._event_code = event_code return control def _create_joystick(device): # Look for something with an ABS X and ABS Y axis, and a joystick 0 button have_x = False have_y = False have_button = False for control in device.controls: if control._event_type == EV_ABS and control._event_code == ABS_X: have_x = True elif control._event_type == EV_ABS and control._event_code == ABS_Y: have_y = True elif control._event_type == EV_KEY and \ control._event_code == BTN_JOYSTICK: have_button = True if not (have_x and have_y and have_button): return return Joystick(device) event_types = { EV_KEY: KEY_MAX, EV_REL: REL_MAX, EV_ABS: ABS_MAX, EV_MSC: MSC_MAX, EV_LED: LED_MAX, EV_SND: SND_MAX, } class EvdevDevice(XlibSelectDevice, Device): _fileno = None def __init__(self, display, filename): self._filename = filename fileno = os.open(filename, os.O_RDONLY) #event_version = EVIOCGVERSION(fileno).value id = EVIOCGID(fileno) self.id_bustype = id.bustype self.id_vendor = hex(id.vendor) self.id_product = hex(id.product) self.id_version = id.version name = EVIOCGNAME(fileno) try: name = name.decode('utf-8') except UnicodeDecodeError: try: name = name.decode('latin-1') except UnicodeDecodeError: pass try: self.phys = EVIOCGPHYS(fileno) except OSError: self.phys = '' try: self.uniq = EVIOCGUNIQ(fileno) except OSError: self.uniq = '' self.controls = [] self.control_map = {} event_types_bits = (ctypes.c_byte * 4)() EVIOCGBIT(fileno, 0, event_types_bits) for event_type in get_set_bits(event_types_bits): if event_type not in event_types: continue max_code = event_types[event_type] nbytes = max_code // 8 + 1 event_codes_bits = (ctypes.c_byte * nbytes)() EVIOCGBIT(fileno, event_type, event_codes_bits) for event_code in get_set_bits(event_codes_bits): control = _create_control(fileno, event_type, event_code) if control: self.control_map[(event_type, event_code)] = control self.controls.append(control) os.close(fileno) super(EvdevDevice, self).__init__(display, name) def open(self, window=None, exclusive=False): super(EvdevDevice, self).open(window, exclusive) try: self._fileno = os.open(self._filename, os.O_RDONLY | os.O_NONBLOCK) except OSError, e: raise DeviceOpenException(e) pyglet.app.platform_event_loop._select_devices.add(self) def close(self): super(EvdevDevice, self).close() if not self._fileno: return pyglet.app.platform_event_loop._select_devices.remove(self) os.close(self._fileno) self._fileno = None def get_controls(self): return self.controls # XlibSelectDevice interface def fileno(self): return self._fileno def poll(self): # TODO return False def select(self): if not self._fileno: return events = (input_event * 64)() bytes = c.read(self._fileno, events, ctypes.sizeof(events)) if bytes < 0: return n_events = bytes // ctypes.sizeof(input_event) for event in events[:n_events]: try: control = self.control_map[(event.type, event.code)] control._set_value(event.value) except KeyError: pass _devices = {} def get_devices(display=None): base = '/dev/input' for filename in os.listdir(base): if filename.startswith('event'): path = os.path.join(base, filename) if path in _devices: continue try: _devices[path] = EvdevDevice(display, path) except OSError: pass return _devices.values() def get_joysticks(display=None): return filter(None, [_create_joystick(d) for d in get_devices(display)])
Python
#!/usr/bin/python # $Id:$ import ctypes import pyglet from pyglet.input.base import DeviceOpenException from pyglet.input.base import Tablet, TabletCursor, TabletCanvas from pyglet.libs.win32 import libwintab as wintab lib = wintab.lib def wtinfo(category, index, buffer): size = lib.WTInfoW(category, index, None) assert size <= ctypes.sizeof(buffer) lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer def wtinfo_string(category, index): size = lib.WTInfoW(category, index, None) buffer = ctypes.create_unicode_buffer(size) lib.WTInfoW(category, index, buffer) return buffer.value def wtinfo_uint(category, index): buffer = wintab.UINT() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_word(category, index): buffer = wintab.WORD() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_dword(category, index): buffer = wintab.DWORD() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_wtpkt(category, index): buffer = wintab.WTPKT() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_bool(category, index): buffer = wintab.BOOL() lib.WTInfoW(category, index, ctypes.byref(buffer)) return bool(buffer.value) class WintabTablet(Tablet): def __init__(self, index): self._device = wintab.WTI_DEVICES + index self.name = wtinfo_string(self._device, wintab.DVC_NAME).strip() self.id = wtinfo_string(self._device, wintab.DVC_PNPID) hardware = wtinfo_uint(self._device, wintab.DVC_HARDWARE) #phys_cursors = hardware & wintab.HWC_PHYSID_CURSORS n_cursors = wtinfo_uint(self._device, wintab.DVC_NCSRTYPES) first_cursor = wtinfo_uint(self._device, wintab.DVC_FIRSTCSR) self.pressure_axis = wtinfo(self._device, wintab.DVC_NPRESSURE, wintab.AXIS()) self.cursors = [] self._cursor_map = {} for i in range(n_cursors): cursor = WintabTabletCursor(self, i + first_cursor) if not cursor.bogus: self.cursors.append(cursor) self._cursor_map[i + first_cursor] = cursor def open(self, window): return WintabTabletCanvas(self, window) class WintabTabletCanvas(TabletCanvas): def __init__(self, device, window, msg_base=wintab.WT_DEFBASE): super(WintabTabletCanvas, self).__init__(window) self.device = device self.msg_base = msg_base # Just use system context, for similarity w/ os x and xinput. # WTI_DEFCONTEXT detaches mouse from tablet, which is nice, but not # possible on os x afiak. self.context_info = context_info = wintab.LOGCONTEXT() wtinfo(wintab.WTI_DEFSYSCTX, 0, context_info) context_info.lcMsgBase = msg_base context_info.lcOptions |= wintab.CXO_MESSAGES # If you change this, change definition of PACKET also. context_info.lcPktData = ( wintab.PK_CHANGED | wintab.PK_CURSOR | wintab.PK_BUTTONS | wintab.PK_X | wintab.PK_Y | wintab.PK_Z | wintab.PK_NORMAL_PRESSURE | wintab.PK_TANGENT_PRESSURE | wintab.PK_ORIENTATION) context_info.lcPktMode = 0 # All absolute self._context = lib.WTOpenW(window._hwnd, ctypes.byref(context_info), True) if not self._context: raise DeviceOpenException("Couldn't open tablet context") window._event_handlers[msg_base + wintab.WT_PACKET] = \ self._event_wt_packet window._event_handlers[msg_base + wintab.WT_PROXIMITY] = \ self._event_wt_proximity self._current_cursor = None self._pressure_scale = device.pressure_axis.get_scale() self._pressure_bias = device.pressure_axis.get_bias() def close(self): lib.WTClose(self._context) self._context = None del self.window._event_handlers[self.msg_base + wintab.WT_PACKET] del self.window._event_handlers[self.msg_base + wintab.WT_PROXIMITY] def _set_current_cursor(self, cursor_type): if self._current_cursor: self.dispatch_event('on_leave', self._current_cursor) self._current_cursor = self.device._cursor_map.get(cursor_type, None) if self._current_cursor: self.dispatch_event('on_enter', self._current_cursor) @pyglet.window.win32.Win32EventHandler(0) def _event_wt_packet(self, msg, wParam, lParam): if lParam != self._context: return packet = wintab.PACKET() if lib.WTPacket(self._context, wParam, ctypes.byref(packet)) == 0: return if not packet.pkChanged: return window_x, window_y = self.window.get_location() # TODO cache on window window_y = self.window.screen.height - window_y - self.window.height x = packet.pkX - window_x y = packet.pkY - window_y pressure = (packet.pkNormalPressure + self._pressure_bias) * \ self._pressure_scale if self._current_cursor is None: self._set_current_cursor(packet.pkCursor) self.dispatch_event('on_motion', self._current_cursor, x, y, pressure, 0., 0.) print packet.pkButtons @pyglet.window.win32.Win32EventHandler(0) def _event_wt_proximity(self, msg, wParam, lParam): if wParam != self._context: return if not lParam & 0xffff0000: # Not a hardware proximity event return if not lParam & 0xffff: # Going out self.dispatch_event('on_leave', self._current_cursor) # If going in, proximity event will be generated by next event, which # can actually grab a cursor id. self._current_cursor = None class WintabTabletCursor(object): def __init__(self, device, index): self.device = device self._cursor = wintab.WTI_CURSORS + index self.name = wtinfo_string(self._cursor, wintab.CSR_NAME).strip() self.active = wtinfo_bool(self._cursor, wintab.CSR_ACTIVE) pktdata = wtinfo_wtpkt(self._cursor, wintab.CSR_PKTDATA) # A whole bunch of cursors are reported by the driver, but most of # them are hogwash. Make sure a cursor has at least X and Y data # before adding it to the device. self.bogus = not (pktdata & wintab.PK_X and pktdata & wintab.PK_Y) if self.bogus: return self.id = (wtinfo_dword(self._cursor, wintab.CSR_TYPE) << 32) | \ wtinfo_dword(self._cursor, wintab.CSR_PHYSID) def __repr__(self): return 'WintabCursor(%r)' % self.name def get_spec_version(): spec_version = wtinfo_word(wintab.WTI_INTERFACE, wintab.IFC_SPECVERSION) return spec_version def get_interface_name(): interface_name = wtinfo_string(wintab.WTI_INTERFACE, wintab.IFC_WINTABID) return interface_name def get_implementation_version(): impl_version = wtinfo_word(wintab.WTI_INTERFACE, wintab.IFC_IMPLVERSION) return impl_version def get_tablets(display=None): # Require spec version 1.1 or greater if get_spec_version() < 0x101: return [] n_devices = wtinfo_uint(wintab.WTI_INTERFACE, wintab.IFC_NDEVICES) devices = [WintabTablet(i) for i in range(n_devices)] return devices
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import pyglet from pyglet.input.base import \ Tablet, TabletCanvas, TabletCursor, DeviceOpenException from pyglet.input.x11_xinput import \ get_devices, XInputWindowEventDispatcher, DeviceResponder try: from pyglet.libs.x11 import xinput as xi _have_xinput = True except: _have_xinput = False class XInputTablet(Tablet): name = 'XInput Tablet' def __init__(self, cursors): self.cursors = cursors def open(self, window): return XInputTabletCanvas(window, self.cursors) class XInputTabletCanvas(DeviceResponder, TabletCanvas): def __init__(self, window, cursors): super(XInputTabletCanvas, self).__init__(window) self.cursors = cursors dispatcher = XInputWindowEventDispatcher.get_dispatcher(window) self.display = window.display self._open_devices = [] self._cursor_map = {} for cursor in cursors: device = cursor.device device_id = device._device_id self._cursor_map[device_id] = cursor cursor.max_pressure = device.axes[2].max if self.display._display != device.display._display: raise DeviceOpenException('Window and device displays differ') open_device = xi.XOpenDevice(device.display._display, device_id) if not open_device: # Ignore this cursor; fail if no cursors added continue self._open_devices.append(open_device) dispatcher.open_device(device_id, open_device, self) def close(self): for device in self._open_devices: xi.XCloseDevice(self.display._display, device) def _motion(self, e): cursor = self._cursor_map.get(e.deviceid) x = e.x y = self.window.height - e.y pressure = e.axis_data[2] / float(cursor.max_pressure) self.dispatch_event('on_motion', cursor, x, y, pressure, 0.0, 0.0) def _proximity_in(self, e): cursor = self._cursor_map.get(e.deviceid) self.dispatch_event('on_enter', cursor) def _proximity_out(self, e): cursor = self._cursor_map.get(e.deviceid) self.dispatch_event('on_leave', cursor) class XInputTabletCursor(TabletCursor): def __init__(self, device): super(XInputTabletCursor, self).__init__(device.name) self.device = device def get_tablets(display=None): # Each cursor appears as a separate xinput device; find devices that look # like Wacom tablet cursors and amalgamate them into a single tablet. cursors = [] devices = get_devices(display) for device in devices: if device.name in ('stylus', 'cursor', 'eraser') and \ len(device.axes) >= 3: cursors.append(XInputTabletCursor(device)) if cursors: return [XInputTablet(cursors)] return []
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import pyglet from pyglet.input.base import Tablet, TabletCanvas, TabletCursor from pyglet.window.carbon import CarbonEventHandler from pyglet.libs.darwin import * from pyglet.libs.darwin import _oscheck class CarbonTablet(Tablet): name = 'OS X System Tablet' def open(self, window): return CarbonTabletCanvas(window) _carbon_tablet = CarbonTablet() class CarbonTabletCanvas(TabletCanvas): def __init__(self, window): super(CarbonTabletCanvas, self).__init__(window) for funcname in dir(self): func = getattr(self, funcname) if hasattr(func, '_platform_event'): window._install_event_handler(func) self._cursors = {} self._cursor = None def close(self): # XXX TODO remove event handlers. pass def _get_cursor(self, proximity_rec): key = (proximity_rec.vendorID, proximity_rec.tabletID, proximity_rec.pointerID, proximity_rec.deviceID, proximity_rec.systemTabletID, proximity_rec.vendorPointerType, proximity_rec.pointerSerialNumber, proximity_rec.uniqueID, proximity_rec.pointerType) if key in self._cursors: cursor = self._cursors[key] else: self._cursors[key] = cursor = \ CarbonTabletCursor(proximity_rec.pointerType) self._cursor = cursor return cursor @CarbonEventHandler(kEventClassTablet, kEventTabletProximity) @CarbonEventHandler(kEventClassTablet, kEventTabletPoint) @CarbonEventHandler(kEventClassMouse, kEventMouseDragged) @CarbonEventHandler(kEventClassMouse, kEventMouseDown) @CarbonEventHandler(kEventClassMouse, kEventMouseUp) @CarbonEventHandler(kEventClassMouse, kEventMouseMoved) def _tablet_event(self, next_handler, ev, data): '''Process tablet event and return True if some event was processed. Return True if no tablet event found. ''' event_type = ctypes.c_uint32() r = carbon.GetEventParameter(ev, kEventParamTabletEventType, typeUInt32, None, ctypes.sizeof(event_type), None, ctypes.byref(event_type)) if r != noErr: return False if event_type.value == kEventTabletProximity: proximity_rec = TabletProximityRec() _oscheck( carbon.GetEventParameter(ev, kEventParamTabletProximityRec, typeTabletProximityRec, None, ctypes.sizeof(proximity_rec), None, ctypes.byref(proximity_rec)) ) cursor = self._get_cursor(proximity_rec) if proximity_rec.enterProximity: self.dispatch_event('on_enter', cursor) else: self.dispatch_event('on_leave', cursor) elif event_type.value == kEventTabletPoint: point_rec = TabletPointRec() _oscheck( carbon.GetEventParameter(ev, kEventParamTabletPointRec, typeTabletPointRec, None, ctypes.sizeof(point_rec), None, ctypes.byref(point_rec)) ) #x = point_rec.absX #y = point_rec.absY x, y = self.window._get_mouse_position(ev) pressure = point_rec.pressure / float(0xffff) #point_rec.tiltX, #point_rec.tiltY, #point_rec.rotation, #point_rec.tangentialPressure, self.dispatch_event('on_motion', self._cursor, x, y, pressure, 0., 0.) carbon.CallNextEventHandler(next_handler, ev) return noErr class CarbonTabletCursor(TabletCursor): def __init__(self, cursor_type): # First approximation based on my results from a Wacom consumer # tablet if cursor_type == 1: name = 'Stylus' elif cursor_type == 3: name = 'Eraser' super(CarbonTabletCursor, self).__init__(name) def get_tablets(display=None): return [_carbon_tablet]
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import pyglet from pyglet.libs.darwin import carbon, _oscheck, create_cfstring from pyglet.libs.darwin.constants import * from base import Device, Control, AbsoluteAxis, RelativeAxis, Button from base import Joystick, AppleRemote from base import DeviceExclusiveException # non-broken c_void_p void_p = ctypes.POINTER(ctypes.c_int) class CFUUIDBytes(ctypes.Structure): _fields_ = [('byte%d' % i, ctypes.c_uint8) for i in range(16)] mach_port_t = void_p io_iterator_t = void_p kern_return_t = ctypes.c_int IOReturn = ctypes.c_uint CFDictionaryRef = void_p CFMutableDictionaryRef = void_p CFArrayRef = void_p CFStringRef = void_p CFUUIDRef = ctypes.POINTER(CFUUIDBytes) AbsoluteTime = ctypes.c_double HRESULT = ctypes.c_int REFIID = CFUUIDBytes IOHIDElementType = ctypes.c_int kIOHIDElementTypeInput_Misc = 1 kIOHIDElementTypeInput_Button = 2 kIOHIDElementTypeInput_Axis = 3 kIOHIDElementTypeInput_ScanCodes = 4 kIOHIDElementTypeOutput = 129 kIOHIDElementTypeFeature = 257 kIOHIDElementTypeCollection = 513 IOHIDElementCookie = ctypes.c_void_p # Full list in IOHIDUsageTables.h kHIDPage_GenericDesktop = 0x01 kHIDUsage_GD_Joystick = 0x04 kHIDUsage_GD_GamePad = 0x05 kHIDUsage_GD_Keyboard = 0x06 kHIDUsage_GD_Keypad = 0x07 kHIDUsage_GD_MultiAxisController = 0x08 kHIDUsage_GD_SystemAppMenu = 0x86 kHIDUsage_GD_SystemMenu = 0x89 kHIDUsage_GD_SystemMenuRight = 0x8A kHIDUsage_GD_SystemMenuLeft = 0x8B kHIDUsage_GD_SystemMenuUp = 0x8C kHIDUsage_GD_SystemMenuDown = 0x8D kHIDPage_Consumer = 0x0C kHIDUsage_Csmr_Menu = 0x40 kHIDUsage_Csmr_FastForward = 0xB3 kHIDUsage_Csmr_Rewind = 0xB4 MACH_PORT_NULL = 0 kIOHIDDeviceKey = "IOHIDDevice" kIOServicePlane = "IOService" kIOHIDProductIDKey = "ProductID" kCFNumberIntType = 9 kIOHIDOptionsTypeSeizeDevice = 1 kIOReturnExclusiveAccess = 0xe00002c5 carbon.CFUUIDGetConstantUUIDWithBytes.restype = CFUUIDRef kIOHIDDeviceUserClientTypeID = carbon.CFUUIDGetConstantUUIDWithBytes(None, 0xFA, 0x12, 0xFA, 0x38, 0x6F, 0x1A, 0x11, 0xD4, 0xBA, 0x0C, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5) kIOCFPlugInInterfaceID = carbon.CFUUIDGetConstantUUIDWithBytes(None, 0xC2, 0x44, 0xE8, 0x58, 0x10, 0x9C, 0x11, 0xD4, 0x91, 0xD4, 0x00, 0x50, 0xE4, 0xC6, 0x42, 0x6F) kIOHIDDeviceInterfaceID = carbon.CFUUIDGetConstantUUIDWithBytes(None, 0x78, 0xBD, 0x42, 0x0C, 0x6F, 0x14, 0x11, 0xD4, 0x94, 0x74, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5) IOHIDCallbackFunction = ctypes.CFUNCTYPE(None, void_p, IOReturn, ctypes.c_void_p, ctypes.c_void_p) CFRunLoopSourceRef = ctypes.c_void_p class IOHIDEventStruct(ctypes.Structure): _fields_ = ( ('type', IOHIDElementType), ('elementCookie', IOHIDElementCookie), ('value', ctypes.c_int32), ('timestamp', AbsoluteTime), ('longValueSize', ctypes.c_uint32), ('longValue', ctypes.c_void_p) ) Self = ctypes.c_void_p class IUnknown(ctypes.Structure): _fields_ = ( ('_reserved', ctypes.c_void_p), ('QueryInterface', ctypes.CFUNCTYPE(HRESULT, Self, REFIID, ctypes.c_void_p)), ('AddRef', ctypes.CFUNCTYPE(ctypes.c_ulong, Self)), ('Release', ctypes.CFUNCTYPE(ctypes.c_ulong, Self)), ) # Most of these function prototypes are not filled in yet because I haven't # bothered. class IOHIDQueueInterface(ctypes.Structure): _fields_ = IUnknown._fields_ + ( ('createAsyncEventSource', ctypes.CFUNCTYPE(IOReturn, Self, ctypes.POINTER(CFRunLoopSourceRef))), ('getAsyncEventSource', ctypes.c_void_p), ('createAsyncPort', ctypes.c_void_p), ('getAsyncPort', ctypes.c_void_p), ('create', ctypes.CFUNCTYPE(IOReturn, Self, ctypes.c_uint32, ctypes.c_uint32)), ('dispose', ctypes.CFUNCTYPE(IOReturn, Self)), ('addElement', ctypes.CFUNCTYPE(IOReturn, Self, IOHIDElementCookie)), ('removeElement', ctypes.c_void_p), ('hasElement', ctypes.c_void_p), ('start', ctypes.CFUNCTYPE(IOReturn, Self)), ('stop', ctypes.CFUNCTYPE(IOReturn, Self)), ('getNextEvent', ctypes.CFUNCTYPE(IOReturn, Self, ctypes.POINTER(IOHIDEventStruct), AbsoluteTime, ctypes.c_uint32)), ('setEventCallout', ctypes.CFUNCTYPE(IOReturn, Self, IOHIDCallbackFunction, ctypes.c_void_p, ctypes.c_void_p)), ('getEventCallout', ctypes.c_void_p), ) class IOHIDDeviceInterface(ctypes.Structure): _fields_ = IUnknown._fields_ + ( ('createAsyncEventSource', ctypes.c_void_p), ('getAsyncEventSource', ctypes.c_void_p), ('createAsyncPort', ctypes.c_void_p), ('getAsyncPort', ctypes.c_void_p), ('open', ctypes.CFUNCTYPE(IOReturn, Self, ctypes.c_uint32)), ('close', ctypes.CFUNCTYPE(IOReturn, Self)), ('setRemovalCallback', ctypes.c_void_p), ('getElementValue', ctypes.CFUNCTYPE(IOReturn, Self, IOHIDElementCookie, ctypes.POINTER(IOHIDEventStruct))), ('setElementValue', ctypes.c_void_p), ('queryElementValue', ctypes.c_void_p), ('startAllQueues', ctypes.c_void_p), ('stopAllQueues', ctypes.c_void_p), ('allocQueue', ctypes.CFUNCTYPE( ctypes.POINTER(ctypes.POINTER(IOHIDQueueInterface)), Self)), ('allocOutputTransaction', ctypes.c_void_p), # 1.2.1 (10.2.3) ('setReport', ctypes.c_void_p), ('getReport', ctypes.c_void_p), # 1.2.2 (10.3) ('copyMatchingElements', ctypes.CFUNCTYPE(IOReturn, Self, CFDictionaryRef, ctypes.POINTER(CFArrayRef))), ('setInterruptReportHandlerCallback', ctypes.c_void_p), ) def get_master_port(): master_port = mach_port_t() _oscheck( carbon.IOMasterPort(MACH_PORT_NULL, ctypes.byref(master_port)) ) return master_port def get_matching_dictionary(): carbon.IOServiceMatching.restype = CFMutableDictionaryRef matching_dictionary = carbon.IOServiceMatching(kIOHIDDeviceKey) return matching_dictionary def get_matching_services(master_port, matching_dictionary): # Consumes reference to matching_dictionary iterator = io_iterator_t() _oscheck( carbon.IOServiceGetMatchingServices(master_port, matching_dictionary, ctypes.byref(iterator)) ) services = [] while carbon.IOIteratorIsValid(iterator): service = carbon.IOIteratorNext(iterator) if not service: break services.append(service) carbon.IOObjectRelease(iterator) return services def cfstring_to_string(value_string): value_length = carbon.CFStringGetLength(value_string) buffer_length = carbon.CFStringGetMaximumSizeForEncoding( value_length, kCFStringEncodingUTF8) buffer = ctypes.c_buffer(buffer_length + 1) result = carbon.CFStringGetCString(value_string, buffer, len(buffer), kCFStringEncodingUTF8) if not result: return return buffer.value def cfnumber_to_int(value): result = ctypes.c_int() carbon.CFNumberGetValue(value, kCFNumberIntType, ctypes.byref(result)) return result.value def cfboolean_to_bool(value): return bool(carbon.CFBooleanGetValue(value)) def cfvalue_to_value(value): if not value: return None value_type = carbon.CFGetTypeID(value) if value_type == carbon.CFStringGetTypeID(): return cfstring_to_string(value) elif value_type == carbon.CFNumberGetTypeID(): return cfnumber_to_int(value) elif value_type == carbon.CFBooleanGetTypeID(): return cfboolean_to_bool(value) else: return None def get_property_value(properties, key): key_string = create_cfstring(key) value = ctypes.c_void_p() present = carbon.CFDictionaryGetValueIfPresent(properties, key_string, ctypes.byref(value)) carbon.CFRelease(key_string) if not present: return None return value def get_property(properties, key): return cfvalue_to_value(get_property_value(properties, key)) def dump_properties(properties): def func(key, value, context): print '%s = %s' % (cfstring_to_string(key), cfvalue_to_value(value)) CFDictionaryApplierFunction = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) carbon.CFDictionaryApplyFunction(properties, CFDictionaryApplierFunction(func), None) class DarwinHIDDevice(Device): ''' :IVariables: `name` : str `manufacturer` : str ''' def __init__(self, display, generic_device): super(DarwinHIDDevice, self).__init__(display, name=None) self._device = self._get_device_interface(generic_device) properties = CFMutableDictionaryRef() _oscheck( carbon.IORegistryEntryCreateCFProperties(generic_device, ctypes.byref(properties), None, 0) ) self.name = get_property(properties, "Product") self.manufacturer = get_property(properties, "Manufacturer") self.usage_page = get_property(properties, 'PrimaryUsagePage') self.usage = get_property(properties, 'PrimaryUsage') carbon.CFRelease(properties) self._controls = self._init_controls() self._open = False self._queue = None self._queue_depth = 8 # Number of events queue can buffer def _get_device_interface(self, generic_device): plug_in_interface = \ ctypes.POINTER(ctypes.POINTER(IUnknown))() score = ctypes.c_int32() _oscheck( carbon.IOCreatePlugInInterfaceForService( generic_device, kIOHIDDeviceUserClientTypeID, kIOCFPlugInInterfaceID, ctypes.byref(plug_in_interface), ctypes.byref(score)) ) carbon.CFUUIDGetUUIDBytes.restype = CFUUIDBytes hid_device_interface = \ ctypes.POINTER(ctypes.POINTER(IOHIDDeviceInterface))() _oscheck( plug_in_interface.contents.contents.QueryInterface( plug_in_interface, carbon.CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), ctypes.byref(hid_device_interface)) ) plug_in_interface.contents.contents.Release(plug_in_interface) return hid_device_interface def _init_controls(self): elements_array = CFArrayRef() _oscheck( self._device.contents.contents.copyMatchingElements(self._device, None, ctypes.byref(elements_array)) ) self._control_cookies = {} controls = [] n_elements = carbon.CFArrayGetCount(elements_array) for i in range(n_elements): properties = carbon.CFArrayGetValueAtIndex(elements_array, i) control = _create_control(properties) if control: controls.append(control) self._control_cookies[control._cookie] = control carbon.CFRelease(elements_array) return controls def open(self, window=None, exclusive=False): super(DarwinHIDDevice, self).open(window, exclusive) flags = 0 if exclusive: flags |= kIOHIDOptionsTypeSeizeDevice result = self._device.contents.contents.open(self._device, flags) if result == 0: self._open = True elif result == kIOReturnExclusiveAccess: raise DeviceExclusiveException() # Create event queue self._queue = self._device.contents.contents.allocQueue(self._device) _oscheck( self._queue.contents.contents.create(self._queue, 0, self._queue_depth) ) # Add all controls into queue for control in self._controls: r = self._queue.contents.contents.addElement(self._queue, control._cookie, 0) if r != 0: print 'error adding %r' % control self._event_source = CFRunLoopSourceRef() self._queue_callback_func = IOHIDCallbackFunction(self._queue_callback) _oscheck( self._queue.contents.contents.createAsyncEventSource(self._queue, ctypes.byref(self._event_source)) ) _oscheck( self._queue.contents.contents.setEventCallout(self._queue, self._queue_callback_func, None, None) ) event_loop = pyglet.app.platform_event_loop._event_loop carbon.GetCFRunLoopFromEventLoop.restype = void_p run_loop = carbon.GetCFRunLoopFromEventLoop(event_loop) kCFRunLoopDefaultMode = \ CFStringRef.in_dll(carbon, 'kCFRunLoopDefaultMode') carbon.CFRunLoopAddSource(run_loop, self._event_source, kCFRunLoopDefaultMode) _oscheck( self._queue.contents.contents.start(self._queue) ) def close(self): super(DarwinHIDDevice, self).close() if not self._open: return _oscheck( self._queue.contents.contents.stop(self._queue) ) _oscheck( self._queue.contents.contents.dispose(self._queue) ) self._queue.contents.contents.Release(self._queue) self._queue = None _oscheck( self._device.contents.contents.close(self._device) ) self._open = False def get_controls(self): return self._controls def _queue_callback(self, target, result, refcon, sender): if not self._open: return event = IOHIDEventStruct() r = self._queue.contents.contents.getNextEvent(self._queue, ctypes.byref(event), 0, 0) while r == 0: try: control = self._control_cookies[event.elementCookie] control._set_value(event.value) except KeyError: pass r = self._queue.contents.contents.getNextEvent(self._queue, ctypes.byref(event), 0, 0) _axis_names = { (0x01, 0x30): 'x', (0x01, 0x31): 'y', (0x01, 0x32): 'z', (0x01, 0x33): 'rx', (0x01, 0x34): 'ry', (0x01, 0x35): 'rz', (0x01, 0x38): 'wheel', (0x01, 0x39): 'hat', } _button_names = { (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemAppMenu): 'menu', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenu): 'select', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuRight): 'right', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuLeft): 'left', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuUp): 'up', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuDown): 'down', (kHIDPage_Consumer, kHIDUsage_Csmr_FastForward): 'right_hold', (kHIDPage_Consumer, kHIDUsage_Csmr_Rewind): 'left_hold', (kHIDPage_Consumer, kHIDUsage_Csmr_Menu): 'menu_hold', (0xff01, 0x23): 'select_hold', } def _create_control(properties): type = get_property(properties, 'Type') if type not in (kIOHIDElementTypeInput_Misc, kIOHIDElementTypeInput_Axis, kIOHIDElementTypeInput_Button): return cookie = get_property(properties, 'ElementCookie') usage_page = get_property(properties, 'UsagePage') usage = get_property(properties, 'Usage') raw_name = get_property(properties, 'Name') if not raw_name: raw_name = '%d:%d' % (usage_page, usage) if type in (kIOHIDElementTypeInput_Misc, kIOHIDElementTypeInput_Axis): name = _axis_names.get((usage_page, usage)) relative = get_property(properties, 'IsRelative') if relative: control = RelativeAxis(name, raw_name) else: min = get_property(properties, 'Min') max = get_property(properties, 'Max') control = AbsoluteAxis(name, min, max, raw_name) elif type == kIOHIDElementTypeInput_Button: name = _button_names.get((usage_page, usage)) control = Button(name, raw_name) else: return control._cookie = cookie return control def _create_joystick(device): # Ignore desktop devices that are not joysticks, gamepads or m-a controllers if device.usage_page == kHIDPage_GenericDesktop and \ device.usage not in (kHIDUsage_GD_Joystick, kHIDUsage_GD_GamePad, kHIDUsage_GD_MultiAxisController): return # Anything else is interesting enough to be a joystick? return Joystick(device) def get_devices(display=None): services = get_matching_services(get_master_port(), get_matching_dictionary()) return [DarwinHIDDevice(display, service) for service in services] def get_joysticks(display=None): return filter(None, [_create_joystick(device) for device in get_devices(display)]) def get_apple_remote(display=None): for device in get_devices(display): if device.name == 'Apple IR': return AppleRemote(device)
Python
#!/usr/bin/python # $Id:$ import ctypes import pyglet from pyglet.input import base from pyglet.libs import win32 from pyglet.libs.win32 import dinput from pyglet.libs.win32 import _kernel32 # These instance names are not defined anywhere, obtained by experiment. The # GUID names (which seem to be ideally what are needed) are wrong/missing for # most of my devices. _abs_instance_names = { 0: 'x', 1: 'y', 2: 'z', 3: 'rx', 4: 'ry', 5: 'rz', } _rel_instance_names = { 0: 'x', 1: 'y', 2: 'wheel', } _btn_instance_names = {} def _create_control(object_instance): raw_name = object_instance.tszName type = object_instance.dwType instance = dinput.DIDFT_GETINSTANCE(type) if type & dinput.DIDFT_ABSAXIS: name = _abs_instance_names.get(instance) control = base.AbsoluteAxis(name, 0, 0xffff, raw_name) elif type & dinput.DIDFT_RELAXIS: name = _rel_instance_names.get(instance) control = base.RelativeAxis(name, raw_name) elif type & dinput.DIDFT_BUTTON: name = _btn_instance_names.get(instance) control = base.Button(name, raw_name) elif type & dinput.DIDFT_POV: control = base.AbsoluteAxis(base.AbsoluteAxis.HAT, 0, 0xffffffff, raw_name) else: return control._type = object_instance.dwType return control class DirectInputDevice(base.Device): def __init__(self, display, device, device_instance): name = device_instance.tszInstanceName super(DirectInputDevice, self).__init__(display, name) self._type = device_instance.dwDevType & 0xff self._subtype = device_instance.dwDevType & 0xff00 self._device = device self._init_controls() self._set_format() def _init_controls(self): self.controls = [] self._device.EnumObjects( dinput.LPDIENUMDEVICEOBJECTSCALLBACK(self._object_enum), None, dinput.DIDFT_ALL) def _object_enum(self, object_instance, arg): control = _create_control(object_instance.contents) if control: self.controls.append(control) return dinput.DIENUM_CONTINUE def _set_format(self): if not self.controls: return object_formats = (dinput.DIOBJECTDATAFORMAT * len(self.controls))() offset = 0 for object_format, control in zip(object_formats, self.controls): object_format.dwOfs = offset object_format.dwType = control._type offset += 4 format = dinput.DIDATAFORMAT() format.dwSize = ctypes.sizeof(format) format.dwObjSize = ctypes.sizeof(dinput.DIOBJECTDATAFORMAT) format.dwFlags = 0 format.dwDataSize = offset format.dwNumObjs = len(object_formats) format.rgodf = ctypes.cast(ctypes.pointer(object_formats), dinput.LPDIOBJECTDATAFORMAT) self._device.SetDataFormat(format) prop = dinput.DIPROPDWORD() prop.diph.dwSize = ctypes.sizeof(prop) prop.diph.dwHeaderSize = ctypes.sizeof(prop.diph) prop.diph.dwObj = 0 prop.diph.dwHow = dinput.DIPH_DEVICE prop.dwData = 64 * ctypes.sizeof(dinput.DIDATAFORMAT) self._device.SetProperty(dinput.DIPROP_BUFFERSIZE, ctypes.byref(prop.diph)) def open(self, window=None, exclusive=False): if not self.controls: return if window is None: # Pick any open window, or the shadow window if no windows # have been created yet. window = pyglet.gl._shadow_window for window in pyglet.app.windows: break flags = dinput.DISCL_BACKGROUND if exclusive: flags |= dinput.DISCL_EXCLUSIVE else: flags |= dinput.DISCL_NONEXCLUSIVE self._wait_object = _kernel32.CreateEventW(None, False, False, None) self._device.SetEventNotification(self._wait_object) pyglet.app.platform_event_loop.add_wait_object(self._wait_object, self._dispatch_events) self._device.SetCooperativeLevel(window._hwnd, flags) self._device.Acquire() def close(self): if not self.controls: return pyglet.app.platform_event_loop.remove_wait_object(self._wait_object) self._device.Unacquire() self._device.SetEventNotification(None) _kernel32.CloseHandle(self._wait_object) def get_controls(self): return self.controls def _dispatch_events(self): if not self.controls: return events = (dinput.DIDEVICEOBJECTDATA * 64)() n_events = win32.DWORD(len(events)) self._device.GetDeviceData(ctypes.sizeof(dinput.DIDEVICEOBJECTDATA), ctypes.cast(ctypes.pointer(events), dinput.LPDIDEVICEOBJECTDATA), ctypes.byref(n_events), 0) for event in events[:n_events.value]: index = event.dwOfs // 4 self.controls[index]._set_value(event.dwData) _i_dinput = None def _init_directinput(): global _i_dinput if _i_dinput: return _i_dinput = dinput.IDirectInput8() module = _kernel32.GetModuleHandleW(None) dinput.DirectInput8Create(module, dinput.DIRECTINPUT_VERSION, dinput.IID_IDirectInput8W, ctypes.byref(_i_dinput), None) def get_devices(display=None): _init_directinput() _devices = [] def _device_enum(device_instance, arg): device = dinput.IDirectInputDevice8() _i_dinput.CreateDevice(device_instance.contents.guidInstance, ctypes.byref(device), None) _devices.append(DirectInputDevice(display, device, device_instance.contents)) return dinput.DIENUM_CONTINUE _i_dinput.EnumDevices(dinput.DI8DEVCLASS_ALL, dinput.LPDIENUMDEVICESCALLBACK(_device_enum), None, dinput.DIEDFL_ATTACHEDONLY) return _devices def _create_joystick(device): if device._type in (dinput.DI8DEVTYPE_JOYSTICK, dinput.DI8DEVTYPE_GAMEPAD): return base.Joystick(device) def get_joysticks(display=None): return filter(None, [_create_joystick(d) for d in get_devices(display)])
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes import errno import os import pyglet from pyglet.app.xlib import XlibSelectDevice from base import Device, Control, RelativeAxis, AbsoluteAxis, Button, Joystick from base import DeviceOpenException from evdev_constants import * from evdev_constants import _rel_raw_names, _abs_raw_names, _key_raw_names c = pyglet.lib.load_library('c') _IOC_NRBITS = 8 _IOC_TYPEBITS = 8 _IOC_SIZEBITS = 14 _IOC_DIRBITS = 2 _IOC_NRMASK = ((1 << _IOC_NRBITS)-1) _IOC_TYPEMASK = ((1 << _IOC_TYPEBITS)-1) _IOC_SIZEMASK = ((1 << _IOC_SIZEBITS)-1) _IOC_DIRMASK = ((1 << _IOC_DIRBITS)-1) _IOC_NRSHIFT = 0 _IOC_TYPESHIFT = (_IOC_NRSHIFT+_IOC_NRBITS) _IOC_SIZESHIFT = (_IOC_TYPESHIFT+_IOC_TYPEBITS) _IOC_DIRSHIFT = (_IOC_SIZESHIFT+_IOC_SIZEBITS) _IOC_NONE = 0 _IOC_WRITE = 1 _IOC_READ = 2 def _IOC(dir, type, nr, size): return ((dir << _IOC_DIRSHIFT) | (type << _IOC_TYPESHIFT) | (nr << _IOC_NRSHIFT) | (size << _IOC_SIZESHIFT)) def _IOR(type, nr, struct): request = _IOC(_IOC_READ, ord(type), nr, ctypes.sizeof(struct)) def f(fileno): buffer = struct() if c.ioctl(fileno, request, ctypes.byref(buffer)) < 0: err = ctypes.c_int.in_dll(c, 'errno').value raise OSError(err, errno.errorcode[err]) return buffer return f def _IOR_len(type, nr): def f(fileno, buffer): request = _IOC(_IOC_READ, ord(type), nr, ctypes.sizeof(buffer)) if c.ioctl(fileno, request, ctypes.byref(buffer)) < 0: err = ctypes.c_int.in_dll(c, 'errno').value raise OSError(err, errno.errorcode[err]) return buffer return f def _IOR_str(type, nr): g = _IOR_len(type, nr) def f(fileno, len=256): return g(fileno, ctypes.create_string_buffer(len)).value return f time_t = ctypes.c_long suseconds_t = ctypes.c_long class timeval(ctypes.Structure): _fields_ = ( ('tv_sec', time_t), ('tv_usec', suseconds_t) ) class input_event(ctypes.Structure): _fields_ = ( ('time', timeval), ('type', ctypes.c_uint16), ('code', ctypes.c_uint16), ('value', ctypes.c_int32) ) class input_id(ctypes.Structure): _fields_ = ( ('bustype', ctypes.c_uint16), ('vendor', ctypes.c_uint16), ('product', ctypes.c_uint16), ('version', ctypes.c_uint16), ) class input_absinfo(ctypes.Structure): _fields_ = ( ('value', ctypes.c_int32), ('minimum', ctypes.c_int32), ('maximum', ctypes.c_int32), ('fuzz', ctypes.c_int32), ('flat', ctypes.c_int32), ) EVIOCGVERSION = _IOR('E', 0x01, ctypes.c_int) EVIOCGID = _IOR('E', 0x02, input_id) EVIOCGNAME = _IOR_str('E', 0x06) EVIOCGPHYS = _IOR_str('E', 0x07) EVIOCGUNIQ = _IOR_str('E', 0x08) def EVIOCGBIT(fileno, ev, buffer): return _IOR_len('E', 0x20 + ev)(fileno, buffer) def EVIOCGABS(fileno, abs): buffer = input_absinfo() return _IOR_len('E', 0x40 + abs)(fileno, buffer) def get_set_bits(bytes): bits = set() j = 0 for byte in bytes: for i in range(8): if byte & 1: bits.add(j + i) byte >>= 1 j += 8 return bits _abs_names = { ABS_X: AbsoluteAxis.X, ABS_Y: AbsoluteAxis.Y, ABS_Z: AbsoluteAxis.Z, ABS_RX: AbsoluteAxis.RX, ABS_RY: AbsoluteAxis.RY, ABS_RZ: AbsoluteAxis.RZ, ABS_HAT0X: AbsoluteAxis.HAT_X, ABS_HAT0Y: AbsoluteAxis.HAT_Y, } _rel_names = { REL_X: RelativeAxis.X, REL_Y: RelativeAxis.Y, REL_Z: RelativeAxis.Z, REL_RX: RelativeAxis.RX, REL_RY: RelativeAxis.RY, REL_RZ: RelativeAxis.RZ, REL_WHEEL: RelativeAxis.WHEEL, } def _create_control(fileno, event_type, event_code): if event_type == EV_ABS: raw_name = _abs_raw_names.get(event_code, 'EV_ABS(%x)' % event_code) name = _abs_names.get(event_code) absinfo = EVIOCGABS(fileno, event_code) value = absinfo.value min = absinfo.minimum max = absinfo.maximum control = AbsoluteAxis(name, min, max, raw_name) control._set_value(value) if name == 'hat_y': control.inverted = True elif event_type == EV_REL: raw_name = _rel_raw_names.get(event_code, 'EV_REL(%x)' % event_code) name = _rel_names.get(event_code) # TODO min/max? control = RelativeAxis(name, raw_name) elif event_type == EV_KEY: raw_name = _key_raw_names.get(event_code, 'EV_KEY(%x)' % event_code) name = None control = Button(name, raw_name) else: value = min = max = 0 # TODO return None control._event_type = event_type control._event_code = event_code return control def _create_joystick(device): # Look for something with an ABS X and ABS Y axis, and a joystick 0 button have_x = False have_y = False have_button = False for control in device.controls: if control._event_type == EV_ABS and control._event_code == ABS_X: have_x = True elif control._event_type == EV_ABS and control._event_code == ABS_Y: have_y = True elif control._event_type == EV_KEY and \ control._event_code == BTN_JOYSTICK: have_button = True if not (have_x and have_y and have_button): return return Joystick(device) event_types = { EV_KEY: KEY_MAX, EV_REL: REL_MAX, EV_ABS: ABS_MAX, EV_MSC: MSC_MAX, EV_LED: LED_MAX, EV_SND: SND_MAX, } class EvdevDevice(XlibSelectDevice, Device): _fileno = None def __init__(self, display, filename): self._filename = filename fileno = os.open(filename, os.O_RDONLY) #event_version = EVIOCGVERSION(fileno).value id = EVIOCGID(fileno) self.id_bustype = id.bustype self.id_vendor = hex(id.vendor) self.id_product = hex(id.product) self.id_version = id.version name = EVIOCGNAME(fileno) try: name = name.decode('utf-8') except UnicodeDecodeError: try: name = name.decode('latin-1') except UnicodeDecodeError: pass try: self.phys = EVIOCGPHYS(fileno) except OSError: self.phys = '' try: self.uniq = EVIOCGUNIQ(fileno) except OSError: self.uniq = '' self.controls = [] self.control_map = {} event_types_bits = (ctypes.c_byte * 4)() EVIOCGBIT(fileno, 0, event_types_bits) for event_type in get_set_bits(event_types_bits): if event_type not in event_types: continue max_code = event_types[event_type] nbytes = max_code // 8 + 1 event_codes_bits = (ctypes.c_byte * nbytes)() EVIOCGBIT(fileno, event_type, event_codes_bits) for event_code in get_set_bits(event_codes_bits): control = _create_control(fileno, event_type, event_code) if control: self.control_map[(event_type, event_code)] = control self.controls.append(control) os.close(fileno) super(EvdevDevice, self).__init__(display, name) def open(self, window=None, exclusive=False): super(EvdevDevice, self).open(window, exclusive) try: self._fileno = os.open(self._filename, os.O_RDONLY | os.O_NONBLOCK) except OSError, e: raise DeviceOpenException(e) pyglet.app.platform_event_loop._select_devices.add(self) def close(self): super(EvdevDevice, self).close() if not self._fileno: return pyglet.app.platform_event_loop._select_devices.remove(self) os.close(self._fileno) self._fileno = None def get_controls(self): return self.controls # XlibSelectDevice interface def fileno(self): return self._fileno def poll(self): # TODO return False def select(self): if not self._fileno: return events = (input_event * 64)() bytes = c.read(self._fileno, events, ctypes.sizeof(events)) if bytes < 0: return n_events = bytes // ctypes.sizeof(input_event) for event in events[:n_events]: try: control = self.control_map[(event.type, event.code)] control._set_value(event.value) except KeyError: pass _devices = {} def get_devices(display=None): base = '/dev/input' for filename in os.listdir(base): if filename.startswith('event'): path = os.path.join(base, filename) if path in _devices: continue try: _devices[path] = EvdevDevice(display, path) except OSError: pass return _devices.values() def get_joysticks(display=None): return filter(None, [_create_joystick(d) for d in get_devices(display)])
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import pyglet from pyglet.input.base import \ Tablet, TabletCanvas, TabletCursor, DeviceOpenException from pyglet.input.x11_xinput import \ get_devices, XInputWindowEventDispatcher, DeviceResponder try: from pyglet.libs.x11 import xinput as xi _have_xinput = True except: _have_xinput = False class XInputTablet(Tablet): name = 'XInput Tablet' def __init__(self, cursors): self.cursors = cursors def open(self, window): return XInputTabletCanvas(window, self.cursors) class XInputTabletCanvas(DeviceResponder, TabletCanvas): def __init__(self, window, cursors): super(XInputTabletCanvas, self).__init__(window) self.cursors = cursors dispatcher = XInputWindowEventDispatcher.get_dispatcher(window) self.display = window.display self._open_devices = [] self._cursor_map = {} for cursor in cursors: device = cursor.device device_id = device._device_id self._cursor_map[device_id] = cursor cursor.max_pressure = device.axes[2].max if self.display._display != device.display._display: raise DeviceOpenException('Window and device displays differ') open_device = xi.XOpenDevice(device.display._display, device_id) if not open_device: # Ignore this cursor; fail if no cursors added continue self._open_devices.append(open_device) dispatcher.open_device(device_id, open_device, self) def close(self): for device in self._open_devices: xi.XCloseDevice(self.display._display, device) def _motion(self, e): cursor = self._cursor_map.get(e.deviceid) x = e.x y = self.window.height - e.y pressure = e.axis_data[2] / float(cursor.max_pressure) self.dispatch_event('on_motion', cursor, x, y, pressure, 0.0, 0.0) def _proximity_in(self, e): cursor = self._cursor_map.get(e.deviceid) self.dispatch_event('on_enter', cursor) def _proximity_out(self, e): cursor = self._cursor_map.get(e.deviceid) self.dispatch_event('on_leave', cursor) class XInputTabletCursor(TabletCursor): def __init__(self, device): super(XInputTabletCursor, self).__init__(device.name) self.device = device def get_tablets(display=None): # Each cursor appears as a separate xinput device; find devices that look # like Wacom tablet cursors and amalgamate them into a single tablet. cursors = [] devices = get_devices(display) for device in devices: if device.name in ('stylus', 'cursor', 'eraser') and \ len(device.axes) >= 3: cursors.append(XInputTabletCursor(device)) if cursors: return [XInputTablet(cursors)] return []
Python
#!/usr/bin/env python '''Event constants from /usr/include/linux/input.h ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' EV_SYN = 0x00 EV_KEY = 0x01 EV_REL = 0x02 EV_ABS = 0x03 EV_MSC = 0x04 EV_LED = 0x11 EV_SND = 0x12 EV_REP = 0x14 EV_FF = 0x15 EV_PWR = 0x16 EV_FF_STATUS = 0x17 EV_MAX = 0x1f # Synchronization events. SYN_REPORT = 0 SYN_CONFIG = 1 # Keys and buttons KEY_RESERVED = 0 KEY_ESC = 1 KEY_1 = 2 KEY_2 = 3 KEY_3 = 4 KEY_4 = 5 KEY_5 = 6 KEY_6 = 7 KEY_7 = 8 KEY_8 = 9 KEY_9 = 10 KEY_0 = 11 KEY_MINUS = 12 KEY_EQUAL = 13 KEY_BACKSPACE = 14 KEY_TAB = 15 KEY_Q = 16 KEY_W = 17 KEY_E = 18 KEY_R = 19 KEY_T = 20 KEY_Y = 21 KEY_U = 22 KEY_I = 23 KEY_O = 24 KEY_P = 25 KEY_LEFTBRACE = 26 KEY_RIGHTBRACE = 27 KEY_ENTER = 28 KEY_LEFTCTRL = 29 KEY_A = 30 KEY_S = 31 KEY_D = 32 KEY_F = 33 KEY_G = 34 KEY_H = 35 KEY_J = 36 KEY_K = 37 KEY_L = 38 KEY_SEMICOLON = 39 KEY_APOSTROPHE = 40 KEY_GRAVE = 41 KEY_LEFTSHIFT = 42 KEY_BACKSLASH = 43 KEY_Z = 44 KEY_X = 45 KEY_C = 46 KEY_V = 47 KEY_B = 48 KEY_N = 49 KEY_M = 50 KEY_COMMA = 51 KEY_DOT = 52 KEY_SLASH = 53 KEY_RIGHTSHIFT = 54 KEY_KPASTERISK = 55 KEY_LEFTALT = 56 KEY_SPACE = 57 KEY_CAPSLOCK = 58 KEY_F1 = 59 KEY_F2 = 60 KEY_F3 = 61 KEY_F4 = 62 KEY_F5 = 63 KEY_F6 = 64 KEY_F7 = 65 KEY_F8 = 66 KEY_F9 = 67 KEY_F10 = 68 KEY_NUMLOCK = 69 KEY_SCROLLLOCK = 70 KEY_KP7 = 71 KEY_KP8 = 72 KEY_KP9 = 73 KEY_KPMINUS = 74 KEY_KP4 = 75 KEY_KP5 = 76 KEY_KP6 = 77 KEY_KPPLUS = 78 KEY_KP1 = 79 KEY_KP2 = 80 KEY_KP3 = 81 KEY_KP0 = 82 KEY_KPDOT = 83 KEY_ZENKAKUHANKAKU = 85 KEY_102ND = 86 KEY_F11 = 87 KEY_F12 = 88 KEY_RO = 89 KEY_KATAKANA = 90 KEY_HIRAGANA = 91 KEY_HENKAN = 92 KEY_KATAKANAHIRAGANA = 93 KEY_MUHENKAN = 94 KEY_KPJPCOMMA = 95 KEY_KPENTER = 96 KEY_RIGHTCTRL = 97 KEY_KPSLASH = 98 KEY_SYSRQ = 99 KEY_RIGHTALT = 100 KEY_LINEFEED = 101 KEY_HOME = 102 KEY_UP = 103 KEY_PAGEUP = 104 KEY_LEFT = 105 KEY_RIGHT = 106 KEY_END = 107 KEY_DOWN = 108 KEY_PAGEDOWN = 109 KEY_INSERT = 110 KEY_DELETE = 111 KEY_MACRO = 112 KEY_MUTE = 113 KEY_VOLUMEDOWN = 114 KEY_VOLUMEUP = 115 KEY_POWER = 116 KEY_KPEQUAL = 117 KEY_KPPLUSMINUS = 118 KEY_PAUSE = 119 KEY_KPCOMMA = 121 KEY_HANGUEL = 122 KEY_HANJA = 123 KEY_YEN = 124 KEY_LEFTMETA = 125 KEY_RIGHTMETA = 126 KEY_COMPOSE = 127 KEY_STOP = 128 KEY_AGAIN = 129 KEY_PROPS = 130 KEY_UNDO = 131 KEY_FRONT = 132 KEY_COPY = 133 KEY_OPEN = 134 KEY_PASTE = 135 KEY_FIND = 136 KEY_CUT = 137 KEY_HELP = 138 KEY_MENU = 139 KEY_CALC = 140 KEY_SETUP = 141 KEY_SLEEP = 142 KEY_WAKEUP = 143 KEY_FILE = 144 KEY_SENDFILE = 145 KEY_DELETEFILE = 146 KEY_XFER = 147 KEY_PROG1 = 148 KEY_PROG2 = 149 KEY_WWW = 150 KEY_MSDOS = 151 KEY_COFFEE = 152 KEY_DIRECTION = 153 KEY_CYCLEWINDOWS = 154 KEY_MAIL = 155 KEY_BOOKMARKS = 156 KEY_COMPUTER = 157 KEY_BACK = 158 KEY_FORWARD = 159 KEY_CLOSECD = 160 KEY_EJECTCD = 161 KEY_EJECTCLOSECD = 162 KEY_NEXTSONG = 163 KEY_PLAYPAUSE = 164 KEY_PREVIOUSSONG = 165 KEY_STOPCD = 166 KEY_RECORD = 167 KEY_REWIND = 168 KEY_PHONE = 169 KEY_ISO = 170 KEY_CONFIG = 171 KEY_HOMEPAGE = 172 KEY_REFRESH = 173 KEY_EXIT = 174 KEY_MOVE = 175 KEY_EDIT = 176 KEY_SCROLLUP = 177 KEY_SCROLLDOWN = 178 KEY_KPLEFTPAREN = 179 KEY_KPRIGHTPAREN = 180 KEY_F13 = 183 KEY_F14 = 184 KEY_F15 = 185 KEY_F16 = 186 KEY_F17 = 187 KEY_F18 = 188 KEY_F19 = 189 KEY_F20 = 190 KEY_F21 = 191 KEY_F22 = 192 KEY_F23 = 193 KEY_F24 = 194 KEY_PLAYCD = 200 KEY_PAUSECD = 201 KEY_PROG3 = 202 KEY_PROG4 = 203 KEY_SUSPEND = 205 KEY_CLOSE = 206 KEY_PLAY = 207 KEY_FASTFORWARD = 208 KEY_BASSBOOST = 209 KEY_PRINT = 210 KEY_HP = 211 KEY_CAMERA = 212 KEY_SOUND = 213 KEY_QUESTION = 214 KEY_EMAIL = 215 KEY_CHAT = 216 KEY_SEARCH = 217 KEY_CONNECT = 218 KEY_FINANCE = 219 KEY_SPORT = 220 KEY_SHOP = 221 KEY_ALTERASE = 222 KEY_CANCEL = 223 KEY_BRIGHTNESSDOWN = 224 KEY_BRIGHTNESSUP = 225 KEY_MEDIA = 226 KEY_UNKNOWN = 240 BTN_MISC = 0x100 BTN_0 = 0x100 BTN_1 = 0x101 BTN_2 = 0x102 BTN_3 = 0x103 BTN_4 = 0x104 BTN_5 = 0x105 BTN_6 = 0x106 BTN_7 = 0x107 BTN_8 = 0x108 BTN_9 = 0x109 BTN_MOUSE = 0x110 BTN_LEFT = 0x110 BTN_RIGHT = 0x111 BTN_MIDDLE = 0x112 BTN_SIDE = 0x113 BTN_EXTRA = 0x114 BTN_FORWARD = 0x115 BTN_BACK = 0x116 BTN_TASK = 0x117 BTN_JOYSTICK = 0x120 BTN_TRIGGER = 0x120 BTN_THUMB = 0x121 BTN_THUMB2 = 0x122 BTN_TOP = 0x123 BTN_TOP2 = 0x124 BTN_PINKIE = 0x125 BTN_BASE = 0x126 BTN_BASE2 = 0x127 BTN_BASE3 = 0x128 BTN_BASE4 = 0x129 BTN_BASE5 = 0x12a BTN_BASE6 = 0x12b BTN_DEAD = 0x12f BTN_GAMEPAD = 0x130 BTN_A = 0x130 BTN_B = 0x131 BTN_C = 0x132 BTN_X = 0x133 BTN_Y = 0x134 BTN_Z = 0x135 BTN_TL = 0x136 BTN_TR = 0x137 BTN_TL2 = 0x138 BTN_TR2 = 0x139 BTN_SELECT = 0x13a BTN_START = 0x13b BTN_MODE = 0x13c BTN_THUMBL = 0x13d BTN_THUMBR = 0x13e BTN_DIGI = 0x140 BTN_TOOL_PEN = 0x140 BTN_TOOL_RUBBER = 0x141 BTN_TOOL_BRUSH = 0x142 BTN_TOOL_PENCIL = 0x143 BTN_TOOL_AIRBRUSH = 0x144 BTN_TOOL_FINGER = 0x145 BTN_TOOL_MOUSE = 0x146 BTN_TOOL_LENS = 0x147 BTN_TOUCH = 0x14a BTN_STYLUS = 0x14b BTN_STYLUS2 = 0x14c BTN_TOOL_DOUBLETAP = 0x14d BTN_TOOL_TRIPLETAP = 0x14e BTN_WHEEL = 0x150 BTN_GEAR_DOWN = 0x150 BTN_GEAR_UP = 0x151 KEY_OK = 0x160 KEY_SELECT = 0x161 KEY_GOTO = 0x162 KEY_CLEAR = 0x163 KEY_POWER2 = 0x164 KEY_OPTION = 0x165 KEY_INFO = 0x166 KEY_TIME = 0x167 KEY_VENDOR = 0x168 KEY_ARCHIVE = 0x169 KEY_PROGRAM = 0x16a KEY_CHANNEL = 0x16b KEY_FAVORITES = 0x16c KEY_EPG = 0x16d KEY_PVR = 0x16e KEY_MHP = 0x16f KEY_LANGUAGE = 0x170 KEY_TITLE = 0x171 KEY_SUBTITLE = 0x172 KEY_ANGLE = 0x173 KEY_ZOOM = 0x174 KEY_MODE = 0x175 KEY_KEYBOARD = 0x176 KEY_SCREEN = 0x177 KEY_PC = 0x178 KEY_TV = 0x179 KEY_TV2 = 0x17a KEY_VCR = 0x17b KEY_VCR2 = 0x17c KEY_SAT = 0x17d KEY_SAT2 = 0x17e KEY_CD = 0x17f KEY_TAPE = 0x180 KEY_RADIO = 0x181 KEY_TUNER = 0x182 KEY_PLAYER = 0x183 KEY_TEXT = 0x184 KEY_DVD = 0x185 KEY_AUX = 0x186 KEY_MP3 = 0x187 KEY_AUDIO = 0x188 KEY_VIDEO = 0x189 KEY_DIRECTORY = 0x18a KEY_LIST = 0x18b KEY_MEMO = 0x18c KEY_CALENDAR = 0x18d KEY_RED = 0x18e KEY_GREEN = 0x18f KEY_YELLOW = 0x190 KEY_BLUE = 0x191 KEY_CHANNELUP = 0x192 KEY_CHANNELDOWN = 0x193 KEY_FIRST = 0x194 KEY_LAST = 0x195 KEY_AB = 0x196 KEY_NEXT = 0x197 KEY_RESTART = 0x198 KEY_SLOW = 0x199 KEY_SHUFFLE = 0x19a KEY_BREAK = 0x19b KEY_PREVIOUS = 0x19c KEY_DIGITS = 0x19d KEY_TEEN = 0x19e KEY_TWEN = 0x19f KEY_DEL_EOL = 0x1c0 KEY_DEL_EOS = 0x1c1 KEY_INS_LINE = 0x1c2 KEY_DEL_LINE = 0x1c3 KEY_FN = 0x1d0 KEY_FN_ESC = 0x1d1 KEY_FN_F1 = 0x1d2 KEY_FN_F2 = 0x1d3 KEY_FN_F3 = 0x1d4 KEY_FN_F4 = 0x1d5 KEY_FN_F5 = 0x1d6 KEY_FN_F6 = 0x1d7 KEY_FN_F7 = 0x1d8 KEY_FN_F8 = 0x1d9 KEY_FN_F9 = 0x1da KEY_FN_F10 = 0x1db KEY_FN_F11 = 0x1dc KEY_FN_F12 = 0x1dd KEY_FN_1 = 0x1de KEY_FN_2 = 0x1df KEY_FN_D = 0x1e0 KEY_FN_E = 0x1e1 KEY_FN_F = 0x1e2 KEY_FN_S = 0x1e3 KEY_FN_B = 0x1e4 KEY_MAX = 0x1ff # Relative axes REL_X = 0x00 REL_Y = 0x01 REL_Z = 0x02 REL_RX = 0x03 REL_RY = 0x04 REL_RZ = 0x05 REL_HWHEEL = 0x06 REL_DIAL = 0x07 REL_WHEEL = 0x08 REL_MISC = 0x09 REL_MAX = 0x0f # Absolute axes ABS_X = 0x00 ABS_Y = 0x01 ABS_Z = 0x02 ABS_RX = 0x03 ABS_RY = 0x04 ABS_RZ = 0x05 ABS_THROTTLE = 0x06 ABS_RUDDER = 0x07 ABS_WHEEL = 0x08 ABS_GAS = 0x09 ABS_BRAKE = 0x0a ABS_HAT0X = 0x10 ABS_HAT0Y = 0x11 ABS_HAT1X = 0x12 ABS_HAT1Y = 0x13 ABS_HAT2X = 0x14 ABS_HAT2Y = 0x15 ABS_HAT3X = 0x16 ABS_HAT3Y = 0x17 ABS_PRESSURE = 0x18 ABS_DISTANCE = 0x19 ABS_TILT_X = 0x1a ABS_TILT_Y = 0x1b ABS_TOOL_WIDTH = 0x1c ABS_VOLUME = 0x20 ABS_MISC = 0x28 ABS_MAX = 0x3f # Misc events MSC_SERIAL = 0x00 MSC_PULSELED = 0x01 MSC_GESTURE = 0x02 MSC_RAW = 0x03 MSC_SCAN = 0x04 MSC_MAX = 0x07 # LEDs LED_NUML = 0x00 LED_CAPSL = 0x01 LED_SCROLLL = 0x02 LED_COMPOSE = 0x03 LED_KANA = 0x04 LED_SLEEP = 0x05 LED_SUSPEND = 0x06 LED_MUTE = 0x07 LED_MISC = 0x08 LED_MAIL = 0x09 LED_CHARGING = 0x0a LED_MAX = 0x0f # Autorepeat values REP_DELAY = 0x00 REP_PERIOD = 0x01 REP_MAX = 0x01 # Sounds SND_CLICK = 0x00 SND_BELL = 0x01 SND_TONE = 0x02 SND_MAX = 0x07 # IDs. ID_BUS = 0 ID_VENDOR = 1 ID_PRODUCT = 2 ID_VERSION = 3 BUS_PCI = 0x01 BUS_ISAPNP = 0x02 BUS_USB = 0x03 BUS_HIL = 0x04 BUS_BLUETOOTH = 0x05 BUS_ISA = 0x10 BUS_I8042 = 0x11 BUS_XTKBD = 0x12 BUS_RS232 = 0x13 BUS_GAMEPORT = 0x14 BUS_PARPORT = 0x15 BUS_AMIGA = 0x16 BUS_ADB = 0x17 BUS_I2C = 0x18 BUS_HOST = 0x19 # Values describing the status of an effect FF_STATUS_STOPPED = 0x00 FF_STATUS_PLAYING = 0x01 FF_STATUS_MAX = 0x01 _rel_raw_names = {} _abs_raw_names = {} _key_raw_names = {} for _name, _val in locals().items(): if _name.startswith('REL_'): _rel_raw_names[_val] = _name elif _name.startswith('ABS_'): _abs_raw_names[_val] = _name elif _name.startswith('KEY_') or _name.startswith('BTN_'): _key_raw_names[_val] = _name
Python
#!/usr/bin/python # $Id:$ import ctypes import pyglet from pyglet.input.base import DeviceOpenException from pyglet.input.base import Tablet, TabletCursor, TabletCanvas from pyglet.libs.win32 import libwintab as wintab lib = wintab.lib def wtinfo(category, index, buffer): size = lib.WTInfoW(category, index, None) assert size <= ctypes.sizeof(buffer) lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer def wtinfo_string(category, index): size = lib.WTInfoW(category, index, None) buffer = ctypes.create_unicode_buffer(size) lib.WTInfoW(category, index, buffer) return buffer.value def wtinfo_uint(category, index): buffer = wintab.UINT() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_word(category, index): buffer = wintab.WORD() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_dword(category, index): buffer = wintab.DWORD() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_wtpkt(category, index): buffer = wintab.WTPKT() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_bool(category, index): buffer = wintab.BOOL() lib.WTInfoW(category, index, ctypes.byref(buffer)) return bool(buffer.value) class WintabTablet(Tablet): def __init__(self, index): self._device = wintab.WTI_DEVICES + index self.name = wtinfo_string(self._device, wintab.DVC_NAME).strip() self.id = wtinfo_string(self._device, wintab.DVC_PNPID) hardware = wtinfo_uint(self._device, wintab.DVC_HARDWARE) #phys_cursors = hardware & wintab.HWC_PHYSID_CURSORS n_cursors = wtinfo_uint(self._device, wintab.DVC_NCSRTYPES) first_cursor = wtinfo_uint(self._device, wintab.DVC_FIRSTCSR) self.pressure_axis = wtinfo(self._device, wintab.DVC_NPRESSURE, wintab.AXIS()) self.cursors = [] self._cursor_map = {} for i in range(n_cursors): cursor = WintabTabletCursor(self, i + first_cursor) if not cursor.bogus: self.cursors.append(cursor) self._cursor_map[i + first_cursor] = cursor def open(self, window): return WintabTabletCanvas(self, window) class WintabTabletCanvas(TabletCanvas): def __init__(self, device, window, msg_base=wintab.WT_DEFBASE): super(WintabTabletCanvas, self).__init__(window) self.device = device self.msg_base = msg_base # Just use system context, for similarity w/ os x and xinput. # WTI_DEFCONTEXT detaches mouse from tablet, which is nice, but not # possible on os x afiak. self.context_info = context_info = wintab.LOGCONTEXT() wtinfo(wintab.WTI_DEFSYSCTX, 0, context_info) context_info.lcMsgBase = msg_base context_info.lcOptions |= wintab.CXO_MESSAGES # If you change this, change definition of PACKET also. context_info.lcPktData = ( wintab.PK_CHANGED | wintab.PK_CURSOR | wintab.PK_BUTTONS | wintab.PK_X | wintab.PK_Y | wintab.PK_Z | wintab.PK_NORMAL_PRESSURE | wintab.PK_TANGENT_PRESSURE | wintab.PK_ORIENTATION) context_info.lcPktMode = 0 # All absolute self._context = lib.WTOpenW(window._hwnd, ctypes.byref(context_info), True) if not self._context: raise DeviceOpenException("Couldn't open tablet context") window._event_handlers[msg_base + wintab.WT_PACKET] = \ self._event_wt_packet window._event_handlers[msg_base + wintab.WT_PROXIMITY] = \ self._event_wt_proximity self._current_cursor = None self._pressure_scale = device.pressure_axis.get_scale() self._pressure_bias = device.pressure_axis.get_bias() def close(self): lib.WTClose(self._context) self._context = None del self.window._event_handlers[self.msg_base + wintab.WT_PACKET] del self.window._event_handlers[self.msg_base + wintab.WT_PROXIMITY] def _set_current_cursor(self, cursor_type): if self._current_cursor: self.dispatch_event('on_leave', self._current_cursor) self._current_cursor = self.device._cursor_map.get(cursor_type, None) if self._current_cursor: self.dispatch_event('on_enter', self._current_cursor) @pyglet.window.win32.Win32EventHandler(0) def _event_wt_packet(self, msg, wParam, lParam): if lParam != self._context: return packet = wintab.PACKET() if lib.WTPacket(self._context, wParam, ctypes.byref(packet)) == 0: return if not packet.pkChanged: return window_x, window_y = self.window.get_location() # TODO cache on window window_y = self.window.screen.height - window_y - self.window.height x = packet.pkX - window_x y = packet.pkY - window_y pressure = (packet.pkNormalPressure + self._pressure_bias) * \ self._pressure_scale if self._current_cursor is None: self._set_current_cursor(packet.pkCursor) self.dispatch_event('on_motion', self._current_cursor, x, y, pressure, 0., 0.) print packet.pkButtons @pyglet.window.win32.Win32EventHandler(0) def _event_wt_proximity(self, msg, wParam, lParam): if wParam != self._context: return if not lParam & 0xffff0000: # Not a hardware proximity event return if not lParam & 0xffff: # Going out self.dispatch_event('on_leave', self._current_cursor) # If going in, proximity event will be generated by next event, which # can actually grab a cursor id. self._current_cursor = None class WintabTabletCursor(object): def __init__(self, device, index): self.device = device self._cursor = wintab.WTI_CURSORS + index self.name = wtinfo_string(self._cursor, wintab.CSR_NAME).strip() self.active = wtinfo_bool(self._cursor, wintab.CSR_ACTIVE) pktdata = wtinfo_wtpkt(self._cursor, wintab.CSR_PKTDATA) # A whole bunch of cursors are reported by the driver, but most of # them are hogwash. Make sure a cursor has at least X and Y data # before adding it to the device. self.bogus = not (pktdata & wintab.PK_X and pktdata & wintab.PK_Y) if self.bogus: return self.id = (wtinfo_dword(self._cursor, wintab.CSR_TYPE) << 32) | \ wtinfo_dword(self._cursor, wintab.CSR_PHYSID) def __repr__(self): return 'WintabCursor(%r)' % self.name def get_spec_version(): spec_version = wtinfo_word(wintab.WTI_INTERFACE, wintab.IFC_SPECVERSION) return spec_version def get_interface_name(): interface_name = wtinfo_string(wintab.WTI_INTERFACE, wintab.IFC_WINTABID) return interface_name def get_implementation_version(): impl_version = wtinfo_word(wintab.WTI_INTERFACE, wintab.IFC_IMPLVERSION) return impl_version def get_tablets(display=None): # Require spec version 1.1 or greater if get_spec_version() < 0x101: return [] n_devices = wtinfo_uint(wintab.WTI_INTERFACE, wintab.IFC_NDEVICES) devices = [WintabTablet(i) for i in range(n_devices)] return devices
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import pyglet from pyglet.input.base import \ Device, DeviceException, DeviceOpenException, \ Control, Button, RelativeAxis, AbsoluteAxis from pyglet.libs.x11 import xlib from pyglet.compat import asstr try: from pyglet.libs.x11 import xinput as xi _have_xinput = True except: _have_xinput = False def ptr_add(ptr, offset): address = ctypes.addressof(ptr.contents) + offset return ctypes.pointer(type(ptr.contents).from_address(address)) class DeviceResponder(object): def _key_press(self, e): pass def _key_release(self, e): pass def _button_press(self, e): pass def _button_release(self, e): pass def _motion(self, e): pass def _proximity_in(self, e): pass def _proximity_out(self, e): pass class XInputDevice(DeviceResponder, Device): def __init__(self, display, device_info): super(XInputDevice, self).__init__(display, asstr(device_info.name)) self._device_id = device_info.id self._device = None # Read device info self.buttons = [] self.keys = [] self.axes = [] ptr = device_info.inputclassinfo for i in range(device_info.num_classes): cp = ctypes.cast(ptr, ctypes.POINTER(xi.XAnyClassInfo)) cls_class = getattr(cp.contents, 'class') if cls_class == xi.KeyClass: cp = ctypes.cast(ptr, ctypes.POINTER(xi.XKeyInfo)) self.min_keycode = cp.contents.min_keycode num_keys = cp.contents.num_keys for i in range(num_keys): self.keys.append(Button('key%d' % i)) elif cls_class == xi.ButtonClass: cp = ctypes.cast(ptr, ctypes.POINTER(xi.XButtonInfo)) num_buttons = cp.contents.num_buttons for i in range(num_buttons): self.buttons.append(Button('button%d' % i)) elif cls_class == xi.ValuatorClass: cp = ctypes.cast(ptr, ctypes.POINTER(xi.XValuatorInfo)) num_axes = cp.contents.num_axes mode = cp.contents.mode axes = ctypes.cast(cp.contents.axes, ctypes.POINTER(xi.XAxisInfo)) for i in range(num_axes): axis = axes[i] if mode == xi.Absolute: self.axes.append(AbsoluteAxis('axis%d' % i, min=axis.min_value, max=axis.max_value)) elif mode == xi.Relative: self.axes.append(RelativeAxis('axis%d' % i)) cls = cp.contents ptr = ptr_add(ptr, cls.length) self.controls = self.buttons + self.keys + self.axes # Can't detect proximity class event without opening device. Just # assume there is the possibility of a control if there are any axes. if self.axes: self.proximity_control = Button('proximity') self.controls.append(self.proximity_control) else: self.proximity_control = None def get_controls(self): return self.controls def open(self, window=None, exclusive=False): # Checks for is_open and raises if already open. # TODO allow opening on multiple windows. super(XInputDevice, self).open(window, exclusive) if window is None: self.is_open = False raise DeviceOpenException('XInput devices require a window') if window.display._display != self.display._display: self.is_open = False raise DeviceOpenException('Window and device displays differ') if exclusive: self.is_open = False raise DeviceOpenException('Cannot open XInput device exclusive') self._device = xi.XOpenDevice(self.display._display, self._device_id) if not self._device: self.is_open = False raise DeviceOpenException('Cannot open device') self._install_events(window) def close(self): super(XInputDevice, self).close() if not self._device: return # TODO: uninstall events xi.XCloseDevice(self.display._display, self._device) def _install_events(self, window): dispatcher = XInputWindowEventDispatcher.get_dispatcher(window) dispatcher.open_device(self._device_id, self._device, self) # DeviceResponder interface def _key_press(self, e): self.keys[e.keycode - self.min_keycode]._set_value(True) def _key_release(self, e): self.keys[e.keycode - self.min_keycode]._set_value(False) def _button_press(self, e): self.buttons[e.button]._set_value(True) def _button_release(self, e): self.buttons[e.button]._set_value(False) def _motion(self, e): for i in range(e.axes_count): self.axes[i]._set_value(e.axis_data[i]) def _proximity_in(self, e): if self.proximity_control: self.proximity_control._set_value(True) def _proximity_out(self, e): if self.proximity_control: self.proximity_control._set_value(False) class XInputWindowEventDispatcher(object): def __init__(self, window): self.window = window self._responders = {} @staticmethod def get_dispatcher(window): try: dispatcher = window.__xinput_window_event_dispatcher except AttributeError: dispatcher = window.__xinput_window_event_dispatcher = \ XInputWindowEventDispatcher(window) return dispatcher def set_responder(self, device_id, responder): self._responders[device_id] = responder def remove_responder(self, device_id): del self._responders[device_id] def open_device(self, device_id, device, responder): self.set_responder(device_id, responder) device = device.contents if not device.num_classes: return # Bind matching extended window events to bound instance methods # on this object. # # This is inspired by test.c of xinput package by Frederic # Lepied available at x.org. # # In C, this stuff is normally handled by the macro DeviceKeyPress and # friends. Since we don't have access to those macros here, we do it # this way. events = [] def add(class_info, event, handler): _type = class_info.event_type_base + event _class = device_id << 8 | _type events.append(_class) self.window._event_handlers[_type] = handler for i in range(device.num_classes): class_info = device.classes[i] if class_info.input_class == xi.KeyClass: add(class_info, xi._deviceKeyPress, self._event_xinput_key_press) add(class_info, xi._deviceKeyRelease, self._event_xinput_key_release) elif class_info.input_class == xi.ButtonClass: add(class_info, xi._deviceButtonPress, self._event_xinput_button_press) add(class_info, xi._deviceButtonRelease, self._event_xinput_button_release) elif class_info.input_class == xi.ValuatorClass: add(class_info, xi._deviceMotionNotify, self._event_xinput_motion) elif class_info.input_class == xi.ProximityClass: add(class_info, xi._proximityIn, self._event_xinput_proximity_in) add(class_info, xi._proximityOut, self._event_xinput_proximity_out) elif class_info.input_class == xi.FeedbackClass: pass elif class_info.input_class == xi.FocusClass: pass elif class_info.input_class == xi.OtherClass: pass array = (xi.XEventClass * len(events))(*events) xi.XSelectExtensionEvent(self.window._x_display, self.window._window, array, len(array)) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_key_press(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceKeyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._key_press(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_key_release(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceKeyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._key_release(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_button_press(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceButtonEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._button_press(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_button_release(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceButtonEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._button_release(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_motion(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceMotionEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._motion(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_proximity_in(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XProximityNotifyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._proximity_in(e) @pyglet.window.xlib.XlibEventHandler(-1) def _event_xinput_proximity_out(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XProximityNotifyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._proximity_out(e) def _check_extension(display): major_opcode = ctypes.c_int() first_event = ctypes.c_int() first_error = ctypes.c_int() xlib.XQueryExtension(display._display, 'XInputExtension', ctypes.byref(major_opcode), ctypes.byref(first_event), ctypes.byref(first_error)) return bool(major_opcode.value) def get_devices(display=None): if display is None: display = pyglet.canvas.get_display() if not _have_xinput or not _check_extension(display): return [] devices = [] count = ctypes.c_int(0) device_list = xi.XListInputDevices(display._display, count) for i in range(count.value): device_info = device_list[i] devices.append(XInputDevice(display, device_info)) xi.XFreeDeviceList(device_list) return devices
Python
#!/usr/bin/env python '''Event constants from /usr/include/linux/input.h ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' EV_SYN = 0x00 EV_KEY = 0x01 EV_REL = 0x02 EV_ABS = 0x03 EV_MSC = 0x04 EV_LED = 0x11 EV_SND = 0x12 EV_REP = 0x14 EV_FF = 0x15 EV_PWR = 0x16 EV_FF_STATUS = 0x17 EV_MAX = 0x1f # Synchronization events. SYN_REPORT = 0 SYN_CONFIG = 1 # Keys and buttons KEY_RESERVED = 0 KEY_ESC = 1 KEY_1 = 2 KEY_2 = 3 KEY_3 = 4 KEY_4 = 5 KEY_5 = 6 KEY_6 = 7 KEY_7 = 8 KEY_8 = 9 KEY_9 = 10 KEY_0 = 11 KEY_MINUS = 12 KEY_EQUAL = 13 KEY_BACKSPACE = 14 KEY_TAB = 15 KEY_Q = 16 KEY_W = 17 KEY_E = 18 KEY_R = 19 KEY_T = 20 KEY_Y = 21 KEY_U = 22 KEY_I = 23 KEY_O = 24 KEY_P = 25 KEY_LEFTBRACE = 26 KEY_RIGHTBRACE = 27 KEY_ENTER = 28 KEY_LEFTCTRL = 29 KEY_A = 30 KEY_S = 31 KEY_D = 32 KEY_F = 33 KEY_G = 34 KEY_H = 35 KEY_J = 36 KEY_K = 37 KEY_L = 38 KEY_SEMICOLON = 39 KEY_APOSTROPHE = 40 KEY_GRAVE = 41 KEY_LEFTSHIFT = 42 KEY_BACKSLASH = 43 KEY_Z = 44 KEY_X = 45 KEY_C = 46 KEY_V = 47 KEY_B = 48 KEY_N = 49 KEY_M = 50 KEY_COMMA = 51 KEY_DOT = 52 KEY_SLASH = 53 KEY_RIGHTSHIFT = 54 KEY_KPASTERISK = 55 KEY_LEFTALT = 56 KEY_SPACE = 57 KEY_CAPSLOCK = 58 KEY_F1 = 59 KEY_F2 = 60 KEY_F3 = 61 KEY_F4 = 62 KEY_F5 = 63 KEY_F6 = 64 KEY_F7 = 65 KEY_F8 = 66 KEY_F9 = 67 KEY_F10 = 68 KEY_NUMLOCK = 69 KEY_SCROLLLOCK = 70 KEY_KP7 = 71 KEY_KP8 = 72 KEY_KP9 = 73 KEY_KPMINUS = 74 KEY_KP4 = 75 KEY_KP5 = 76 KEY_KP6 = 77 KEY_KPPLUS = 78 KEY_KP1 = 79 KEY_KP2 = 80 KEY_KP3 = 81 KEY_KP0 = 82 KEY_KPDOT = 83 KEY_ZENKAKUHANKAKU = 85 KEY_102ND = 86 KEY_F11 = 87 KEY_F12 = 88 KEY_RO = 89 KEY_KATAKANA = 90 KEY_HIRAGANA = 91 KEY_HENKAN = 92 KEY_KATAKANAHIRAGANA = 93 KEY_MUHENKAN = 94 KEY_KPJPCOMMA = 95 KEY_KPENTER = 96 KEY_RIGHTCTRL = 97 KEY_KPSLASH = 98 KEY_SYSRQ = 99 KEY_RIGHTALT = 100 KEY_LINEFEED = 101 KEY_HOME = 102 KEY_UP = 103 KEY_PAGEUP = 104 KEY_LEFT = 105 KEY_RIGHT = 106 KEY_END = 107 KEY_DOWN = 108 KEY_PAGEDOWN = 109 KEY_INSERT = 110 KEY_DELETE = 111 KEY_MACRO = 112 KEY_MUTE = 113 KEY_VOLUMEDOWN = 114 KEY_VOLUMEUP = 115 KEY_POWER = 116 KEY_KPEQUAL = 117 KEY_KPPLUSMINUS = 118 KEY_PAUSE = 119 KEY_KPCOMMA = 121 KEY_HANGUEL = 122 KEY_HANJA = 123 KEY_YEN = 124 KEY_LEFTMETA = 125 KEY_RIGHTMETA = 126 KEY_COMPOSE = 127 KEY_STOP = 128 KEY_AGAIN = 129 KEY_PROPS = 130 KEY_UNDO = 131 KEY_FRONT = 132 KEY_COPY = 133 KEY_OPEN = 134 KEY_PASTE = 135 KEY_FIND = 136 KEY_CUT = 137 KEY_HELP = 138 KEY_MENU = 139 KEY_CALC = 140 KEY_SETUP = 141 KEY_SLEEP = 142 KEY_WAKEUP = 143 KEY_FILE = 144 KEY_SENDFILE = 145 KEY_DELETEFILE = 146 KEY_XFER = 147 KEY_PROG1 = 148 KEY_PROG2 = 149 KEY_WWW = 150 KEY_MSDOS = 151 KEY_COFFEE = 152 KEY_DIRECTION = 153 KEY_CYCLEWINDOWS = 154 KEY_MAIL = 155 KEY_BOOKMARKS = 156 KEY_COMPUTER = 157 KEY_BACK = 158 KEY_FORWARD = 159 KEY_CLOSECD = 160 KEY_EJECTCD = 161 KEY_EJECTCLOSECD = 162 KEY_NEXTSONG = 163 KEY_PLAYPAUSE = 164 KEY_PREVIOUSSONG = 165 KEY_STOPCD = 166 KEY_RECORD = 167 KEY_REWIND = 168 KEY_PHONE = 169 KEY_ISO = 170 KEY_CONFIG = 171 KEY_HOMEPAGE = 172 KEY_REFRESH = 173 KEY_EXIT = 174 KEY_MOVE = 175 KEY_EDIT = 176 KEY_SCROLLUP = 177 KEY_SCROLLDOWN = 178 KEY_KPLEFTPAREN = 179 KEY_KPRIGHTPAREN = 180 KEY_F13 = 183 KEY_F14 = 184 KEY_F15 = 185 KEY_F16 = 186 KEY_F17 = 187 KEY_F18 = 188 KEY_F19 = 189 KEY_F20 = 190 KEY_F21 = 191 KEY_F22 = 192 KEY_F23 = 193 KEY_F24 = 194 KEY_PLAYCD = 200 KEY_PAUSECD = 201 KEY_PROG3 = 202 KEY_PROG4 = 203 KEY_SUSPEND = 205 KEY_CLOSE = 206 KEY_PLAY = 207 KEY_FASTFORWARD = 208 KEY_BASSBOOST = 209 KEY_PRINT = 210 KEY_HP = 211 KEY_CAMERA = 212 KEY_SOUND = 213 KEY_QUESTION = 214 KEY_EMAIL = 215 KEY_CHAT = 216 KEY_SEARCH = 217 KEY_CONNECT = 218 KEY_FINANCE = 219 KEY_SPORT = 220 KEY_SHOP = 221 KEY_ALTERASE = 222 KEY_CANCEL = 223 KEY_BRIGHTNESSDOWN = 224 KEY_BRIGHTNESSUP = 225 KEY_MEDIA = 226 KEY_UNKNOWN = 240 BTN_MISC = 0x100 BTN_0 = 0x100 BTN_1 = 0x101 BTN_2 = 0x102 BTN_3 = 0x103 BTN_4 = 0x104 BTN_5 = 0x105 BTN_6 = 0x106 BTN_7 = 0x107 BTN_8 = 0x108 BTN_9 = 0x109 BTN_MOUSE = 0x110 BTN_LEFT = 0x110 BTN_RIGHT = 0x111 BTN_MIDDLE = 0x112 BTN_SIDE = 0x113 BTN_EXTRA = 0x114 BTN_FORWARD = 0x115 BTN_BACK = 0x116 BTN_TASK = 0x117 BTN_JOYSTICK = 0x120 BTN_TRIGGER = 0x120 BTN_THUMB = 0x121 BTN_THUMB2 = 0x122 BTN_TOP = 0x123 BTN_TOP2 = 0x124 BTN_PINKIE = 0x125 BTN_BASE = 0x126 BTN_BASE2 = 0x127 BTN_BASE3 = 0x128 BTN_BASE4 = 0x129 BTN_BASE5 = 0x12a BTN_BASE6 = 0x12b BTN_DEAD = 0x12f BTN_GAMEPAD = 0x130 BTN_A = 0x130 BTN_B = 0x131 BTN_C = 0x132 BTN_X = 0x133 BTN_Y = 0x134 BTN_Z = 0x135 BTN_TL = 0x136 BTN_TR = 0x137 BTN_TL2 = 0x138 BTN_TR2 = 0x139 BTN_SELECT = 0x13a BTN_START = 0x13b BTN_MODE = 0x13c BTN_THUMBL = 0x13d BTN_THUMBR = 0x13e BTN_DIGI = 0x140 BTN_TOOL_PEN = 0x140 BTN_TOOL_RUBBER = 0x141 BTN_TOOL_BRUSH = 0x142 BTN_TOOL_PENCIL = 0x143 BTN_TOOL_AIRBRUSH = 0x144 BTN_TOOL_FINGER = 0x145 BTN_TOOL_MOUSE = 0x146 BTN_TOOL_LENS = 0x147 BTN_TOUCH = 0x14a BTN_STYLUS = 0x14b BTN_STYLUS2 = 0x14c BTN_TOOL_DOUBLETAP = 0x14d BTN_TOOL_TRIPLETAP = 0x14e BTN_WHEEL = 0x150 BTN_GEAR_DOWN = 0x150 BTN_GEAR_UP = 0x151 KEY_OK = 0x160 KEY_SELECT = 0x161 KEY_GOTO = 0x162 KEY_CLEAR = 0x163 KEY_POWER2 = 0x164 KEY_OPTION = 0x165 KEY_INFO = 0x166 KEY_TIME = 0x167 KEY_VENDOR = 0x168 KEY_ARCHIVE = 0x169 KEY_PROGRAM = 0x16a KEY_CHANNEL = 0x16b KEY_FAVORITES = 0x16c KEY_EPG = 0x16d KEY_PVR = 0x16e KEY_MHP = 0x16f KEY_LANGUAGE = 0x170 KEY_TITLE = 0x171 KEY_SUBTITLE = 0x172 KEY_ANGLE = 0x173 KEY_ZOOM = 0x174 KEY_MODE = 0x175 KEY_KEYBOARD = 0x176 KEY_SCREEN = 0x177 KEY_PC = 0x178 KEY_TV = 0x179 KEY_TV2 = 0x17a KEY_VCR = 0x17b KEY_VCR2 = 0x17c KEY_SAT = 0x17d KEY_SAT2 = 0x17e KEY_CD = 0x17f KEY_TAPE = 0x180 KEY_RADIO = 0x181 KEY_TUNER = 0x182 KEY_PLAYER = 0x183 KEY_TEXT = 0x184 KEY_DVD = 0x185 KEY_AUX = 0x186 KEY_MP3 = 0x187 KEY_AUDIO = 0x188 KEY_VIDEO = 0x189 KEY_DIRECTORY = 0x18a KEY_LIST = 0x18b KEY_MEMO = 0x18c KEY_CALENDAR = 0x18d KEY_RED = 0x18e KEY_GREEN = 0x18f KEY_YELLOW = 0x190 KEY_BLUE = 0x191 KEY_CHANNELUP = 0x192 KEY_CHANNELDOWN = 0x193 KEY_FIRST = 0x194 KEY_LAST = 0x195 KEY_AB = 0x196 KEY_NEXT = 0x197 KEY_RESTART = 0x198 KEY_SLOW = 0x199 KEY_SHUFFLE = 0x19a KEY_BREAK = 0x19b KEY_PREVIOUS = 0x19c KEY_DIGITS = 0x19d KEY_TEEN = 0x19e KEY_TWEN = 0x19f KEY_DEL_EOL = 0x1c0 KEY_DEL_EOS = 0x1c1 KEY_INS_LINE = 0x1c2 KEY_DEL_LINE = 0x1c3 KEY_FN = 0x1d0 KEY_FN_ESC = 0x1d1 KEY_FN_F1 = 0x1d2 KEY_FN_F2 = 0x1d3 KEY_FN_F3 = 0x1d4 KEY_FN_F4 = 0x1d5 KEY_FN_F5 = 0x1d6 KEY_FN_F6 = 0x1d7 KEY_FN_F7 = 0x1d8 KEY_FN_F8 = 0x1d9 KEY_FN_F9 = 0x1da KEY_FN_F10 = 0x1db KEY_FN_F11 = 0x1dc KEY_FN_F12 = 0x1dd KEY_FN_1 = 0x1de KEY_FN_2 = 0x1df KEY_FN_D = 0x1e0 KEY_FN_E = 0x1e1 KEY_FN_F = 0x1e2 KEY_FN_S = 0x1e3 KEY_FN_B = 0x1e4 KEY_MAX = 0x1ff # Relative axes REL_X = 0x00 REL_Y = 0x01 REL_Z = 0x02 REL_RX = 0x03 REL_RY = 0x04 REL_RZ = 0x05 REL_HWHEEL = 0x06 REL_DIAL = 0x07 REL_WHEEL = 0x08 REL_MISC = 0x09 REL_MAX = 0x0f # Absolute axes ABS_X = 0x00 ABS_Y = 0x01 ABS_Z = 0x02 ABS_RX = 0x03 ABS_RY = 0x04 ABS_RZ = 0x05 ABS_THROTTLE = 0x06 ABS_RUDDER = 0x07 ABS_WHEEL = 0x08 ABS_GAS = 0x09 ABS_BRAKE = 0x0a ABS_HAT0X = 0x10 ABS_HAT0Y = 0x11 ABS_HAT1X = 0x12 ABS_HAT1Y = 0x13 ABS_HAT2X = 0x14 ABS_HAT2Y = 0x15 ABS_HAT3X = 0x16 ABS_HAT3Y = 0x17 ABS_PRESSURE = 0x18 ABS_DISTANCE = 0x19 ABS_TILT_X = 0x1a ABS_TILT_Y = 0x1b ABS_TOOL_WIDTH = 0x1c ABS_VOLUME = 0x20 ABS_MISC = 0x28 ABS_MAX = 0x3f # Misc events MSC_SERIAL = 0x00 MSC_PULSELED = 0x01 MSC_GESTURE = 0x02 MSC_RAW = 0x03 MSC_SCAN = 0x04 MSC_MAX = 0x07 # LEDs LED_NUML = 0x00 LED_CAPSL = 0x01 LED_SCROLLL = 0x02 LED_COMPOSE = 0x03 LED_KANA = 0x04 LED_SLEEP = 0x05 LED_SUSPEND = 0x06 LED_MUTE = 0x07 LED_MISC = 0x08 LED_MAIL = 0x09 LED_CHARGING = 0x0a LED_MAX = 0x0f # Autorepeat values REP_DELAY = 0x00 REP_PERIOD = 0x01 REP_MAX = 0x01 # Sounds SND_CLICK = 0x00 SND_BELL = 0x01 SND_TONE = 0x02 SND_MAX = 0x07 # IDs. ID_BUS = 0 ID_VENDOR = 1 ID_PRODUCT = 2 ID_VERSION = 3 BUS_PCI = 0x01 BUS_ISAPNP = 0x02 BUS_USB = 0x03 BUS_HIL = 0x04 BUS_BLUETOOTH = 0x05 BUS_ISA = 0x10 BUS_I8042 = 0x11 BUS_XTKBD = 0x12 BUS_RS232 = 0x13 BUS_GAMEPORT = 0x14 BUS_PARPORT = 0x15 BUS_AMIGA = 0x16 BUS_ADB = 0x17 BUS_I2C = 0x18 BUS_HOST = 0x19 # Values describing the status of an effect FF_STATUS_STOPPED = 0x00 FF_STATUS_PLAYING = 0x01 FF_STATUS_MAX = 0x01 _rel_raw_names = {} _abs_raw_names = {} _key_raw_names = {} for _name, _val in locals().items(): if _name.startswith('REL_'): _rel_raw_names[_val] = _name elif _name.startswith('ABS_'): _abs_raw_names[_val] = _name elif _name.startswith('KEY_') or _name.startswith('BTN_'): _key_raw_names[_val] = _name
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import pyglet from pyglet.libs.darwin import carbon, _oscheck, create_cfstring from pyglet.libs.darwin.constants import * from base import Device, Control, AbsoluteAxis, RelativeAxis, Button from base import Joystick, AppleRemote from base import DeviceExclusiveException # non-broken c_void_p void_p = ctypes.POINTER(ctypes.c_int) class CFUUIDBytes(ctypes.Structure): _fields_ = [('byte%d' % i, ctypes.c_uint8) for i in range(16)] mach_port_t = void_p io_iterator_t = void_p kern_return_t = ctypes.c_int IOReturn = ctypes.c_uint CFDictionaryRef = void_p CFMutableDictionaryRef = void_p CFArrayRef = void_p CFStringRef = void_p CFUUIDRef = ctypes.POINTER(CFUUIDBytes) AbsoluteTime = ctypes.c_double HRESULT = ctypes.c_int REFIID = CFUUIDBytes IOHIDElementType = ctypes.c_int kIOHIDElementTypeInput_Misc = 1 kIOHIDElementTypeInput_Button = 2 kIOHIDElementTypeInput_Axis = 3 kIOHIDElementTypeInput_ScanCodes = 4 kIOHIDElementTypeOutput = 129 kIOHIDElementTypeFeature = 257 kIOHIDElementTypeCollection = 513 IOHIDElementCookie = ctypes.c_void_p # Full list in IOHIDUsageTables.h kHIDPage_GenericDesktop = 0x01 kHIDUsage_GD_Joystick = 0x04 kHIDUsage_GD_GamePad = 0x05 kHIDUsage_GD_Keyboard = 0x06 kHIDUsage_GD_Keypad = 0x07 kHIDUsage_GD_MultiAxisController = 0x08 kHIDUsage_GD_SystemAppMenu = 0x86 kHIDUsage_GD_SystemMenu = 0x89 kHIDUsage_GD_SystemMenuRight = 0x8A kHIDUsage_GD_SystemMenuLeft = 0x8B kHIDUsage_GD_SystemMenuUp = 0x8C kHIDUsage_GD_SystemMenuDown = 0x8D kHIDPage_Consumer = 0x0C kHIDUsage_Csmr_Menu = 0x40 kHIDUsage_Csmr_FastForward = 0xB3 kHIDUsage_Csmr_Rewind = 0xB4 MACH_PORT_NULL = 0 kIOHIDDeviceKey = "IOHIDDevice" kIOServicePlane = "IOService" kIOHIDProductIDKey = "ProductID" kCFNumberIntType = 9 kIOHIDOptionsTypeSeizeDevice = 1 kIOReturnExclusiveAccess = 0xe00002c5 carbon.CFUUIDGetConstantUUIDWithBytes.restype = CFUUIDRef kIOHIDDeviceUserClientTypeID = carbon.CFUUIDGetConstantUUIDWithBytes(None, 0xFA, 0x12, 0xFA, 0x38, 0x6F, 0x1A, 0x11, 0xD4, 0xBA, 0x0C, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5) kIOCFPlugInInterfaceID = carbon.CFUUIDGetConstantUUIDWithBytes(None, 0xC2, 0x44, 0xE8, 0x58, 0x10, 0x9C, 0x11, 0xD4, 0x91, 0xD4, 0x00, 0x50, 0xE4, 0xC6, 0x42, 0x6F) kIOHIDDeviceInterfaceID = carbon.CFUUIDGetConstantUUIDWithBytes(None, 0x78, 0xBD, 0x42, 0x0C, 0x6F, 0x14, 0x11, 0xD4, 0x94, 0x74, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5) IOHIDCallbackFunction = ctypes.CFUNCTYPE(None, void_p, IOReturn, ctypes.c_void_p, ctypes.c_void_p) CFRunLoopSourceRef = ctypes.c_void_p class IOHIDEventStruct(ctypes.Structure): _fields_ = ( ('type', IOHIDElementType), ('elementCookie', IOHIDElementCookie), ('value', ctypes.c_int32), ('timestamp', AbsoluteTime), ('longValueSize', ctypes.c_uint32), ('longValue', ctypes.c_void_p) ) Self = ctypes.c_void_p class IUnknown(ctypes.Structure): _fields_ = ( ('_reserved', ctypes.c_void_p), ('QueryInterface', ctypes.CFUNCTYPE(HRESULT, Self, REFIID, ctypes.c_void_p)), ('AddRef', ctypes.CFUNCTYPE(ctypes.c_ulong, Self)), ('Release', ctypes.CFUNCTYPE(ctypes.c_ulong, Self)), ) # Most of these function prototypes are not filled in yet because I haven't # bothered. class IOHIDQueueInterface(ctypes.Structure): _fields_ = IUnknown._fields_ + ( ('createAsyncEventSource', ctypes.CFUNCTYPE(IOReturn, Self, ctypes.POINTER(CFRunLoopSourceRef))), ('getAsyncEventSource', ctypes.c_void_p), ('createAsyncPort', ctypes.c_void_p), ('getAsyncPort', ctypes.c_void_p), ('create', ctypes.CFUNCTYPE(IOReturn, Self, ctypes.c_uint32, ctypes.c_uint32)), ('dispose', ctypes.CFUNCTYPE(IOReturn, Self)), ('addElement', ctypes.CFUNCTYPE(IOReturn, Self, IOHIDElementCookie)), ('removeElement', ctypes.c_void_p), ('hasElement', ctypes.c_void_p), ('start', ctypes.CFUNCTYPE(IOReturn, Self)), ('stop', ctypes.CFUNCTYPE(IOReturn, Self)), ('getNextEvent', ctypes.CFUNCTYPE(IOReturn, Self, ctypes.POINTER(IOHIDEventStruct), AbsoluteTime, ctypes.c_uint32)), ('setEventCallout', ctypes.CFUNCTYPE(IOReturn, Self, IOHIDCallbackFunction, ctypes.c_void_p, ctypes.c_void_p)), ('getEventCallout', ctypes.c_void_p), ) class IOHIDDeviceInterface(ctypes.Structure): _fields_ = IUnknown._fields_ + ( ('createAsyncEventSource', ctypes.c_void_p), ('getAsyncEventSource', ctypes.c_void_p), ('createAsyncPort', ctypes.c_void_p), ('getAsyncPort', ctypes.c_void_p), ('open', ctypes.CFUNCTYPE(IOReturn, Self, ctypes.c_uint32)), ('close', ctypes.CFUNCTYPE(IOReturn, Self)), ('setRemovalCallback', ctypes.c_void_p), ('getElementValue', ctypes.CFUNCTYPE(IOReturn, Self, IOHIDElementCookie, ctypes.POINTER(IOHIDEventStruct))), ('setElementValue', ctypes.c_void_p), ('queryElementValue', ctypes.c_void_p), ('startAllQueues', ctypes.c_void_p), ('stopAllQueues', ctypes.c_void_p), ('allocQueue', ctypes.CFUNCTYPE( ctypes.POINTER(ctypes.POINTER(IOHIDQueueInterface)), Self)), ('allocOutputTransaction', ctypes.c_void_p), # 1.2.1 (10.2.3) ('setReport', ctypes.c_void_p), ('getReport', ctypes.c_void_p), # 1.2.2 (10.3) ('copyMatchingElements', ctypes.CFUNCTYPE(IOReturn, Self, CFDictionaryRef, ctypes.POINTER(CFArrayRef))), ('setInterruptReportHandlerCallback', ctypes.c_void_p), ) def get_master_port(): master_port = mach_port_t() _oscheck( carbon.IOMasterPort(MACH_PORT_NULL, ctypes.byref(master_port)) ) return master_port def get_matching_dictionary(): carbon.IOServiceMatching.restype = CFMutableDictionaryRef matching_dictionary = carbon.IOServiceMatching(kIOHIDDeviceKey) return matching_dictionary def get_matching_services(master_port, matching_dictionary): # Consumes reference to matching_dictionary iterator = io_iterator_t() _oscheck( carbon.IOServiceGetMatchingServices(master_port, matching_dictionary, ctypes.byref(iterator)) ) services = [] while carbon.IOIteratorIsValid(iterator): service = carbon.IOIteratorNext(iterator) if not service: break services.append(service) carbon.IOObjectRelease(iterator) return services def cfstring_to_string(value_string): value_length = carbon.CFStringGetLength(value_string) buffer_length = carbon.CFStringGetMaximumSizeForEncoding( value_length, kCFStringEncodingUTF8) buffer = ctypes.c_buffer(buffer_length + 1) result = carbon.CFStringGetCString(value_string, buffer, len(buffer), kCFStringEncodingUTF8) if not result: return return buffer.value def cfnumber_to_int(value): result = ctypes.c_int() carbon.CFNumberGetValue(value, kCFNumberIntType, ctypes.byref(result)) return result.value def cfboolean_to_bool(value): return bool(carbon.CFBooleanGetValue(value)) def cfvalue_to_value(value): if not value: return None value_type = carbon.CFGetTypeID(value) if value_type == carbon.CFStringGetTypeID(): return cfstring_to_string(value) elif value_type == carbon.CFNumberGetTypeID(): return cfnumber_to_int(value) elif value_type == carbon.CFBooleanGetTypeID(): return cfboolean_to_bool(value) else: return None def get_property_value(properties, key): key_string = create_cfstring(key) value = ctypes.c_void_p() present = carbon.CFDictionaryGetValueIfPresent(properties, key_string, ctypes.byref(value)) carbon.CFRelease(key_string) if not present: return None return value def get_property(properties, key): return cfvalue_to_value(get_property_value(properties, key)) def dump_properties(properties): def func(key, value, context): print '%s = %s' % (cfstring_to_string(key), cfvalue_to_value(value)) CFDictionaryApplierFunction = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) carbon.CFDictionaryApplyFunction(properties, CFDictionaryApplierFunction(func), None) class DarwinHIDDevice(Device): ''' :IVariables: `name` : str `manufacturer` : str ''' def __init__(self, display, generic_device): super(DarwinHIDDevice, self).__init__(display, name=None) self._device = self._get_device_interface(generic_device) properties = CFMutableDictionaryRef() _oscheck( carbon.IORegistryEntryCreateCFProperties(generic_device, ctypes.byref(properties), None, 0) ) self.name = get_property(properties, "Product") self.manufacturer = get_property(properties, "Manufacturer") self.usage_page = get_property(properties, 'PrimaryUsagePage') self.usage = get_property(properties, 'PrimaryUsage') carbon.CFRelease(properties) self._controls = self._init_controls() self._open = False self._queue = None self._queue_depth = 8 # Number of events queue can buffer def _get_device_interface(self, generic_device): plug_in_interface = \ ctypes.POINTER(ctypes.POINTER(IUnknown))() score = ctypes.c_int32() _oscheck( carbon.IOCreatePlugInInterfaceForService( generic_device, kIOHIDDeviceUserClientTypeID, kIOCFPlugInInterfaceID, ctypes.byref(plug_in_interface), ctypes.byref(score)) ) carbon.CFUUIDGetUUIDBytes.restype = CFUUIDBytes hid_device_interface = \ ctypes.POINTER(ctypes.POINTER(IOHIDDeviceInterface))() _oscheck( plug_in_interface.contents.contents.QueryInterface( plug_in_interface, carbon.CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), ctypes.byref(hid_device_interface)) ) plug_in_interface.contents.contents.Release(plug_in_interface) return hid_device_interface def _init_controls(self): elements_array = CFArrayRef() _oscheck( self._device.contents.contents.copyMatchingElements(self._device, None, ctypes.byref(elements_array)) ) self._control_cookies = {} controls = [] n_elements = carbon.CFArrayGetCount(elements_array) for i in range(n_elements): properties = carbon.CFArrayGetValueAtIndex(elements_array, i) control = _create_control(properties) if control: controls.append(control) self._control_cookies[control._cookie] = control carbon.CFRelease(elements_array) return controls def open(self, window=None, exclusive=False): super(DarwinHIDDevice, self).open(window, exclusive) flags = 0 if exclusive: flags |= kIOHIDOptionsTypeSeizeDevice result = self._device.contents.contents.open(self._device, flags) if result == 0: self._open = True elif result == kIOReturnExclusiveAccess: raise DeviceExclusiveException() # Create event queue self._queue = self._device.contents.contents.allocQueue(self._device) _oscheck( self._queue.contents.contents.create(self._queue, 0, self._queue_depth) ) # Add all controls into queue for control in self._controls: r = self._queue.contents.contents.addElement(self._queue, control._cookie, 0) if r != 0: print 'error adding %r' % control self._event_source = CFRunLoopSourceRef() self._queue_callback_func = IOHIDCallbackFunction(self._queue_callback) _oscheck( self._queue.contents.contents.createAsyncEventSource(self._queue, ctypes.byref(self._event_source)) ) _oscheck( self._queue.contents.contents.setEventCallout(self._queue, self._queue_callback_func, None, None) ) event_loop = pyglet.app.platform_event_loop._event_loop carbon.GetCFRunLoopFromEventLoop.restype = void_p run_loop = carbon.GetCFRunLoopFromEventLoop(event_loop) kCFRunLoopDefaultMode = \ CFStringRef.in_dll(carbon, 'kCFRunLoopDefaultMode') carbon.CFRunLoopAddSource(run_loop, self._event_source, kCFRunLoopDefaultMode) _oscheck( self._queue.contents.contents.start(self._queue) ) def close(self): super(DarwinHIDDevice, self).close() if not self._open: return _oscheck( self._queue.contents.contents.stop(self._queue) ) _oscheck( self._queue.contents.contents.dispose(self._queue) ) self._queue.contents.contents.Release(self._queue) self._queue = None _oscheck( self._device.contents.contents.close(self._device) ) self._open = False def get_controls(self): return self._controls def _queue_callback(self, target, result, refcon, sender): if not self._open: return event = IOHIDEventStruct() r = self._queue.contents.contents.getNextEvent(self._queue, ctypes.byref(event), 0, 0) while r == 0: try: control = self._control_cookies[event.elementCookie] control._set_value(event.value) except KeyError: pass r = self._queue.contents.contents.getNextEvent(self._queue, ctypes.byref(event), 0, 0) _axis_names = { (0x01, 0x30): 'x', (0x01, 0x31): 'y', (0x01, 0x32): 'z', (0x01, 0x33): 'rx', (0x01, 0x34): 'ry', (0x01, 0x35): 'rz', (0x01, 0x38): 'wheel', (0x01, 0x39): 'hat', } _button_names = { (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemAppMenu): 'menu', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenu): 'select', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuRight): 'right', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuLeft): 'left', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuUp): 'up', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuDown): 'down', (kHIDPage_Consumer, kHIDUsage_Csmr_FastForward): 'right_hold', (kHIDPage_Consumer, kHIDUsage_Csmr_Rewind): 'left_hold', (kHIDPage_Consumer, kHIDUsage_Csmr_Menu): 'menu_hold', (0xff01, 0x23): 'select_hold', } def _create_control(properties): type = get_property(properties, 'Type') if type not in (kIOHIDElementTypeInput_Misc, kIOHIDElementTypeInput_Axis, kIOHIDElementTypeInput_Button): return cookie = get_property(properties, 'ElementCookie') usage_page = get_property(properties, 'UsagePage') usage = get_property(properties, 'Usage') raw_name = get_property(properties, 'Name') if not raw_name: raw_name = '%d:%d' % (usage_page, usage) if type in (kIOHIDElementTypeInput_Misc, kIOHIDElementTypeInput_Axis): name = _axis_names.get((usage_page, usage)) relative = get_property(properties, 'IsRelative') if relative: control = RelativeAxis(name, raw_name) else: min = get_property(properties, 'Min') max = get_property(properties, 'Max') control = AbsoluteAxis(name, min, max, raw_name) elif type == kIOHIDElementTypeInput_Button: name = _button_names.get((usage_page, usage)) control = Button(name, raw_name) else: return control._cookie = cookie return control def _create_joystick(device): # Ignore desktop devices that are not joysticks, gamepads or m-a controllers if device.usage_page == kHIDPage_GenericDesktop and \ device.usage not in (kHIDUsage_GD_Joystick, kHIDUsage_GD_GamePad, kHIDUsage_GD_MultiAxisController): return # Anything else is interesting enough to be a joystick? return Joystick(device) def get_devices(display=None): services = get_matching_services(get_master_port(), get_matching_dictionary()) return [DarwinHIDDevice(display, service) for service in services] def get_joysticks(display=None): return filter(None, [_create_joystick(device) for device in get_devices(display)]) def get_apple_remote(display=None): for device in get_devices(display): if device.name == 'Apple IR': return AppleRemote(device)
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Interface classes for `pyglet.input`. :since: pyglet 1.2 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import sys from pyglet.event import EventDispatcher _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc class DeviceException(Exception): pass class DeviceOpenException(DeviceException): pass class DeviceExclusiveException(DeviceException): pass class Device(object): '''Input device. :Ivariables: `display` : `Display` Display this device is connected to. `name` : str Name of the device, as described by the device firmware. `manufacturer` : str Name of the device manufacturer, or ``None`` if the information is not available. ''' def __init__(self, display, name): self.display = display self.name = name self.manufacturer = None # TODO: make private self.is_open = False def open(self, window=None, exclusive=False): '''Open the device to begin receiving input from it. :Parameters: `window` : Window Optional window to associate with the device. The behaviour of this parameter is device and operating system dependant. It can usually be omitted for most devices. `exclusive` : bool If ``True`` the device will be opened exclusively so that no other application can use it. The method will raise `DeviceExclusiveException` if the device cannot be opened this way (for example, because another application has already opened it). ''' if self.is_open: raise DeviceOpenException('Device is already open.') self.is_open = True def close(self): '''Close the device. ''' self.is_open = False def get_controls(self): '''Get a list of controls provided by the device. :rtype: list of `Control` ''' raise NotImplementedError('abstract') def __repr__(self): return '%s(name=%s)' % (self.__class__.__name__, self.name) class Control(EventDispatcher): '''Single value input provided by a device. A control's value can be queried when the device is open. Event handlers can be attached to the control to be called when the value changes. The `min` and `max` properties are provided as advertised by the device; in some cases the control's value will be outside this range. :Ivariables: `name` : str Name of the control, or ``None`` if unknown `raw_name` : str Unmodified name of the control, as presented by the operating system; or ``None`` if unknown. `inverted` : bool If ``True``, the value reported is actually inverted from what the device reported; usually this is to provide consistency across operating systems. ''' _value = None def __init__(self, name, raw_name=None): self.name = name self.raw_name = raw_name self.inverted = False def _get_value(self): return self._value def _set_value(self, value): if value == self._value: return self._value = value self.dispatch_event('on_change', value) value = property(_get_value, doc='''Current value of the control. The range of the value is device-dependent; for absolute controls the range is given by ``min`` and ``max`` (however the value may exceed this range); for relative controls the range is undefined. :type: float''') def __repr__(self): if self.name: return '%s(name=%s, raw_name=%s)' % ( self.__class__.__name__, self.name, self.raw_name) else: return '%s(raw_name=%s)' % (self.__class__.__name__, self.raw_name) if _is_epydoc: def on_change(self, value): '''The value changed. :Parameters: `value` : float Current value of the control. :event: ''' Control.register_event_type('on_change') class RelativeAxis(Control): '''An axis whose value represents a relative change from the previous value. ''' #: Name of the horizontal axis control X = 'x' #: Name of the vertical axis control Y = 'y' #: Name of the Z axis control. Z = 'z' #: Name of the rotational-X axis control RX = 'rx' #: Name of the rotational-Y axis control RY = 'ry' #: Name of the rotational-Z axis control RZ = 'rz' #: Name of the scroll wheel control WHEEL = 'wheel' def _get_value(self): return self._value def _set_value(self, value): self._value = value self.dispatch_event('on_change', value) value = property(_get_value) class AbsoluteAxis(Control): '''An axis whose value represents a physical measurement from the device. The value is advertised to range over ``min`` and ``max``. :Ivariables: `min` : float Minimum advertised value. `max` : float Maximum advertised value. ''' #: Name of the horizontal axis control X = 'x' #: Name of the vertical axis control Y = 'y' #: Name of the Z axis control. Z = 'z' #: Name of the rotational-X axis control RX = 'rx' #: Name of the rotational-Y axis control RY = 'ry' #: Name of the rotational-Z axis control RZ = 'rz' #: Name of the hat (POV) control, when a single control enumerates all of #: the hat's positions. HAT = 'hat' #: Name of the hat's (POV's) horizontal control, when the hat position is #: described by two orthogonal controls. HAT_X = 'hat_x' #: Name of the hat's (POV's) vertical control, when the hat position is #: described by two orthogonal controls. HAT_Y = 'hat_y' def __init__(self, name, min, max, raw_name=None): super(AbsoluteAxis, self).__init__(name, raw_name) self.min = min self.max = max class Button(Control): '''A control whose value is boolean. ''' def _get_value(self): return bool(self._value) def _set_value(self, value): if value == self._value: return self._value = value self.dispatch_event('on_change', bool(value)) if value: self.dispatch_event('on_press') else: self.dispatch_event('on_release') value = property(_get_value) if _is_epydoc: def on_press(self): '''The button was pressed. :event: ''' def on_release(self): '''The button was released. :event: ''' Button.register_event_type('on_press') Button.register_event_type('on_release') class Joystick(EventDispatcher): '''High-level interface for joystick-like devices. This includes analogue and digital joysticks, gamepads, game controllers, and possibly even steering wheels and other input devices. There is unfortunately no way to distinguish between these different device types. To use a joystick, first call `open`, then in your game loop examine the values of `x`, `y`, and so on. These values are normalized to the range [-1.0, 1.0]. To receive events when the value of an axis changes, attach an on_joyaxis_motion event handler to the joystick. The `Joystick` instance, axis name, and current value are passed as parameters to this event. To handle button events, you should attach on_joybutton_press and on_joy_button_release event handlers to the joystick. Both the `Joystick` instance and the index of the changed button are passed as parameters to these events. Alternately, you may attach event handlers to each individual button in `button_controls` to receive on_press or on_release events. To use the hat switch, attach an on_joyhat_motion event handler to the joystick. The handler will be called with both the hat_x and hat_y values whenever the value of the hat switch changes. The device name can be queried to get the name of the joystick. :Ivariables: `device` : `Device` The underlying device used by this joystick interface. `x` : float Current X (horizontal) value ranging from -1.0 (left) to 1.0 (right). `y` : float Current y (vertical) value ranging from -1.0 (top) to 1.0 (bottom). `z` : float Current Z value ranging from -1.0 to 1.0. On joysticks the Z value is usually the throttle control. On game controllers the Z value is usually the secondary thumb vertical axis. `rx` : float Current rotational X value ranging from -1.0 to 1.0. `ry` : float Current rotational Y value ranging from -1.0 to 1.0. `rz` : float Current rotational Z value ranging from -1.0 to 1.0. On joysticks the RZ value is usually the twist of the stick. On game controllers the RZ value is usually the secondary thumb horizontal axis. `hat_x` : int Current hat (POV) horizontal position; one of -1 (left), 0 (centered) or 1 (right). `hat_y` : int Current hat (POV) vertical position; one of -1 (bottom), 0 (centered) or 1 (top). `buttons` : list of bool List of boolean values representing current states of the buttons. These are in order, so that button 1 has value at ``buttons[0]``, and so on. `x_control` : `AbsoluteAxis` Underlying control for `x` value, or ``None`` if not available. `y_control` : `AbsoluteAxis` Underlying control for `y` value, or ``None`` if not available. `z_control` : `AbsoluteAxis` Underlying control for `z` value, or ``None`` if not available. `rx_control` : `AbsoluteAxis` Underlying control for `rx` value, or ``None`` if not available. `ry_control` : `AbsoluteAxis` Underlying control for `ry` value, or ``None`` if not available. `rz_control` : `AbsoluteAxis` Underlying control for `rz` value, or ``None`` if not available. `hat_x_control` : `AbsoluteAxis` Underlying control for `hat_x` value, or ``None`` if not available. `hat_y_control` : `AbsoluteAxis` Underlying control for `hat_y` value, or ``None`` if not available. `button_controls` : list of `Button` Underlying controls for `buttons` values. ''' def __init__(self, device): self.device = device self.x = 0 self.y = 0 self.z = 0 self.rx = 0 self.ry = 0 self.rz = 0 self.hat_x = 0 self.hat_y = 0 self.buttons = [] self.x_control = None self.y_control = None self.z_control = None self.rx_control = None self.ry_control = None self.rz_control = None self.hat_x_control = None self.hat_y_control = None self.button_controls = [] def add_axis(control): name = control.name scale = 2.0 / (control.max - control.min) bias = -1.0 - control.min * scale if control.inverted: scale = -scale bias = -bias setattr(self, name + '_control', control) @control.event def on_change(value): normalized_value = value * scale + bias setattr(self, name, normalized_value) self.dispatch_event('on_joyaxis_motion', self, name, normalized_value) def add_button(control): i = len(self.buttons) self.buttons.append(False) self.button_controls.append(control) @control.event def on_change(value): self.buttons[i] = value @control.event def on_press(): self.dispatch_event('on_joybutton_press', self, i) @control.event def on_release(): self.dispatch_event('on_joybutton_release', self, i) def add_hat(control): # 8-directional hat encoded as a single control (Windows/Mac) self.hat_x_control = control self.hat_y_control = control @control.event def on_change(value): if value & 0xffff == 0xffff: self.hat_x = self.hat_y = 0 else: if control.max > 8: # DirectInput: scale value value //= 0xfff if 0 <= value < 8: self.hat_x, self.hat_y = ( ( 0, 1), ( 1, 1), ( 1, 0), ( 1, -1), ( 0, -1), (-1, -1), (-1, 0), (-1, 1), )[value] else: # Out of range self.hat_x = self.hat_y = 0 self.dispatch_event('on_joyhat_motion', self, self.hat_x, self.hat_y) for control in device.get_controls(): if isinstance(control, AbsoluteAxis): if control.name in ('x', 'y', 'z', 'rx', 'ry', 'rz', 'hat_x', 'hat_y'): add_axis(control) elif control.name == 'hat': add_hat(control) elif isinstance(control, Button): add_button(control) def open(self, window=None, exclusive=False): '''Open the joystick device. See `Device.open`. ''' self.device.open(window, exclusive) def close(self): '''Close the joystick device. See `Device.close`. ''' self.device.close() def on_joyaxis_motion(self, joystick, axis, value): '''The value of a joystick axis changed. :Parameters: `joystick` : `Joystick` The joystick device whose axis changed. `axis` : string The name of the axis that changed. `value` : float The current value of the axis, normalized to [-1, 1]. ''' def on_joybutton_press(self, joystick, button): '''A button on the joystick was pressed. :Parameters: `joystick` : `Joystick` The joystick device whose button was pressed. `button` : int The index (in `button_controls`) of the button that was pressed. ''' def on_joybutton_release(self, joystick, button): '''A button on the joystick was released. :Parameters: `joystick` : `Joystick` The joystick device whose button was released. `button` : int The index (in `button_controls`) of the button that was released. ''' def on_joyhat_motion(self, joystick, hat_x, hat_y): '''The value of the joystick hat switch changed. :Parameters: `joystick` : `Joystick` The joystick device whose hat control changed. `hat_x` : int Current hat (POV) horizontal position; one of -1 (left), 0 (centered) or 1 (right). `hat_y` : int Current hat (POV) vertical position; one of -1 (bottom), 0 (centered) or 1 (top). ''' Joystick.register_event_type('on_joyaxis_motion') Joystick.register_event_type('on_joybutton_press') Joystick.register_event_type('on_joybutton_release') Joystick.register_event_type('on_joyhat_motion') class AppleRemote(EventDispatcher): '''High-level interface for Apple remote control. This interface provides access to the 6 button controls on the remote. Pressing and holding certain buttons on the remote is interpreted as a separate control. :Ivariables: `device` : `Device` The underlying device used by this interface. `left_control` : `Button` Button control for the left (prev) button. `left_hold_control` : `Button` Button control for holding the left button (rewind). `right_control` : `Button` Button control for the right (next) button. `right_hold_control` : `Button` Button control for holding the right button (fast forward). `up_control` : `Button` Button control for the up (volume increase) button. `down_control` : `Button` Button control for the down (volume decrease) button. `select_control` : `Button` Button control for the select (play/pause) button. `select_hold_control` : `Button` Button control for holding the select button. `menu_control` : `Button` Button control for the menu button. `menu_hold_control` : `Button` Button control for holding the menu button. ''' def __init__(self, device): def add_button(control): setattr(self, control.name + '_control', control) @control.event def on_press(): self.dispatch_event('on_button_press', control.name) @control.event def on_release(): self.dispatch_event('on_button_release', control.name) self.device = device for control in device.get_controls(): if control.name in ('left', 'left_hold', 'right', 'right_hold', 'up', 'down', 'menu', 'select', 'menu_hold', 'select_hold'): add_button(control) def open(self, window=None, exclusive=False): '''Open the device. See `Device.open`. ''' self.device.open(window, exclusive) def close(self): '''Close the device. See `Device.close`. ''' self.device.close() def on_button_press(self, button): """A button on the remote was pressed. Only the 'up' and 'down' buttons will generate an event when the button is first pressed. All other buttons on the remote will wait until the button is released and then send both the press and release events at the same time. :Parameters: `button` : unicode The name of the button that was pressed. The valid names are 'up', 'down', 'left', 'right', 'left_hold', 'right_hold', 'menu', 'menu_hold', 'select', and 'select_hold' :event: """ def on_button_release(self, button): """A button on the remote was released. The 'select_hold' and 'menu_hold' button release events are sent immediately after the corresponding press events regardless of whether or not the user has released the button. :Parameters: `button` : unicode The name of the button that was released. The valid names are 'up', 'down', 'left', 'right', 'left_hold', 'right_hold', 'menu', 'menu_hold', 'select', and 'select_hold' :event: """ AppleRemote.register_event_type('on_button_press') AppleRemote.register_event_type('on_button_release') class Tablet(object): '''High-level interface to tablet devices. Unlike other devices, tablets must be opened for a specific window, and cannot be opened exclusively. The `open` method returns a `TabletCanvas` object, which supports the events provided by the tablet. Currently only one tablet device can be used, though it can be opened on multiple windows. If more than one tablet is connected, the behaviour is undefined. ''' def open(self, window): '''Open a tablet device for a window. :Parameters: `window` : `Window` The window on which the tablet will be used. :rtype: `TabletCanvas` ''' raise NotImplementedError('abstract') class TabletCanvas(EventDispatcher): '''Event dispatcher for tablets. Use `Tablet.open` to obtain this object for a particular tablet device and window. Events may be generated even if the tablet stylus is outside of the window; this is operating-system dependent. The events each provide the `TabletCursor` that was used to generate the event; for example, to distinguish between a stylus and an eraser. Only one cursor can be used at a time, otherwise the results are undefined. :Ivariables: `window` : Window The window on which this tablet was opened. ''' # OS X: Active window receives tablet events only when cursor is in window # Windows: Active window receives all tablet events # # Note that this means enter/leave pairs are not always consistent (normal # usage). def __init__(self, window): self.window = window def close(self): '''Close the tablet device for this window. ''' raise NotImplementedError('abstract') if _is_epydoc: def on_enter(self, cursor): '''A cursor entered the proximity of the window. The cursor may be hovering above the tablet surface, but outside of the window bounds, or it may have entered the window bounds. Note that you cannot rely on `on_enter` and `on_leave` events to be generated in pairs; some events may be lost if the cursor was out of the window bounds at the time. :Parameters: `cursor` : `TabletCursor` The cursor that entered proximity. :event: ''' def on_leave(self, cursor): '''A cursor left the proximity of the window. The cursor may have moved too high above the tablet surface to be detected, or it may have left the bounds of the window. Note that you cannot rely on `on_enter` and `on_leave` events to be generated in pairs; some events may be lost if the cursor was out of the window bounds at the time. :Parameters: `cursor` : `TabletCursor` The cursor that left proximity. :event: ''' def on_motion(self, cursor, x, y, pressure): '''The cursor moved on the tablet surface. If `pressure` is 0, then the cursor is actually hovering above the tablet surface, not in contact. :Parameters: `cursor` : `TabletCursor` The cursor that moved. `x` : int The X position of the cursor, in window coordinates. `y` : int The Y position of the cursor, in window coordinates. `pressure` : float The pressure applied to the cursor, in range 0.0 (no pressure) to 1.0 (full pressure). `tilt_x` : float Currently undefined. `tilt_y` : float Currently undefined. :event: ''' TabletCanvas.register_event_type('on_enter') TabletCanvas.register_event_type('on_leave') TabletCanvas.register_event_type('on_motion') class TabletCursor(object): '''A distinct cursor used on a tablet. Most tablets support at least a *stylus* and an *erasor* cursor; this object is used to distinguish them when tablet events are generated. :Ivariables: `name` : str Name of the cursor. ''' # TODO well-defined names for stylus and eraser. def __init__(self, name): self.name = name def __repr__(self): return '%s(%s)' % (self.__class__.__name__, self.name)
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Joystick, tablet and USB HID device support. This module provides a unified interface to almost any input device, besides the regular mouse and keyboard support provided by `Window`. At the lowest level, `get_devices` can be used to retrieve a list of all supported devices, including joysticks, tablets, space controllers, wheels, pedals, remote controls, keyboards and mice. The set of returned devices varies greatly depending on the operating system (and, of course, what's plugged in). At this level pyglet does not try to interpret *what* a particular device is, merely what controls it provides. A `Control` can be either a button, whose value is either ``True`` or ``False``, or a relative or absolute-valued axis, whose value is a float. Sometimes the name of a control can be provided (for example, ``x``, representing the horizontal axis of a joystick), but often not. In these cases the device API may still be useful -- the user will have to be asked to press each button in turn or move each axis separately to identify them. Higher-level interfaces are provided for joysticks, tablets and the Apple remote control. These devices can usually be identified by pyglet positively, and a base level of functionality for each one provided through a common interface. To use an input device: 1. Call `get_devices`, `get_apple_remote` or `get_joysticks` to retrieve and identify the device. 2. For low-level devices (retrieved by `get_devices`), query the devices list of controls and determine which ones you are interested in. For high-level interfaces the set of controls is provided by the interface. 3. Optionally attach event handlers to controls on the device. 4. Call `Device.open` to begin receiving events on the device. You can begin querying the control values after this time; they will be updated asynchronously. 5. Call `Device.close` when you are finished with the device (not needed if your application quits at this time). To use a tablet, follow the procedure above using `get_tablets`, but note that no control list is available; instead, calling `Tablet.open` returns a `TabletCanvas` onto which you should set your event handlers. :since: pyglet 1.2 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import sys from base import Device, Control, RelativeAxis, AbsoluteAxis, \ Button, Joystick, AppleRemote, Tablet from base import DeviceException, DeviceOpenException, DeviceExclusiveException _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc def get_apple_remote(display=None): '''Get the Apple remote control device. The Apple remote is the small white 6-button remote control that accompanies most recent Apple desktops and laptops. The remote can only be used with Mac OS X. :Parameters: `display` : `Display` Currently ignored. :rtype: `AppleRemote` :return: The remote device, or ``None`` if the computer does not support it. ''' return None if _is_epydoc: def get_devices(display=None): '''Get a list of all attached input devices. :Parameters: `display` : `Display` The display device to query for input devices. Ignored on Mac OS X and Windows. On Linux, defaults to the default display device. :rtype: list of `Device` ''' def get_joysticks(display=None): '''Get a list of attached joysticks. :Parameters: `display` : `Display` The display device to query for input devices. Ignored on Mac OS X and Windows. On Linux, defaults to the default display device. :rtype: list of `Joystick` ''' def get_tablets(display=None): '''Get a list of tablets. This function may return a valid tablet device even if one is not attached (for example, it is not possible on Mac OS X to determine if a tablet device is connected). Despite returning a list of tablets, pyglet does not currently support multiple tablets, and the behaviour is undefined if more than one is attached. :Parameters: `display` : `Display` The display device to query for input devices. Ignored on Mac OS X and Windows. On Linux, defaults to the default display device. :rtype: list of `Tablet` ''' else: def get_tablets(display=None): return [] if sys.platform.startswith('linux'): from x11_xinput import get_devices as xinput_get_devices from x11_xinput_tablet import get_tablets from evdev import get_devices as evdev_get_devices from evdev import get_joysticks def get_devices(display=None): return (evdev_get_devices(display) + xinput_get_devices(display)) elif sys.platform in ('cygwin', 'win32'): from directinput import get_devices, get_joysticks try: from wintab import get_tablets except: pass elif sys.platform == 'darwin': from pyglet import options as pyglet_options if pyglet_options['darwin_cocoa']: from darwin_hid import get_devices, get_joysticks, get_apple_remote else: from carbon_hid import get_devices, get_joysticks, get_apple_remote from carbon_tablet import get_tablets
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import pyglet from pyglet.input.base import \ Device, DeviceException, DeviceOpenException, \ Control, Button, RelativeAxis, AbsoluteAxis from pyglet.libs.x11 import xlib from pyglet.compat import asstr try: from pyglet.libs.x11 import xinput as xi _have_xinput = True except: _have_xinput = False def ptr_add(ptr, offset): address = ctypes.addressof(ptr.contents) + offset return ctypes.pointer(type(ptr.contents).from_address(address)) class DeviceResponder(object): def _key_press(self, e): pass def _key_release(self, e): pass def _button_press(self, e): pass def _button_release(self, e): pass def _motion(self, e): pass def _proximity_in(self, e): pass def _proximity_out(self, e): pass class XInputDevice(DeviceResponder, Device): def __init__(self, display, device_info): super(XInputDevice, self).__init__(display, asstr(device_info.name)) self._device_id = device_info.id self._device = None # Read device info self.buttons = [] self.keys = [] self.axes = [] ptr = device_info.inputclassinfo for i in range(device_info.num_classes): cp = ctypes.cast(ptr, ctypes.POINTER(xi.XAnyClassInfo)) cls_class = getattr(cp.contents, 'class') if cls_class == xi.KeyClass: cp = ctypes.cast(ptr, ctypes.POINTER(xi.XKeyInfo)) self.min_keycode = cp.contents.min_keycode num_keys = cp.contents.num_keys for i in range(num_keys): self.keys.append(Button('key%d' % i)) elif cls_class == xi.ButtonClass: cp = ctypes.cast(ptr, ctypes.POINTER(xi.XButtonInfo)) num_buttons = cp.contents.num_buttons for i in range(num_buttons): self.buttons.append(Button('button%d' % i)) elif cls_class == xi.ValuatorClass: cp = ctypes.cast(ptr, ctypes.POINTER(xi.XValuatorInfo)) num_axes = cp.contents.num_axes mode = cp.contents.mode axes = ctypes.cast(cp.contents.axes, ctypes.POINTER(xi.XAxisInfo)) for i in range(num_axes): axis = axes[i] if mode == xi.Absolute: self.axes.append(AbsoluteAxis('axis%d' % i, min=axis.min_value, max=axis.max_value)) elif mode == xi.Relative: self.axes.append(RelativeAxis('axis%d' % i)) cls = cp.contents ptr = ptr_add(ptr, cls.length) self.controls = self.buttons + self.keys + self.axes # Can't detect proximity class event without opening device. Just # assume there is the possibility of a control if there are any axes. if self.axes: self.proximity_control = Button('proximity') self.controls.append(self.proximity_control) else: self.proximity_control = None def get_controls(self): return self.controls def open(self, window=None, exclusive=False): # Checks for is_open and raises if already open. # TODO allow opening on multiple windows. super(XInputDevice, self).open(window, exclusive) if window is None: self.is_open = False raise DeviceOpenException('XInput devices require a window') if window.display._display != self.display._display: self.is_open = False raise DeviceOpenException('Window and device displays differ') if exclusive: self.is_open = False raise DeviceOpenException('Cannot open XInput device exclusive') self._device = xi.XOpenDevice(self.display._display, self._device_id) if not self._device: self.is_open = False raise DeviceOpenException('Cannot open device') self._install_events(window) def close(self): super(XInputDevice, self).close() if not self._device: return # TODO: uninstall events xi.XCloseDevice(self.display._display, self._device) def _install_events(self, window): dispatcher = XInputWindowEventDispatcher.get_dispatcher(window) dispatcher.open_device(self._device_id, self._device, self) # DeviceResponder interface def _key_press(self, e): self.keys[e.keycode - self.min_keycode]._set_value(True) def _key_release(self, e): self.keys[e.keycode - self.min_keycode]._set_value(False) def _button_press(self, e): self.buttons[e.button]._set_value(True) def _button_release(self, e): self.buttons[e.button]._set_value(False) def _motion(self, e): for i in range(e.axes_count): self.axes[i]._set_value(e.axis_data[i]) def _proximity_in(self, e): if self.proximity_control: self.proximity_control._set_value(True) def _proximity_out(self, e): if self.proximity_control: self.proximity_control._set_value(False) class XInputWindowEventDispatcher(object): def __init__(self, window): self.window = window self._responders = {} @staticmethod def get_dispatcher(window): try: dispatcher = window.__xinput_window_event_dispatcher except AttributeError: dispatcher = window.__xinput_window_event_dispatcher = \ XInputWindowEventDispatcher(window) return dispatcher def set_responder(self, device_id, responder): self._responders[device_id] = responder def remove_responder(self, device_id): del self._responders[device_id] def open_device(self, device_id, device, responder): self.set_responder(device_id, responder) device = device.contents if not device.num_classes: return # Bind matching extended window events to bound instance methods # on this object. # # This is inspired by test.c of xinput package by Frederic # Lepied available at x.org. # # In C, this stuff is normally handled by the macro DeviceKeyPress and # friends. Since we don't have access to those macros here, we do it # this way. events = [] def add(class_info, event, handler): _type = class_info.event_type_base + event _class = device_id << 8 | _type events.append(_class) self.window._event_handlers[_type] = handler for i in range(device.num_classes): class_info = device.classes[i] if class_info.input_class == xi.KeyClass: add(class_info, xi._deviceKeyPress, self._event_xinput_key_press) add(class_info, xi._deviceKeyRelease, self._event_xinput_key_release) elif class_info.input_class == xi.ButtonClass: add(class_info, xi._deviceButtonPress, self._event_xinput_button_press) add(class_info, xi._deviceButtonRelease, self._event_xinput_button_release) elif class_info.input_class == xi.ValuatorClass: add(class_info, xi._deviceMotionNotify, self._event_xinput_motion) elif class_info.input_class == xi.ProximityClass: add(class_info, xi._proximityIn, self._event_xinput_proximity_in) add(class_info, xi._proximityOut, self._event_xinput_proximity_out) elif class_info.input_class == xi.FeedbackClass: pass elif class_info.input_class == xi.FocusClass: pass elif class_info.input_class == xi.OtherClass: pass array = (xi.XEventClass * len(events))(*events) xi.XSelectExtensionEvent(self.window._x_display, self.window._window, array, len(array)) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_key_press(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceKeyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._key_press(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_key_release(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceKeyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._key_release(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_button_press(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceButtonEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._button_press(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_button_release(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceButtonEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._button_release(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_motion(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceMotionEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._motion(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_proximity_in(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XProximityNotifyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._proximity_in(e) @pyglet.window.xlib.XlibEventHandler(-1) def _event_xinput_proximity_out(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XProximityNotifyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._proximity_out(e) def _check_extension(display): major_opcode = ctypes.c_int() first_event = ctypes.c_int() first_error = ctypes.c_int() xlib.XQueryExtension(display._display, 'XInputExtension', ctypes.byref(major_opcode), ctypes.byref(first_event), ctypes.byref(first_error)) return bool(major_opcode.value) def get_devices(display=None): if display is None: display = pyglet.canvas.get_display() if not _have_xinput or not _check_extension(display): return [] devices = [] count = ctypes.c_int(0) device_list = xi.XListInputDevices(display._display, count) for i in range(count.value): device_info = device_list[i] devices.append(XInputDevice(display, device_info)) xi.XFreeDeviceList(device_list) return devices
Python
#!/usr/bin/python # $Id:$ import ctypes import pyglet from pyglet.input import base from pyglet.libs import win32 from pyglet.libs.win32 import dinput from pyglet.libs.win32 import _kernel32 # These instance names are not defined anywhere, obtained by experiment. The # GUID names (which seem to be ideally what are needed) are wrong/missing for # most of my devices. _abs_instance_names = { 0: 'x', 1: 'y', 2: 'z', 3: 'rx', 4: 'ry', 5: 'rz', } _rel_instance_names = { 0: 'x', 1: 'y', 2: 'wheel', } _btn_instance_names = {} def _create_control(object_instance): raw_name = object_instance.tszName type = object_instance.dwType instance = dinput.DIDFT_GETINSTANCE(type) if type & dinput.DIDFT_ABSAXIS: name = _abs_instance_names.get(instance) control = base.AbsoluteAxis(name, 0, 0xffff, raw_name) elif type & dinput.DIDFT_RELAXIS: name = _rel_instance_names.get(instance) control = base.RelativeAxis(name, raw_name) elif type & dinput.DIDFT_BUTTON: name = _btn_instance_names.get(instance) control = base.Button(name, raw_name) elif type & dinput.DIDFT_POV: control = base.AbsoluteAxis(base.AbsoluteAxis.HAT, 0, 0xffffffff, raw_name) else: return control._type = object_instance.dwType return control class DirectInputDevice(base.Device): def __init__(self, display, device, device_instance): name = device_instance.tszInstanceName super(DirectInputDevice, self).__init__(display, name) self._type = device_instance.dwDevType & 0xff self._subtype = device_instance.dwDevType & 0xff00 self._device = device self._init_controls() self._set_format() def _init_controls(self): self.controls = [] self._device.EnumObjects( dinput.LPDIENUMDEVICEOBJECTSCALLBACK(self._object_enum), None, dinput.DIDFT_ALL) def _object_enum(self, object_instance, arg): control = _create_control(object_instance.contents) if control: self.controls.append(control) return dinput.DIENUM_CONTINUE def _set_format(self): if not self.controls: return object_formats = (dinput.DIOBJECTDATAFORMAT * len(self.controls))() offset = 0 for object_format, control in zip(object_formats, self.controls): object_format.dwOfs = offset object_format.dwType = control._type offset += 4 format = dinput.DIDATAFORMAT() format.dwSize = ctypes.sizeof(format) format.dwObjSize = ctypes.sizeof(dinput.DIOBJECTDATAFORMAT) format.dwFlags = 0 format.dwDataSize = offset format.dwNumObjs = len(object_formats) format.rgodf = ctypes.cast(ctypes.pointer(object_formats), dinput.LPDIOBJECTDATAFORMAT) self._device.SetDataFormat(format) prop = dinput.DIPROPDWORD() prop.diph.dwSize = ctypes.sizeof(prop) prop.diph.dwHeaderSize = ctypes.sizeof(prop.diph) prop.diph.dwObj = 0 prop.diph.dwHow = dinput.DIPH_DEVICE prop.dwData = 64 * ctypes.sizeof(dinput.DIDATAFORMAT) self._device.SetProperty(dinput.DIPROP_BUFFERSIZE, ctypes.byref(prop.diph)) def open(self, window=None, exclusive=False): if not self.controls: return if window is None: # Pick any open window, or the shadow window if no windows # have been created yet. window = pyglet.gl._shadow_window for window in pyglet.app.windows: break flags = dinput.DISCL_BACKGROUND if exclusive: flags |= dinput.DISCL_EXCLUSIVE else: flags |= dinput.DISCL_NONEXCLUSIVE self._wait_object = _kernel32.CreateEventW(None, False, False, None) self._device.SetEventNotification(self._wait_object) pyglet.app.platform_event_loop.add_wait_object(self._wait_object, self._dispatch_events) self._device.SetCooperativeLevel(window._hwnd, flags) self._device.Acquire() def close(self): if not self.controls: return pyglet.app.platform_event_loop.remove_wait_object(self._wait_object) self._device.Unacquire() self._device.SetEventNotification(None) _kernel32.CloseHandle(self._wait_object) def get_controls(self): return self.controls def _dispatch_events(self): if not self.controls: return events = (dinput.DIDEVICEOBJECTDATA * 64)() n_events = win32.DWORD(len(events)) self._device.GetDeviceData(ctypes.sizeof(dinput.DIDEVICEOBJECTDATA), ctypes.cast(ctypes.pointer(events), dinput.LPDIDEVICEOBJECTDATA), ctypes.byref(n_events), 0) for event in events[:n_events.value]: index = event.dwOfs // 4 self.controls[index]._set_value(event.dwData) _i_dinput = None def _init_directinput(): global _i_dinput if _i_dinput: return _i_dinput = dinput.IDirectInput8() module = _kernel32.GetModuleHandleW(None) dinput.DirectInput8Create(module, dinput.DIRECTINPUT_VERSION, dinput.IID_IDirectInput8W, ctypes.byref(_i_dinput), None) def get_devices(display=None): _init_directinput() _devices = [] def _device_enum(device_instance, arg): device = dinput.IDirectInputDevice8() _i_dinput.CreateDevice(device_instance.contents.guidInstance, ctypes.byref(device), None) _devices.append(DirectInputDevice(display, device, device_instance.contents)) return dinput.DIENUM_CONTINUE _i_dinput.EnumDevices(dinput.DI8DEVCLASS_ALL, dinput.LPDIENUMDEVICESCALLBACK(_device_enum), None, dinput.DIEDFL_ATTACHEDONLY) return _devices def _create_joystick(device): if device._type in (dinput.DI8DEVTYPE_JOYSTICK, dinput.DI8DEVTYPE_GAMEPAD): return base.Joystick(device) def get_joysticks(display=None): return filter(None, [_create_joystick(d) for d in get_devices(display)])
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from pyglet.app.base import PlatformEventLoop from pyglet.libs.darwin.cocoapy import * NSApplication = ObjCClass('NSApplication') NSMenu = ObjCClass('NSMenu') NSMenuItem = ObjCClass('NSMenuItem') NSAutoreleasePool = ObjCClass('NSAutoreleasePool') NSDate = ObjCClass('NSDate') NSEvent = ObjCClass('NSEvent') def add_menu_item(menu, title, action, key): title = CFSTR(title) action = get_selector(action) key = CFSTR(key) menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( title, action, key) menu.addItem_(menuItem) # cleanup title.release() key.release() menuItem.release() def create_menu(): appMenu = NSMenu.alloc().init() # Hide still doesn't work!? add_menu_item(appMenu, 'Hide!', 'hide:', 'h') appMenu.addItem_(NSMenuItem.separatorItem()) add_menu_item(appMenu, 'Quit!', 'terminate:', 'q') menubar = NSMenu.alloc().init() appMenuItem = NSMenuItem.alloc().init() appMenuItem.setSubmenu_(appMenu) menubar.addItem_(appMenuItem) NSApp = NSApplication.sharedApplication() NSApp.setMainMenu_(menubar) # cleanup appMenu.release() menubar.release() appMenuItem.release() class CocoaEventLoop(PlatformEventLoop): def __init__(self): super(CocoaEventLoop, self).__init__() # Prepare the default application. self.NSApp = NSApplication.sharedApplication() # Create an autorelease pool for menu creation and finishLaunching self.pool = NSAutoreleasePool.alloc().init() create_menu() self.NSApp.setActivationPolicy_(NSApplicationActivationPolicyRegular) self.NSApp.finishLaunching() self.NSApp.activateIgnoringOtherApps_(True) def start(self): pass def step(self, timeout=None): # Drain the old autorelease pool self.pool.drain() self.pool = NSAutoreleasePool.alloc().init() # Determine the timeout date. if timeout is None: # Using distantFuture as untilDate means that nextEventMatchingMask # will wait until the next event comes along. timeout_date = NSDate.distantFuture() else: timeout_date = NSDate.dateWithTimeIntervalSinceNow_(timeout) # Retrieve the next event (if any). We wait for an event to show up # and then process it, or if timeout_date expires we simply return. # We only process one event per call of step(). self._is_running.set() event = self.NSApp.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, timeout_date, NSDefaultRunLoopMode, True) # Dispatch the event (if any). if event is not None: event_type = event.type() if event_type != NSApplicationDefined: # Send out event as normal. Responders will still receive # keyUp:, keyDown:, and flagsChanged: events. self.NSApp.sendEvent_(event) # Resend key events as special pyglet-specific messages # which supplant the keyDown:, keyUp:, and flagsChanged: messages # because NSApplication translates multiple key presses into key # equivalents before sending them on, which means that some keyUp: # messages are never sent for individual keys. Our pyglet-specific # replacements ensure that we see all the raw key presses & releases. # We also filter out key-down repeats since pyglet only sends one # on_key_press event per key press. if event_type == NSKeyDown and not event.isARepeat(): self.NSApp.sendAction_to_from_(get_selector("pygletKeyDown:"), None, event) elif event_type == NSKeyUp: self.NSApp.sendAction_to_from_(get_selector("pygletKeyUp:"), None, event) elif event_type == NSFlagsChanged: self.NSApp.sendAction_to_from_(get_selector("pygletFlagsChanged:"), None, event) self.NSApp.updateWindows() did_time_out = False else: did_time_out = True self._is_running.clear() # Destroy the autorelease pool used for this step. #del pool return did_time_out def stop(self): pass def notify(self): pool = NSAutoreleasePool.alloc().init() notifyEvent = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSApplicationDefined, # type NSPoint(0.0, 0.0), # location 0, # modifierFlags 0, # timestamp 0, # windowNumber None, # graphicsContext 0, # subtype 0, # data1 0, # data2 ) self.NSApp.postEvent_atStart_(notifyEvent, False) pool.drain()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes from pyglet import app from base import PlatformEventLoop from pyglet.libs.win32 import _kernel32, _user32, types, constants from pyglet.libs.win32.constants import * from pyglet.libs.win32.types import * class Win32EventLoop(PlatformEventLoop): def __init__(self): super(Win32EventLoop, self).__init__() self._next_idle_time = None # Force immediate creation of an event queue on this thread -- note # that since event loop is created on pyglet.app import, whatever # imports pyglet.app _must_ own the main run loop. msg = types.MSG() _user32.PeekMessageW(ctypes.byref(msg), 0, constants.WM_USER, constants.WM_USER, constants.PM_NOREMOVE) self._event_thread = _kernel32.GetCurrentThreadId() self._wait_objects = [] self._recreate_wait_objects_array() self._timer_proc = types.TIMERPROC(self._timer_proc_func) self._timer = _user32.SetTimer( 0, 0, constants.USER_TIMER_MAXIMUM, self._timer_proc) def add_wait_object(self, object, func): self._wait_objects.append((object, func)) self._recreate_wait_objects_array() def remove_wait_object(self, object): for i, (_object, _) in enumerate(self._wait_objects): if object == _object: del self._wait_objects[i] break self._recreate_wait_objects_array() def _recreate_wait_objects_array(self): if not self._wait_objects: self._wait_objects_n = 0 self._wait_objects_array = None return self._wait_objects_n = len(self._wait_objects) self._wait_objects_array = \ (HANDLE * self._wait_objects_n)(*[o for o, f in self._wait_objects]) def start(self): if _kernel32.GetCurrentThreadId() != self._event_thread: raise RuntimeError('EventLoop.run() must be called from the same ' + 'thread that imports pyglet.app') self._timer_func = None self._polling = False self._allow_polling = True def step(self, timeout=None): self.dispatch_posted_events() msg = types.MSG() if timeout is None: timeout = constants.INFINITE else: timeout = int(timeout * 1000) # milliseconds result = _user32.MsgWaitForMultipleObjects( self._wait_objects_n, self._wait_objects_array, False, timeout, constants.QS_ALLINPUT) result -= constants.WAIT_OBJECT_0 if result == self._wait_objects_n: while _user32.PeekMessageW(ctypes.byref(msg), 0, 0, 0, constants.PM_REMOVE): _user32.TranslateMessage(ctypes.byref(msg)) _user32.DispatchMessageW(ctypes.byref(msg)) elif 0 <= result < self._wait_objects_n: object, func = self._wait_objects[result] func() # Return True if timeout was interrupted. return result <= self._wait_objects_n def notify(self): # Nudge the event loop with a message it will discard. Note that only # user events are actually posted. The posted event will not # interrupt the window move/size drag loop -- it seems there's no way # to do this. _user32.PostThreadMessageW(self._event_thread, constants.WM_USER, 0, 0) def set_timer(self, func, interval): if func is None or interval is None: interval = constants.USER_TIMER_MAXIMUM else: interval = int(interval * 1000) # milliseconds self._timer_func = func _user32.SetTimer(0, self._timer, interval, self._timer_proc) def _timer_proc_func(self, hwnd, msg, timer, t): if self._timer_func: self._timer_func()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import os import select import threading from ctypes import * from pyglet import app from pyglet.app.base import PlatformEventLoop from pyglet.compat import asbytes class XlibSelectDevice(object): def fileno(self): '''Get the file handle for ``select()`` for this device. :rtype: int ''' raise NotImplementedError('abstract') def select(self): '''Perform event processing on the device. Called when ``select()`` returns this device in its list of active files. ''' raise NotImplementedError('abstract') def poll(self): '''Check if the device has events ready to process. :rtype: bool :return: True if there are events to process, False otherwise. ''' return False class NotificationDevice(XlibSelectDevice): def __init__(self): self._sync_file_read, self._sync_file_write = os.pipe() self._event = threading.Event() def fileno(self): return self._sync_file_read def set(self): self._event.set() os.write(self._sync_file_write, asbytes('1')) def select(self): self._event.clear() os.read(self._sync_file_read, 1) app.platform_event_loop.dispatch_posted_events() def poll(self): return self._event.isSet() class XlibEventLoop(PlatformEventLoop): def __init__(self): super(XlibEventLoop, self).__init__() self._notification_device = NotificationDevice() self._select_devices = set() self._select_devices.add(self._notification_device) def notify(self): self._notification_device.set() def step(self, timeout=None): pending_devices = [] # Check for already pending events for device in self._select_devices: if device.poll(): pending_devices.append(device) # If nothing was immediately pending, block until there's activity # on a device. if not pending_devices and (timeout is None or timeout > 0.0): iwtd = self._select_devices pending_devices, _, _ = select.select(iwtd, (), (), timeout) if not pending_devices: return False # Dispatch activity on matching devices for device in pending_devices: device.select() # Dispatch resize events for window in app.windows: if window._needs_resize: window.switch_to() window.dispatch_event('on_resize', window._width, window._height) window.dispatch_event('on_expose') window._needs_resize = False return True
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import sys import threading import Queue from pyglet import app from pyglet import clock from pyglet import event _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc class PlatformEventLoop(object): ''' :since: pyglet 1.2 ''' def __init__(self): self._event_queue = Queue.Queue() self._is_running = threading.Event() self._is_running.clear() def is_running(self): '''Return True if the event loop is currently processing, or False if it is blocked or not activated. :rtype: bool ''' return self._is_running.is_set() def post_event(self, dispatcher, event, *args): '''Post an event into the main application thread. The event is queued internally until the `run` method's thread is able to dispatch the event. This method can be safely called from any thread. If the method is called from the `run` method's thread (for example, from within an event handler), the event may be dispatched within the same runloop iteration or the next one; the choice is nondeterministic. :Parameters: `dispatcher` : EventDispatcher Dispatcher to process the event. `event` : str Event name. `args` : sequence Arguments to pass to the event handlers. ''' self._event_queue.put((dispatcher, event, args)) self.notify() def dispatch_posted_events(self): '''Immediately dispatch all pending events. Normally this is called automatically by the runloop iteration. ''' while True: try: dispatcher, event, args = self._event_queue.get(False) except Queue.Empty: break dispatcher.dispatch_event(event, *args) def notify(self): '''Notify the event loop that something needs processing. If the event loop is blocked, it will unblock and perform an iteration immediately. If the event loop is running, another iteration is scheduled for immediate execution afterwards. ''' raise NotImplementedError('abstract') def start(self): pass def step(self, timeout=None): '''TODO in mac/linux: return True if didn't time out''' raise NotImplementedError('abstract') def set_timer(self, func, interval): raise NotImplementedError('abstract') def stop(self): pass class EventLoop(event.EventDispatcher): '''The main run loop of the application. Calling `run` begins the application event loop, which processes operating system events, calls `pyglet.clock.tick` to call scheduled functions and calls `pyglet.window.Window.on_draw` and `pyglet.window.Window.flip` to update window contents. Applications can subclass `EventLoop` and override certain methods to integrate another framework's run loop, or to customise processing in some other way. You should not in general override `run`, as this method contains platform-specific code that ensures the application remains responsive to the user while keeping CPU usage to a minimum. ''' _has_exit_condition = None _has_exit = False def __init__(self): self._has_exit_condition = threading.Condition() self.clock = clock.get_default() self.is_running = False def run(self): '''Begin processing events, scheduled functions and window updates. This method returns when `has_exit` is set to True. Developers are discouraged from overriding this method, as the implementation is platform-specific. ''' self.has_exit = False self._legacy_setup() platform_event_loop = app.platform_event_loop platform_event_loop.start() self.dispatch_event('on_enter') self.is_running = True if True: # TODO runtime option. self._run_estimated() else: self._run() self.is_running = False self.dispatch_event('on_exit') platform_event_loop.stop() def _run(self): '''The simplest standard run loop, using constant timeout. Suitable for well-behaving platforms (Mac, Linux and some Windows). ''' platform_event_loop = app.platform_event_loop while not self.has_exit: timeout = self.idle() platform_event_loop.step(timeout) def _run_estimated(self): '''Run-loop that continually estimates function mapping requested timeout to measured timeout using a least-squares linear regression. Suitable for oddball platforms (Windows). ''' platform_event_loop = app.platform_event_loop predictor = self._least_squares() gradient, offset = predictor.next() time = self.clock.time while not self.has_exit: timeout = self.idle() if timeout is None: estimate = None else: estimate = max(gradient * timeout + offset, 0.0) if False: print 'Gradient = %f, Offset = %f' % (gradient, offset) print 'Timeout = %f, Estimate = %f' % (timeout, estimate) t = time() if not platform_event_loop.step(estimate) and estimate != 0.0 and \ estimate is not None: dt = time() - t gradient, offset = predictor.send((dt, estimate)) @staticmethod def _least_squares(gradient=1, offset=0): X = 0 Y = 0 XX = 0 XY = 0 n = 0 x, y = yield gradient, offset X += x Y += y XX += x * x XY += x * y n += 1 while True: x, y = yield gradient, offset X += x Y += y XX += x * x XY += x * y n += 1 try: gradient = (n * XY - X * Y) / (n * XX - X * X) offset = (Y - gradient * X) / n except ZeroDivisionError: # Can happen in pathalogical case; keep current # gradient/offset for now. pass def _legacy_setup(self): # Disable event queuing for dispatch_events from pyglet.window import Window Window._enable_event_queue = False # Dispatch pending events for window in app.windows: window.switch_to() window.dispatch_pending_events() def enter_blocking(self): '''Called by pyglet internal processes when the operating system is about to block due to a user interaction. For example, this is common when the user begins resizing or moving a window. This method provides the event loop with an opportunity to set up an OS timer on the platform event loop, which will continue to be invoked during the blocking operation. The default implementation ensures that `idle` continues to be called as documented. :since: pyglet 1.2 ''' timeout = self.idle() app.platform_event_loop.set_timer(self._blocking_timer, timeout) def exit_blocking(self): '''Called by pyglet internal processes when the blocking operation completes. See `enter_blocking`. ''' app.platform_event_loop.set_timer(None, None) def _blocking_timer(self): timeout = self.idle() app.platform_event_loop.set_timer(self._blocking_timer, timeout) def idle(self): '''Called during each iteration of the event loop. The method is called immediately after any window events (i.e., after any user input). The method can return a duration after which the idle method will be called again. The method may be called earlier if the user creates more input events. The method can return `None` to only wait for user events. For example, return ``1.0`` to have the idle method called every second, or immediately after any user events. The default implementation dispatches the `pyglet.window.Window.on_draw` event for all windows and uses `pyglet.clock.tick` and `pyglet.clock.get_sleep_time` on the default clock to determine the return value. This method should be overridden by advanced users only. To have code execute at regular intervals, use the `pyglet.clock.schedule` methods. :rtype: float :return: The number of seconds before the idle method should be called again, or `None` to block for user input. ''' dt = self.clock.update_time() redraw_all = self.clock.call_scheduled_functions(dt) # Redraw all windows for window in app.windows: if redraw_all or (window._legacy_invalid and window.invalid): window.switch_to() window.dispatch_event('on_draw') window.flip() window._legacy_invalid = False # Update timout return self.clock.get_sleep_time(True) def _get_has_exit(self): self._has_exit_condition.acquire() result = self._has_exit self._has_exit_condition.release() return result def _set_has_exit(self, value): self._has_exit_condition.acquire() self._has_exit = value self._has_exit_condition.notify() self._has_exit_condition.release() has_exit = property(_get_has_exit, _set_has_exit, doc='''Flag indicating if the event loop will exit in the next iteration. When set, all waiting threads are interrupted (see `sleep`). Thread-safe since pyglet 1.2. :see: `exit` :type: bool ''') def exit(self): '''Safely exit the event loop at the end of the current iteration. This method is a thread-safe equivalent for for setting `has_exit` to ``True``. All waiting threads will be interrupted (see `sleep`). ''' self._set_has_exit(True) app.platform_event_loop.notify() def sleep(self, timeout): '''Wait for some amount of time, or until the `has_exit` flag is set or `exit` is called. This method is thread-safe. :Parameters: `timeout` : float Time to wait, in seconds. :since: pyglet 1.2 :rtype: bool :return: ``True`` if the `has_exit` flag is now set, otherwise ``False``. ''' self._has_exit_condition.acquire() self._has_exit_condition.wait(timeout) result = self._has_exit self._has_exit_condition.release() return result def on_window_close(self, window): '''Default window close handler.''' if not app.windows: self.exit() if _is_epydoc: def on_window_close(self, window): '''A window was closed. This event is dispatched when a window is closed. It is not dispatched if the window's close button was pressed but the window did not close. The default handler calls `exit` if no more windows are open. You can override this handler to base your application exit on some other policy. :event: ''' def on_enter(self): '''The event loop is about to begin. This is dispatched when the event loop is prepared to enter the main run loop, and represents the last chance for an application to initialise itself. :event: ''' def on_exit(self): '''The event loop is about to exit. After dispatching this event, the `run` method returns (the application may not actually exit if you have more code following the `run` invocation). :event: ''' EventLoop.register_event_type('on_window_close') EventLoop.register_event_type('on_enter') EventLoop.register_event_type('on_exit')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes from pyglet import app from pyglet.app.base import PlatformEventLoop from pyglet.libs.darwin import * EventLoopTimerProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p) class CarbonEventLoop(PlatformEventLoop): def __init__(self): self._event_loop = carbon.GetMainEventLoop() self._timer = ctypes.c_void_p() self._timer_func = None self._timer_func_proc = EventLoopTimerProc(self._timer_proc) super(CarbonEventLoop, self).__init__() def notify(self): carbon.SetEventLoopTimerNextFireTime( self._timer, ctypes.c_double(0.0)) def start(self): # Create timer timer = self._timer carbon.InstallEventLoopTimer(self._event_loop, ctypes.c_double(0.1), #? ctypes.c_double(kEventDurationForever), self._timer_func_proc, None, ctypes.byref(timer)) def stop(self): carbon.RemoveEventLoopTimer(self._timer) def step(self, timeout=None): self.dispatch_posted_events() event_dispatcher = carbon.GetEventDispatcherTarget() e = ctypes.c_void_p() if timeout is None: timeout = kEventDurationForever self._is_running.set() # XXX should spin on multiple events after first timeout if carbon.ReceiveNextEvent(0, None, ctypes.c_double(timeout), True, ctypes.byref(e)) == 0: carbon.SendEventToEventTarget(e, event_dispatcher) carbon.ReleaseEvent(e) timed_out = False else: timed_out = True self._is_running.clear() return not timed_out def set_timer(self, func, interval): if interval is None or func is None: interval = kEventDurationForever self._timer_func = func carbon.SetEventLoopTimerNextFireTime(self._timer, ctypes.c_double(interval)) def _timer_proc(self, timer, data): if self._timer_func: self._timer_func() ''' self.dispatch_posted_events() allow_polling = True for window in app.windows: # Check for live resizing if window._resizing is not None: allow_polling = False old_width, old_height = window._resizing rect = Rect() carbon.GetWindowBounds(window._window, kWindowContentRgn, ctypes.byref(rect)) width = rect.right - rect.left height = rect.bottom - rect.top if width != old_width or height != old_height: window._resizing = width, height window.switch_to() window.dispatch_event('on_resize', width, height) # Check for live dragging if window._dragging: allow_polling = False # Check for deferred recreate if window._recreate_deferred: # Break out of ReceiveNextEvent so it can be processed # in next iteration. carbon.QuitEventLoop(self._event_loop) self._force_idle = True sleep_time = self.idle() if sleep_time is None: sleep_time = kEventDurationForever elif sleep_time < 0.01 and allow_polling and self._allow_polling: # Switch event loop to polling. carbon.QuitEventLoop(self._event_loop) self._force_idle = True sleep_time = kEventDurationForever carbon.SetEventLoopTimerNextFireTime(timer, ctypes.c_double(sleep_time)) '''
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import sys import threading import Queue from pyglet import app from pyglet import clock from pyglet import event _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc class PlatformEventLoop(object): ''' :since: pyglet 1.2 ''' def __init__(self): self._event_queue = Queue.Queue() self._is_running = threading.Event() self._is_running.clear() def is_running(self): '''Return True if the event loop is currently processing, or False if it is blocked or not activated. :rtype: bool ''' return self._is_running.is_set() def post_event(self, dispatcher, event, *args): '''Post an event into the main application thread. The event is queued internally until the `run` method's thread is able to dispatch the event. This method can be safely called from any thread. If the method is called from the `run` method's thread (for example, from within an event handler), the event may be dispatched within the same runloop iteration or the next one; the choice is nondeterministic. :Parameters: `dispatcher` : EventDispatcher Dispatcher to process the event. `event` : str Event name. `args` : sequence Arguments to pass to the event handlers. ''' self._event_queue.put((dispatcher, event, args)) self.notify() def dispatch_posted_events(self): '''Immediately dispatch all pending events. Normally this is called automatically by the runloop iteration. ''' while True: try: dispatcher, event, args = self._event_queue.get(False) except Queue.Empty: break dispatcher.dispatch_event(event, *args) def notify(self): '''Notify the event loop that something needs processing. If the event loop is blocked, it will unblock and perform an iteration immediately. If the event loop is running, another iteration is scheduled for immediate execution afterwards. ''' raise NotImplementedError('abstract') def start(self): pass def step(self, timeout=None): '''TODO in mac/linux: return True if didn't time out''' raise NotImplementedError('abstract') def set_timer(self, func, interval): raise NotImplementedError('abstract') def stop(self): pass class EventLoop(event.EventDispatcher): '''The main run loop of the application. Calling `run` begins the application event loop, which processes operating system events, calls `pyglet.clock.tick` to call scheduled functions and calls `pyglet.window.Window.on_draw` and `pyglet.window.Window.flip` to update window contents. Applications can subclass `EventLoop` and override certain methods to integrate another framework's run loop, or to customise processing in some other way. You should not in general override `run`, as this method contains platform-specific code that ensures the application remains responsive to the user while keeping CPU usage to a minimum. ''' _has_exit_condition = None _has_exit = False def __init__(self): self._has_exit_condition = threading.Condition() self.clock = clock.get_default() self.is_running = False def run(self): '''Begin processing events, scheduled functions and window updates. This method returns when `has_exit` is set to True. Developers are discouraged from overriding this method, as the implementation is platform-specific. ''' self.has_exit = False self._legacy_setup() platform_event_loop = app.platform_event_loop platform_event_loop.start() self.dispatch_event('on_enter') self.is_running = True if True: # TODO runtime option. self._run_estimated() else: self._run() self.is_running = False self.dispatch_event('on_exit') platform_event_loop.stop() def _run(self): '''The simplest standard run loop, using constant timeout. Suitable for well-behaving platforms (Mac, Linux and some Windows). ''' platform_event_loop = app.platform_event_loop while not self.has_exit: timeout = self.idle() platform_event_loop.step(timeout) def _run_estimated(self): '''Run-loop that continually estimates function mapping requested timeout to measured timeout using a least-squares linear regression. Suitable for oddball platforms (Windows). ''' platform_event_loop = app.platform_event_loop predictor = self._least_squares() gradient, offset = predictor.next() time = self.clock.time while not self.has_exit: timeout = self.idle() if timeout is None: estimate = None else: estimate = max(gradient * timeout + offset, 0.0) if False: print 'Gradient = %f, Offset = %f' % (gradient, offset) print 'Timeout = %f, Estimate = %f' % (timeout, estimate) t = time() if not platform_event_loop.step(estimate) and estimate != 0.0 and \ estimate is not None: dt = time() - t gradient, offset = predictor.send((dt, estimate)) @staticmethod def _least_squares(gradient=1, offset=0): X = 0 Y = 0 XX = 0 XY = 0 n = 0 x, y = yield gradient, offset X += x Y += y XX += x * x XY += x * y n += 1 while True: x, y = yield gradient, offset X += x Y += y XX += x * x XY += x * y n += 1 try: gradient = (n * XY - X * Y) / (n * XX - X * X) offset = (Y - gradient * X) / n except ZeroDivisionError: # Can happen in pathalogical case; keep current # gradient/offset for now. pass def _legacy_setup(self): # Disable event queuing for dispatch_events from pyglet.window import Window Window._enable_event_queue = False # Dispatch pending events for window in app.windows: window.switch_to() window.dispatch_pending_events() def enter_blocking(self): '''Called by pyglet internal processes when the operating system is about to block due to a user interaction. For example, this is common when the user begins resizing or moving a window. This method provides the event loop with an opportunity to set up an OS timer on the platform event loop, which will continue to be invoked during the blocking operation. The default implementation ensures that `idle` continues to be called as documented. :since: pyglet 1.2 ''' timeout = self.idle() app.platform_event_loop.set_timer(self._blocking_timer, timeout) def exit_blocking(self): '''Called by pyglet internal processes when the blocking operation completes. See `enter_blocking`. ''' app.platform_event_loop.set_timer(None, None) def _blocking_timer(self): timeout = self.idle() app.platform_event_loop.set_timer(self._blocking_timer, timeout) def idle(self): '''Called during each iteration of the event loop. The method is called immediately after any window events (i.e., after any user input). The method can return a duration after which the idle method will be called again. The method may be called earlier if the user creates more input events. The method can return `None` to only wait for user events. For example, return ``1.0`` to have the idle method called every second, or immediately after any user events. The default implementation dispatches the `pyglet.window.Window.on_draw` event for all windows and uses `pyglet.clock.tick` and `pyglet.clock.get_sleep_time` on the default clock to determine the return value. This method should be overridden by advanced users only. To have code execute at regular intervals, use the `pyglet.clock.schedule` methods. :rtype: float :return: The number of seconds before the idle method should be called again, or `None` to block for user input. ''' dt = self.clock.update_time() redraw_all = self.clock.call_scheduled_functions(dt) # Redraw all windows for window in app.windows: if redraw_all or (window._legacy_invalid and window.invalid): window.switch_to() window.dispatch_event('on_draw') window.flip() window._legacy_invalid = False # Update timout return self.clock.get_sleep_time(True) def _get_has_exit(self): self._has_exit_condition.acquire() result = self._has_exit self._has_exit_condition.release() return result def _set_has_exit(self, value): self._has_exit_condition.acquire() self._has_exit = value self._has_exit_condition.notify() self._has_exit_condition.release() has_exit = property(_get_has_exit, _set_has_exit, doc='''Flag indicating if the event loop will exit in the next iteration. When set, all waiting threads are interrupted (see `sleep`). Thread-safe since pyglet 1.2. :see: `exit` :type: bool ''') def exit(self): '''Safely exit the event loop at the end of the current iteration. This method is a thread-safe equivalent for for setting `has_exit` to ``True``. All waiting threads will be interrupted (see `sleep`). ''' self._set_has_exit(True) app.platform_event_loop.notify() def sleep(self, timeout): '''Wait for some amount of time, or until the `has_exit` flag is set or `exit` is called. This method is thread-safe. :Parameters: `timeout` : float Time to wait, in seconds. :since: pyglet 1.2 :rtype: bool :return: ``True`` if the `has_exit` flag is now set, otherwise ``False``. ''' self._has_exit_condition.acquire() self._has_exit_condition.wait(timeout) result = self._has_exit self._has_exit_condition.release() return result def on_window_close(self, window): '''Default window close handler.''' if not app.windows: self.exit() if _is_epydoc: def on_window_close(self, window): '''A window was closed. This event is dispatched when a window is closed. It is not dispatched if the window's close button was pressed but the window did not close. The default handler calls `exit` if no more windows are open. You can override this handler to base your application exit on some other policy. :event: ''' def on_enter(self): '''The event loop is about to begin. This is dispatched when the event loop is prepared to enter the main run loop, and represents the last chance for an application to initialise itself. :event: ''' def on_exit(self): '''The event loop is about to exit. After dispatching this event, the `run` method returns (the application may not actually exit if you have more code following the `run` invocation). :event: ''' EventLoop.register_event_type('on_window_close') EventLoop.register_event_type('on_enter') EventLoop.register_event_type('on_exit')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Application-wide functionality. Most applications need only call `run` after creating one or more windows to begin processing events. For example, a simple application consisting of one window is:: import pyglet win = pyglet.window.Window() pyglet.app.run() To handle events on the main event loop, instantiate it manually. The following example exits the application as soon as any window is closed (the default policy is to wait until all windows are closed):: event_loop = pyglet.app.EventLoop() @event_loop.event def on_window_close(window): event_loop.exit() :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import sys import weakref _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc class AppException(Exception): pass class WeakSet(object): '''Set of objects, referenced weakly. Adding an object to this set does not prevent it from being garbage collected. Upon being garbage collected, the object is automatically removed from the set. ''' def __init__(self): self._dict = weakref.WeakKeyDictionary() def add(self, value): self._dict[value] = True def remove(self, value): del self._dict[value] def __iter__(self): for key in self._dict.keys(): yield key def __contains__(self, other): return other in self._dict def __len__(self): return len(self._dict) #: Set of all open displays. Instances of `Display` are automatically added #: to this set upon construction. The set uses weak references, so displays #: are removed from the set when they are no longer referenced. #: #: :deprecated: Use `pyglet.canvas.get_display`. #: #: :type: `WeakSet` displays = WeakSet() #: Set of all open windows (including invisible windows). Instances of #: `Window` are automatically added to this set upon construction. The set #: uses weak references, so windows are removed from the set when they are no #: longer referenced or are closed explicitly. #: #: :type: `WeakSet` windows = WeakSet() def run(): '''Begin processing events, scheduled functions and window updates. This is a convenience function, equivalent to:: pyglet.app.event_loop.run() ''' event_loop.run() def exit(): '''Exit the application event loop. Causes the application event loop to finish, if an event loop is currently running. The application may not necessarily exit (for example, there may be additional code following the `run` invocation). This is a convenience function, equivalent to:: event_loop.exit() ''' event_loop.exit() from pyglet.app.base import EventLoop if _is_epydoc: from pyglet.app.base import PlatformEventLoop else: if sys.platform == 'darwin': from pyglet import options as pyglet_options if pyglet_options['darwin_cocoa']: from pyglet.app.cocoa import CocoaEventLoop as PlatformEventLoop else: from pyglet.app.carbon import CarbonEventLoop as PlatformEventLoop elif sys.platform in ('win32', 'cygwin'): from pyglet.app.win32 import Win32EventLoop as PlatformEventLoop else: from pyglet.app.xlib import XlibEventLoop as PlatformEventLoop #: The global event loop. Applications can replace this with their own #: subclass of `pyglet.app.base.EventLoop` before calling `EventLoop.run`. #: #: :type: `EventLoop` event_loop = EventLoop() #: The platform-dependent event loop. Applications must not subclass or #: replace this object. #: #: :since: pyglet 1.2 #: #: :type: `PlatformEventLoop` platform_event_loop = PlatformEventLoop()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ '''Minimal Windows COM interface. Allows pyglet to use COM interfaces on Windows without comtypes. Unlike comtypes, this module does not provide property interfaces, read typelibs, nice-ify return values or permit Python implementations of COM interfaces. We don't need anything that sophisticated to work with DirectX. All interfaces should derive from IUnknown (defined in this module). The Python COM interfaces are actually pointers to the implementation (take note when translating methods that take an interface as argument). Interfaces can define methods:: class IDirectSound8(com.IUnknown): _methods_ = [ ('CreateSoundBuffer', com.STDMETHOD()), ('GetCaps', com.STDMETHOD(LPDSCAPS)), ... ] Only use STDMETHOD or METHOD for the method types (not ordinary ctypes function types). The 'this' pointer is bound automatically... e.g., call:: device = IDirectSound8() DirectSoundCreate8(None, ctypes.byref(device), None) caps = DSCAPS() device.GetCaps(caps) Because STDMETHODs use HRESULT as the return type, there is no need to check the return value. Don't forget to manually manage memory... call Release() when you're done with an interface. ''' import ctypes import sys if sys.platform != 'win32': raise ImportError('pyglet.com requires a Windows build of Python') class GUID(ctypes.Structure): _fields_ = [ ('Data1', ctypes.c_ulong), ('Data2', ctypes.c_ushort), ('Data3', ctypes.c_ushort), ('Data4', ctypes.c_ubyte * 8) ] def __init__(self, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8): self.Data1 = l self.Data2 = w1 self.Data3 = w2 self.Data4[:] = (b1, b2, b3, b4, b5, b6, b7, b8) def __repr__(self): b1, b2, b3, b4, b5, b6, b7, b8 = self.Data4 return 'GUID(%x, %x, %x, %x, %x, %x, %x, %x, %x, %x, %x)' % ( self.Data1, self.Data2, self.Data3, b1, b2, b3, b4, b5, b6, b7, b8) LPGUID = ctypes.POINTER(GUID) IID = GUID REFIID = ctypes.POINTER(IID) class METHOD(object): '''COM method.''' def __init__(self, restype, *args): self.restype = restype self.argtypes = args def get_field(self): return ctypes.WINFUNCTYPE(self.restype, *self.argtypes) class STDMETHOD(METHOD): '''COM method with HRESULT return value.''' def __init__(self, *args): super(STDMETHOD, self).__init__(ctypes.HRESULT, *args) class COMMethodInstance(object): '''Binds a COM interface method.''' def __init__(self, name, i, method): self.name = name self.i = i self.method = method def __get__(self, obj, tp): if obj is not None: return lambda *args: \ self.method.get_field()(self.i, self.name)(obj, *args) raise AttributeError() class COMInterface(ctypes.Structure): '''Dummy struct to serve as the type of all COM pointers.''' _fields_ = [ ('lpVtbl', ctypes.c_void_p), ] class InterfaceMetaclass(type(ctypes.POINTER(COMInterface))): '''Creates COM interface pointers.''' def __new__(cls, name, bases, dct): methods = [] for base in bases[::-1]: methods.extend(base.__dict__.get('_methods_', ())) methods.extend(dct.get('_methods_', ())) for i, (n, method) in enumerate(methods): dct[n] = COMMethodInstance(n, i, method) dct['_type_'] = COMInterface return super(InterfaceMetaclass, cls).__new__(cls, name, bases, dct) class Interface(ctypes.POINTER(COMInterface)): '''Base COM interface pointer.''' __metaclass__ = InterfaceMetaclass class IUnknown(Interface): _methods_ = [ ('QueryInterface', STDMETHOD(REFIID, ctypes.c_void_p)), ('AddRef', METHOD(ctypes.c_int)), ('Release', METHOD(ctypes.c_int)) ]
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ from pyglet.media import Source, AudioFormat, AudioData import ctypes import os import math class ProceduralSource(Source): def __init__(self, duration, sample_rate=44800, sample_size=16): self._duration = float(duration) self.audio_format = AudioFormat( channels=1, sample_size=sample_size, sample_rate=sample_rate) self._offset = 0 self._bytes_per_sample = sample_size >> 3 self._bytes_per_second = self._bytes_per_sample * sample_rate self._max_offset = int(self._bytes_per_second * self._duration) if self._bytes_per_sample == 2: self._max_offset &= 0xfffffffe def _get_audio_data(self, bytes): bytes = min(bytes, self._max_offset - self._offset) if bytes <= 0: return None timestamp = float(self._offset) / self._bytes_per_second duration = float(bytes) / self._bytes_per_second data = self._generate_data(bytes, self._offset) self._offset += bytes return AudioData(data, bytes, timestamp, duration, []) def _generate_data(self, bytes, offset): '''Generate `bytes` bytes of data. Return data as ctypes array or string. ''' raise NotImplementedError('abstract') def seek(self, timestamp): self._offset = int(timestamp * self._bytes_per_second) # Bound within duration self._offset = min(max(self._offset, 0), self._max_offset) # Align to sample if self._bytes_per_sample == 2: self._offset &= 0xfffffffe class Silence(ProceduralSource): def _generate_data(self, bytes, offset): if self._bytes_per_sample == 1: return '\127' * bytes else: return '\0' * bytes class WhiteNoise(ProceduralSource): def _generate_data(self, bytes, offset): return os.urandom(bytes) class Sine(ProceduralSource): def __init__(self, duration, frequency=440, **kwargs): super(Sine, self).__init__(duration, **kwargs) self.frequency = frequency def _generate_data(self, bytes, offset): if self._bytes_per_sample == 1: start = offset samples = bytes bias = 127 amplitude = 127 data = (ctypes.c_ubyte * samples)() else: start = offset >> 1 samples = bytes >> 1 bias = 0 amplitude = 32767 data = (ctypes.c_short * samples)() step = self.frequency * (math.pi * 2) / self.audio_format.sample_rate for i in range(samples): data[i] = int(math.sin(step * (i + start)) * amplitude + bias) return data class Saw(ProceduralSource): def __init__(self, duration, frequency=440, **kwargs): super(Saw, self).__init__(duration, **kwargs) self.frequency = frequency def _generate_data(self, bytes, offset): # XXX TODO consider offset if self._bytes_per_sample == 1: samples = bytes value = 127 max = 255 min = 0 data = (ctypes.c_ubyte * samples)() else: samples = bytes >> 1 value = 0 max = 32767 min = -32768 data = (ctypes.c_short * samples)() step = (max - min) * 2 * self.frequency / self.audio_format.sample_rate for i in range(samples): value += step if value > max: value = max - (value - max) step = -step if value < min: value = min - (value - min) step = -step data[i] = value return data class Square(ProceduralSource): def __init__(self, duration, frequency=440, **kwargs): super(Square, self).__init__(duration, **kwargs) self.frequency = frequency def _generate_data(self, bytes, offset): # XXX TODO consider offset if self._bytes_per_sample == 1: samples = bytes value = 0 amplitude = 255 data = (ctypes.c_ubyte * samples)() else: samples = bytes >> 1 value = -32768 amplitude = 65535 data = (ctypes.c_short * samples)() period = self.audio_format.sample_rate / self.frequency / 2 count = 0 for i in range(samples): count += 1 if count == period: value = amplitude - value count = 0 data[i] = value return data
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Simple Python-only RIFF reader, supports uncompressed WAV files. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' # RIFF reference: # http://www.saettler.com/RIFFMCI/riffmci.html # # More readable WAVE summaries: # # http://www.borg.com/~jglatt/tech/wave.htm # http://www.sonicspot.com/guide/wavefiles.html from pyglet.media import StreamingSource, AudioData, AudioFormat from pyglet.media import MediaFormatException from pyglet.compat import BytesIO, asbytes import struct WAVE_FORMAT_PCM = 0x0001 IBM_FORMAT_MULAW = 0x0101 IBM_FORMAT_ALAW = 0x0102 IBM_FORMAT_ADPCM = 0x0103 class RIFFFormatException(MediaFormatException): pass class WAVEFormatException(RIFFFormatException): pass class RIFFChunk(object): header_fmt = '<4sL' header_length = struct.calcsize(header_fmt) def __init__(self, file, name, length, offset): self.file = file self.name = name self.length = length self.offset = offset def get_data(self): self.file.seek(self.offset) return self.file.read(self.length) def __repr__(self): return '%s(%r, offset=%r, length=%r)' % ( self.__class__.__name__, self.name, self.offset, self.length) class RIFFForm(object): _chunks = None def __init__(self, file, offset): self.file = file self.offset = offset def get_chunks(self): if self._chunks: return self._chunks self._chunks = [] self.file.seek(self.offset) offset = self.offset while True: header = self.file.read(RIFFChunk.header_length) if not header: break name, length = struct.unpack(RIFFChunk.header_fmt, header) offset += RIFFChunk.header_length cls = self._chunk_types.get(name, RIFFChunk) chunk = cls(self.file, name, length, offset) self._chunks.append(chunk) offset += length if offset & 0x3 != 0: offset = (offset | 0x3) + 1 self.file.seek(offset) return self._chunks def __repr__(self): return '%s(offset=%r)' % (self.__class__.__name__, self.offset) class RIFFType(RIFFChunk): def __init__(self, *args, **kwargs): super(RIFFType, self).__init__(*args, **kwargs) self.file.seek(self.offset) form = self.file.read(4) if form != asbytes('WAVE'): raise RIFFFormatException('Unsupported RIFF form "%s"' % form) self.form = WaveForm(self.file, self.offset + 4) class RIFFFile(RIFFForm): _chunk_types = { asbytes('RIFF'): RIFFType, } def __init__(self, file): if not hasattr(file, 'seek'): file = BytesIO(file.read()) super(RIFFFile, self).__init__(file, 0) def get_wave_form(self): chunks = self.get_chunks() if len(chunks) == 1 and isinstance(chunks[0], RIFFType): return chunks[0].form class WaveFormatChunk(RIFFChunk): def __init__(self, *args, **kwargs): super(WaveFormatChunk, self).__init__(*args, **kwargs) fmt = '<HHLLHH' if struct.calcsize(fmt) != self.length: raise RIFFFormatException('Size of format chunk is incorrect.') (self.wFormatTag, self.wChannels, self.dwSamplesPerSec, self.dwAvgBytesPerSec, self.wBlockAlign, self.wBitsPerSample) = struct.unpack(fmt, self.get_data()) class WaveDataChunk(RIFFChunk): pass class WaveForm(RIFFForm): _chunk_types = { asbytes('fmt '): WaveFormatChunk, asbytes('data'): WaveDataChunk } def get_format_chunk(self): for chunk in self.get_chunks(): if isinstance(chunk, WaveFormatChunk): return chunk def get_data_chunk(self): for chunk in self.get_chunks(): if isinstance(chunk, WaveDataChunk): return chunk class WaveSource(StreamingSource): def __init__(self, filename, file=None): if file is None: file = open(filename, 'rb') self._file = file # Read RIFF format, get format and data chunks riff = RIFFFile(file) wave_form = riff.get_wave_form() if wave_form: format = wave_form.get_format_chunk() data_chunk = wave_form.get_data_chunk() if not wave_form or not format or not data_chunk: if not filename or filename.lower().endswith('.wav'): raise WAVEFormatException('Not a WAVE file') else: raise WAVEFormatException( 'AVbin is required to decode compressed media') if format.wFormatTag != WAVE_FORMAT_PCM: raise WAVEFormatException('Unsupported WAVE format category') if format.wBitsPerSample not in (8, 16): raise WAVEFormatException('Unsupported sample bit size: %d' % format.wBitsPerSample) self.audio_format = AudioFormat( channels=format.wChannels, sample_size=format.wBitsPerSample, sample_rate=format.dwSamplesPerSec) self._duration = \ float(data_chunk.length) / self.audio_format.bytes_per_second self._start_offset = data_chunk.offset self._max_offset = data_chunk.length self._offset = 0 self._file.seek(self._start_offset) def get_audio_data(self, bytes): bytes = min(bytes, self._max_offset - self._offset) if not bytes: return None data = self._file.read(bytes) self._offset += len(data) timestamp = float(self._offset) / self.audio_format.bytes_per_second duration = float(bytes) / self.audio_format.bytes_per_second return AudioData(data, len(data), timestamp, duration, []) def seek(self, timestamp): offset = int(timestamp * self.audio_format.bytes_per_second) # Bound within duration offset = min(max(offset, 0), self._max_offset) # Align to sample if self.audio_format.bytes_per_sample == 2: offset &= 0xfffffffe elif self.audio_format.bytes_per_sample == 4: offset &= 0xfffffffc self._file.seek(offset + self._start_offset) self._offset = offset
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Use avbin to decode audio and video media. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import sys import struct import ctypes import threading import time import pyglet from pyglet import gl from pyglet.gl import gl_info from pyglet import image import pyglet.lib from pyglet.media import \ MediaFormatException, StreamingSource, VideoFormat, AudioFormat, \ AudioData, MediaEvent, WorkerThread, SourceInfo from pyglet.compat import asbytes, asbytes_filename if sys.platform.startswith('win') and struct.calcsize('P') == 8: av = 'avbin64' else: av = 'avbin' av = pyglet.lib.load_library(av, darwin='/usr/local/lib/libavbin.dylib') AVBIN_RESULT_ERROR = -1 AVBIN_RESULT_OK = 0 AVbinResult = ctypes.c_int AVBIN_STREAM_TYPE_UNKNOWN = 0 AVBIN_STREAM_TYPE_VIDEO = 1 AVBIN_STREAM_TYPE_AUDIO = 2 AVbinStreamType = ctypes.c_int AVBIN_SAMPLE_FORMAT_U8 = 0 AVBIN_SAMPLE_FORMAT_S16 = 1 AVBIN_SAMPLE_FORMAT_S24 = 2 AVBIN_SAMPLE_FORMAT_S32 = 3 AVBIN_SAMPLE_FORMAT_FLOAT = 4 AVbinSampleFormat = ctypes.c_int AVBIN_LOG_QUIET = -8 AVBIN_LOG_PANIC = 0 AVBIN_LOG_FATAL = 8 AVBIN_LOG_ERROR = 16 AVBIN_LOG_WARNING = 24 AVBIN_LOG_INFO = 32 AVBIN_LOG_VERBOSE = 40 AVBIN_LOG_DEBUG = 48 AVbinLogLevel = ctypes.c_int AVbinFileP = ctypes.c_void_p AVbinStreamP = ctypes.c_void_p Timestamp = ctypes.c_int64 class AVbinFileInfo(ctypes.Structure): _fields_ = [ ('structure_size', ctypes.c_size_t), ('n_streams', ctypes.c_int), ('start_time', Timestamp), ('duration', Timestamp), ('title', ctypes.c_char * 512), ('author', ctypes.c_char * 512), ('copyright', ctypes.c_char * 512), ('comment', ctypes.c_char * 512), ('album', ctypes.c_char * 512), ('year', ctypes.c_int), ('track', ctypes.c_int), ('genre', ctypes.c_char * 32), ] class _AVbinStreamInfoVideo8(ctypes.Structure): _fields_ = [ ('width', ctypes.c_uint), ('height', ctypes.c_uint), ('sample_aspect_num', ctypes.c_uint), ('sample_aspect_den', ctypes.c_uint), ('frame_rate_num', ctypes.c_uint), ('frame_rate_den', ctypes.c_uint), ] class _AVbinStreamInfoAudio8(ctypes.Structure): _fields_ = [ ('sample_format', ctypes.c_int), ('sample_rate', ctypes.c_uint), ('sample_bits', ctypes.c_uint), ('channels', ctypes.c_uint), ] class _AVbinStreamInfoUnion8(ctypes.Union): _fields_ = [ ('video', _AVbinStreamInfoVideo8), ('audio', _AVbinStreamInfoAudio8), ] class AVbinStreamInfo8(ctypes.Structure): _fields_ = [ ('structure_size', ctypes.c_size_t), ('type', ctypes.c_int), ('u', _AVbinStreamInfoUnion8) ] class AVbinPacket(ctypes.Structure): _fields_ = [ ('structure_size', ctypes.c_size_t), ('timestamp', Timestamp), ('stream_index', ctypes.c_int), ('data', ctypes.POINTER(ctypes.c_uint8)), ('size', ctypes.c_size_t), ] AVbinLogCallback = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p) av.avbin_get_version.restype = ctypes.c_int av.avbin_get_ffmpeg_revision.restype = ctypes.c_int av.avbin_get_audio_buffer_size.restype = ctypes.c_size_t av.avbin_have_feature.restype = ctypes.c_int av.avbin_have_feature.argtypes = [ctypes.c_char_p] av.avbin_init.restype = AVbinResult av.avbin_set_log_level.restype = AVbinResult av.avbin_set_log_level.argtypes = [AVbinLogLevel] av.avbin_set_log_callback.argtypes = [AVbinLogCallback] av.avbin_open_filename.restype = AVbinFileP av.avbin_open_filename.argtypes = [ctypes.c_char_p] av.avbin_close_file.argtypes = [AVbinFileP] av.avbin_seek_file.argtypes = [AVbinFileP, Timestamp] av.avbin_file_info.argtypes = [AVbinFileP, ctypes.POINTER(AVbinFileInfo)] av.avbin_stream_info.argtypes = [AVbinFileP, ctypes.c_int, ctypes.POINTER(AVbinStreamInfo8)] av.avbin_open_stream.restype = ctypes.c_void_p av.avbin_open_stream.argtypes = [AVbinFileP, ctypes.c_int] av.avbin_close_stream.argtypes = [AVbinStreamP] av.avbin_read.argtypes = [AVbinFileP, ctypes.POINTER(AVbinPacket)] av.avbin_read.restype = AVbinResult av.avbin_decode_audio.restype = ctypes.c_int av.avbin_decode_audio.argtypes = [AVbinStreamP, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)] av.avbin_decode_video.restype = ctypes.c_int av.avbin_decode_video.argtypes = [AVbinStreamP, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p] if True: # XXX lock all avbin calls. not clear from ffmpeg documentation if this # is necessary. leaving it on while debugging to rule out the possiblity # of a problem. def synchronize(func, lock): def f(*args): lock.acquire() result = func(*args) lock.release() return result return f _avbin_lock = threading.Lock() for name in dir(av): if name.startswith('avbin_'): setattr(av, name, synchronize(getattr(av, name), _avbin_lock)) def get_version(): return av.avbin_get_version() class AVbinException(MediaFormatException): pass def timestamp_from_avbin(timestamp): return float(timestamp) / 1000000 def timestamp_to_avbin(timestamp): return int(timestamp * 1000000) class VideoPacket(object): _next_id = 0 def __init__(self, packet): self.timestamp = timestamp_from_avbin(packet.timestamp) self.data = (ctypes.c_uint8 * packet.size)() self.size = packet.size ctypes.memmove(self.data, packet.data, self.size) # Decoded image. 0 == not decoded yet; None == Error or discarded self.image = 0 self.id = self._next_id self.__class__._next_id += 1 class AVbinSource(StreamingSource): def __init__(self, filename, file=None): if file is not None: raise NotImplementedError('TODO: Load from file stream') self._file = av.avbin_open_filename(asbytes_filename(filename)) if not self._file: raise AVbinException('Could not open "%s"' % filename) self._video_stream = None self._video_stream_index = -1 self._audio_stream = None self._audio_stream_index = -1 file_info = AVbinFileInfo() file_info.structure_size = ctypes.sizeof(file_info) av.avbin_file_info(self._file, ctypes.byref(file_info)) self._duration = timestamp_from_avbin(file_info.duration) self.info = SourceInfo() self.info.title = file_info.title self.info.author = file_info.author self.info.copyright = file_info.copyright self.info.comment = file_info.comment self.info.album = file_info.album self.info.year = file_info.year self.info.track = file_info.track self.info.genre = file_info.genre # Pick the first video and audio streams found, ignore others. for i in range(file_info.n_streams): info = AVbinStreamInfo8() info.structure_size = ctypes.sizeof(info) av.avbin_stream_info(self._file, i, info) if (info.type == AVBIN_STREAM_TYPE_VIDEO and not self._video_stream): stream = av.avbin_open_stream(self._file, i) if not stream: continue self.video_format = VideoFormat( width=info.u.video.width, height=info.u.video.height) if info.u.video.sample_aspect_num != 0: self.video_format.sample_aspect = ( float(info.u.video.sample_aspect_num) / info.u.video.sample_aspect_den) if _have_frame_rate: self.video_format.frame_rate = ( float(info.u.video.frame_rate_num) / info.u.video.frame_rate_den) self._video_stream = stream self._video_stream_index = i elif (info.type == AVBIN_STREAM_TYPE_AUDIO and info.u.audio.sample_bits in (8, 16) and info.u.audio.channels in (1, 2) and not self._audio_stream): stream = av.avbin_open_stream(self._file, i) if not stream: continue self.audio_format = AudioFormat( channels=info.u.audio.channels, sample_size=info.u.audio.sample_bits, sample_rate=info.u.audio.sample_rate) self._audio_stream = stream self._audio_stream_index = i self._packet = AVbinPacket() self._packet.structure_size = ctypes.sizeof(self._packet) self._packet.stream_index = -1 self._events = [] # Timestamp of last video packet added to decoder queue. self._video_timestamp = 0 self._buffered_audio_data = [] if self.audio_format: self._audio_buffer = \ (ctypes.c_uint8 * av.avbin_get_audio_buffer_size())() if self.video_format: self._video_packets = [] self._decode_thread = WorkerThread() self._decode_thread.start() self._condition = threading.Condition() def __del__(self): if _debug: print 'del avbin source' try: if self._video_stream: av.avbin_close_stream(self._video_stream) if self._audio_stream: av.avbin_close_stream(self._audio_stream) av.avbin_close_file(self._file) except: pass # XXX TODO call this / add to source api def delete(self): if self.video_format: self._decode_thread.stop() def seek(self, timestamp): if _debug: print 'AVbin seek', timestamp av.avbin_seek_file(self._file, timestamp_to_avbin(timestamp)) self._audio_packet_size = 0 del self._events[:] del self._buffered_audio_data[:] if self.video_format: self._video_timestamp = 0 self._condition.acquire() for packet in self._video_packets: packet.image = None self._condition.notify() self._condition.release() del self._video_packets[:] self._decode_thread.clear_jobs() def _get_packet(self): # Read a packet into self._packet. Returns True if OK, False if no # more packets are in stream. return av.avbin_read(self._file, self._packet) == AVBIN_RESULT_OK def _process_packet(self): # Returns (packet_type, packet), where packet_type = 'video' or # 'audio'; and packet is VideoPacket or AudioData. In either case, # packet is buffered or queued for decoding; no further action is # necessary. Returns (None, None) if packet was neither type. if self._packet.stream_index == self._video_stream_index: if self._packet.timestamp < 0: # XXX TODO # AVbin needs hack to decode timestamp for B frames in # some containers (OGG?). See # http://www.dranger.com/ffmpeg/tutorial05.html # For now we just drop these frames. return None, None video_packet = VideoPacket(self._packet) if _debug: print 'Created and queued frame %d (%f)' % \ (video_packet.id, video_packet.timestamp) self._video_timestamp = max(self._video_timestamp, video_packet.timestamp) self._video_packets.append(video_packet) self._decode_thread.put_job( lambda: self._decode_video_packet(video_packet)) return 'video', video_packet elif self._packet.stream_index == self._audio_stream_index: audio_data = self._decode_audio_packet() if audio_data: if _debug: print 'Got an audio packet at', audio_data.timestamp self._buffered_audio_data.append(audio_data) return 'audio', audio_data return None, None def get_audio_data(self, bytes): try: audio_data = self._buffered_audio_data.pop(0) audio_data_timeend = audio_data.timestamp + audio_data.duration except IndexError: audio_data = None audio_data_timeend = self._video_timestamp + 1 if _debug: print 'get_audio_data' have_video_work = False # Keep reading packets until we have an audio packet and all the # associated video packets have been enqueued on the decoder thread. while not audio_data or ( self._video_stream and self._video_timestamp < audio_data_timeend): if not self._get_packet(): break packet_type, packet = self._process_packet() if packet_type == 'video': have_video_work = True elif not audio_data and packet_type == 'audio': audio_data = self._buffered_audio_data.pop(0) if _debug: print 'Got requested audio packet at', audio_data.timestamp audio_data_timeend = audio_data.timestamp + audio_data.duration if have_video_work: # Give decoder thread a chance to run before we return this audio # data. time.sleep(0) if not audio_data: if _debug: print 'get_audio_data returning None' return None while self._events and self._events[0].timestamp <= audio_data_timeend: event = self._events.pop(0) if event.timestamp >= audio_data.timestamp: event.timestamp -= audio_data.timestamp audio_data.events.append(event) if _debug: print 'get_audio_data returning ts %f with events' % \ audio_data.timestamp, audio_data.events print 'remaining events are', self._events return audio_data def _decode_audio_packet(self): packet = self._packet size_out = ctypes.c_int(len(self._audio_buffer)) while True: audio_packet_ptr = ctypes.cast(packet.data, ctypes.c_void_p) audio_packet_size = packet.size used = av.avbin_decode_audio(self._audio_stream, audio_packet_ptr, audio_packet_size, self._audio_buffer, size_out) if used < 0: self._audio_packet_size = 0 break audio_packet_ptr.value += used audio_packet_size -= used if size_out.value <= 0: continue # XXX how did this ever work? replaced with copy below # buffer = ctypes.string_at(self._audio_buffer, size_out) # XXX to actually copy the data.. but it never used to crash, so # maybe I'm missing something buffer = ctypes.create_string_buffer(size_out.value) ctypes.memmove(buffer, self._audio_buffer, len(buffer)) buffer = buffer.raw duration = float(len(buffer)) / self.audio_format.bytes_per_second self._audio_packet_timestamp = \ timestamp = timestamp_from_avbin(packet.timestamp) return AudioData(buffer, len(buffer), timestamp, duration, []) def _decode_video_packet(self, packet): width = self.video_format.width height = self.video_format.height pitch = width * 3 buffer = (ctypes.c_uint8 * (pitch * height))() result = av.avbin_decode_video(self._video_stream, packet.data, packet.size, buffer) if result < 0: image_data = None else: image_data = image.ImageData(width, height, 'RGB', buffer, pitch) packet.image = image_data # Notify get_next_video_frame() that another one is ready. self._condition.acquire() self._condition.notify() self._condition.release() def _ensure_video_packets(self): '''Process packets until a video packet has been queued (and begun decoding). Return False if EOS. ''' if not self._video_packets: if _debug: print 'No video packets...' # Read ahead until we have another video packet self._get_packet() packet_type, _ = self._process_packet() while packet_type and packet_type != 'video': self._get_packet() packet_type, _ = self._process_packet() if not packet_type: return False if _debug: print 'Queued packet', _ return True def get_next_video_timestamp(self): if not self.video_format: return if self._ensure_video_packets(): if _debug: print 'Next video timestamp is', self._video_packets[0].timestamp return self._video_packets[0].timestamp def get_next_video_frame(self): if not self.video_format: return if self._ensure_video_packets(): packet = self._video_packets.pop(0) if _debug: print 'Waiting for', packet # Block until decoding is complete self._condition.acquire() while packet.image == 0: self._condition.wait() self._condition.release() if _debug: print 'Returning', packet return packet.image av.avbin_init() if pyglet.options['debug_media']: _debug = True av.avbin_set_log_level(AVBIN_LOG_DEBUG) else: _debug = False av.avbin_set_log_level(AVBIN_LOG_QUIET) _have_frame_rate = av.avbin_have_feature(asbytes('frame_rate'))
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import time from pyglet.media import AbstractAudioPlayer, AbstractAudioDriver, \ MediaThread, MediaEvent import pyglet _debug = pyglet.options['debug_media'] class SilentAudioPacket(object): def __init__(self, timestamp, duration): self.timestamp = timestamp self.duration = duration def consume(self, dt): self.timestamp += dt self.duration -= dt class SilentAudioPlayerPacketConsumer(AbstractAudioPlayer): # When playing video, length of audio (in secs) to buffer ahead. _buffer_time = 0.4 # Minimum number of bytes to request from source _min_update_bytes = 1024 # Maximum sleep time _sleep_time = 0.2 def __init__(self, source_group, player): super(SilentAudioPlayerPacketConsumer, self).__init__(source_group, player) # System time of first timestamp self._timestamp_time = None # List of buffered SilentAudioPacket self._packets = [] self._packets_duration = 0 self._events = [] # Actual play state. self._playing = False # TODO Be nice to avoid creating this thread if user doesn't care # about EOS events and there's no video format. # NOTE Use thread.condition as lock for all instance vars used by worker self._thread = MediaThread(target=self._worker_func) if source_group.audio_format: self._thread.start() def delete(self): if _debug: print 'SilentAudioPlayer.delete' self._thread.stop() def play(self): if _debug: print 'SilentAudioPlayer.play' self._thread.condition.acquire() if not self._playing: self._playing = True self._timestamp_time = time.time() self._thread.condition.notify() self._thread.condition.release() def stop(self): if _debug: print 'SilentAudioPlayer.stop' self._thread.condition.acquire() if self._playing: timestamp = self.get_time() if self._packets: packet = self._packets[0] self._packets_duration -= timestamp - packet.timestamp packet.consume(timestamp - packet.timestamp) self._playing = False self._thread.condition.release() def clear(self): if _debug: print 'SilentAudioPlayer.clear' self._thread.condition.acquire() del self._packets[:] self._packets_duration = 0 del self._events[:] self._thread.condition.release() def get_time(self): if _debug: print 'SilentAudioPlayer.get_time()' self._thread.condition.acquire() packets = self._packets if self._playing: # Consume timestamps result = None offset = time.time() - self._timestamp_time while packets: packet = packets[0] if offset > packet.duration: del packets[0] self._timestamp_time += packet.duration offset -= packet.duration self._packets_duration -= packet.duration else: packet.consume(offset) self._packets_duration -= offset self._timestamp_time += offset result = packet.timestamp break else: # Paused if packets: result = packets[0].timestamp else: result = None self._thread.condition.release() if _debug: print 'SilentAudioPlayer.get_time() -> ', result return result # Worker func that consumes audio data and dispatches events def _worker_func(self): thread = self._thread #buffered_time = 0 eos = False events = self._events while True: thread.condition.acquire() if thread.stopped or (eos and not events): thread.condition.release() break # Use up "buffered" audio based on amount of time passed. timestamp = self.get_time() if _debug: print 'timestamp: %r' % timestamp # Dispatch events while events and timestamp is not None: if (events[0].timestamp is None or events[0].timestamp <= timestamp): events[0]._sync_dispatch_to_player(self.player) del events[0] # Calculate how much data to request from source secs = self._buffer_time - self._packets_duration bytes = secs * self.source_group.audio_format.bytes_per_second if _debug: print 'Trying to buffer %d bytes (%r secs)' % (bytes, secs) while bytes > self._min_update_bytes and not eos: # Pull audio data from source audio_data = self.source_group.get_audio_data(int(bytes)) if not audio_data and not eos: events.append(MediaEvent(timestamp, 'on_eos')) events.append(MediaEvent(timestamp, 'on_source_group_eos')) eos = True break # Pretend to buffer audio data, collect events. if self._playing and not self._packets: self._timestamp_time = time.time() self._packets.append(SilentAudioPacket(audio_data.timestamp, audio_data.duration)) self._packets_duration += audio_data.duration for event in audio_data.events: event.timestamp += audio_data.timestamp events.append(event) events.extend(audio_data.events) bytes -= audio_data.length sleep_time = self._sleep_time if not self._playing: sleep_time = None elif events and events[0].timestamp and timestamp: sleep_time = min(sleep_time, events[0].timestamp - timestamp) if _debug: print 'SilentAudioPlayer(Worker).sleep', sleep_time thread.sleep(sleep_time) thread.condition.release() class SilentTimeAudioPlayer(AbstractAudioPlayer): # Note that when using this player (automatic if playing back video with # unsupported audio codec) no events are dispatched (because they are # normally encoded in the audio packet -- so no EOS events are delivered. # This is a design flaw. # # Also, seeking is broken because the timestamps aren't synchronized with # the source group. _time = 0.0 _systime = None def play(self): self._systime = time.time() def stop(self): self._time = self.get_time() self._systime = None def delete(self): pass def clear(self): pass def get_time(self): if self._systime is None: return self._time else: return time.time() - self._systime + self._time class SilentAudioDriver(AbstractAudioDriver): def create_audio_player(self, source_group, player): if source_group.audio_format: return SilentAudioPlayerPacketConsumer(source_group, player) else: return SilentTimeAudioPlayer(source_group, player) def create_audio_driver(): return SilentAudioDriver()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ import ctypes from pyglet import com lib = ctypes.oledll.dsound DWORD = ctypes.c_uint32 LPDWORD = ctypes.POINTER(DWORD) LONG = ctypes.c_long LPLONG = ctypes.POINTER(LONG) WORD = ctypes.c_uint16 HWND = DWORD LPUNKNOWN = ctypes.c_void_p D3DVALUE = ctypes.c_float PD3DVALUE = ctypes.POINTER(D3DVALUE) class D3DVECTOR(ctypes.Structure): _fields_ = [ ('x', ctypes.c_float), ('y', ctypes.c_float), ('z', ctypes.c_float), ] PD3DVECTOR = ctypes.POINTER(D3DVECTOR) class WAVEFORMATEX(ctypes.Structure): _fields_ = [ ('wFormatTag', WORD), ('nChannels', WORD), ('nSamplesPerSec', DWORD), ('nAvgBytesPerSec', DWORD), ('nBlockAlign', WORD), ('wBitsPerSample', WORD), ('cbSize', WORD), ] LPWAVEFORMATEX = ctypes.POINTER(WAVEFORMATEX) WAVE_FORMAT_PCM = 1 class DSCAPS(ctypes.Structure): _fields_ = [ ('dwSize', DWORD), ('dwFlags', DWORD), ('dwMinSecondarySampleRate', DWORD), ('dwMaxSecondarySampleRate', DWORD), ('dwPrimaryBuffers', DWORD), ('dwMaxHwMixingAllBuffers', DWORD), ('dwMaxHwMixingStaticBuffers', DWORD), ('dwMaxHwMixingStreamingBuffers', DWORD), ('dwFreeHwMixingAllBuffers', DWORD), ('dwFreeHwMixingStaticBuffers', DWORD), ('dwFreeHwMixingStreamingBuffers', DWORD), ('dwMaxHw3DAllBuffers', DWORD), ('dwMaxHw3DStaticBuffers', DWORD), ('dwMaxHw3DStreamingBuffers', DWORD), ('dwFreeHw3DAllBuffers', DWORD), ('dwFreeHw3DStaticBuffers', DWORD), ('dwFreeHw3DStreamingBuffers', DWORD), ('dwTotalHwMemBytes', DWORD), ('dwFreeHwMemBytes', DWORD), ('dwMaxContigFreeHwMemBytes', DWORD), ('dwUnlockTransferRateHwBuffers', DWORD), ('dwPlayCpuOverheadSwBuffers', DWORD), ('dwReserved1', DWORD), ('dwReserved2', DWORD) ] LPDSCAPS = ctypes.POINTER(DSCAPS) class DSBCAPS(ctypes.Structure): _fields_ = [ ('dwSize', DWORD), ('dwFlags', DWORD), ('dwBufferBytes', DWORD), ('dwUnlockTransferRate', DWORD), ('dwPlayCpuOverhead', DWORD), ] LPDSBCAPS = ctypes.POINTER(DSBCAPS) class DSBUFFERDESC(ctypes.Structure): _fields_ = [ ('dwSize', DWORD), ('dwFlags', DWORD), ('dwBufferBytes', DWORD), ('dwReserved', DWORD), ('lpwfxFormat', LPWAVEFORMATEX), ] LPDSBUFFERDESC = ctypes.POINTER(DSBUFFERDESC) class DS3DBUFFER(ctypes.Structure): _fields_ = [ ('dwSize', DWORD), ('vPosition', D3DVECTOR), ('vVelocity', D3DVECTOR), ('dwInsideConeAngle', DWORD), ('dwOutsideConeAngle', DWORD), ('vConeOrientation', D3DVECTOR), ('lConeOutsideVolume', LONG), ('flMinDistance', D3DVALUE), ('flMaxDistance', D3DVALUE), ('dwMode', DWORD), ] LPDS3DBUFFER = ctypes.POINTER(DS3DBUFFER) class DS3DLISTENER(ctypes.Structure): _fields_ = [ ('dwSize', DWORD), ('vPosition', D3DVECTOR), ('vVelocity', D3DVECTOR), ('vOrientFront', D3DVECTOR), ('vOrientTop', D3DVECTOR), ('flDistanceFactor', D3DVALUE), ('flRolloffFactor', D3DVALUE), ('flDopplerFactor', D3DVALUE), ] LPDS3DLISTENER = ctypes.POINTER(DS3DLISTENER) class IDirectSoundBuffer(com.IUnknown): _methods_ = [ ('GetCaps', com.STDMETHOD(LPDSBCAPS)), ('GetCurrentPosition', com.STDMETHOD(LPDWORD, LPDWORD)), ('GetFormat', com.STDMETHOD(LPWAVEFORMATEX, DWORD, LPDWORD)), ('GetVolume', com.STDMETHOD(LPLONG)), ('GetPan', com.STDMETHOD(LPLONG)), ('GetFrequency', com.STDMETHOD(LPDWORD)), ('GetStatus', com.STDMETHOD(LPDWORD)), ('Initialize', com.STDMETHOD(ctypes.c_void_p, LPDSBUFFERDESC)), ('Lock', com.STDMETHOD(DWORD, DWORD, ctypes.POINTER(ctypes.c_void_p), LPDWORD, ctypes.POINTER(ctypes.c_void_p), LPDWORD, DWORD)), ('Play', com.STDMETHOD(DWORD, DWORD, DWORD)), ('SetCurrentPosition', com.STDMETHOD(DWORD)), ('SetFormat', com.STDMETHOD(LPWAVEFORMATEX)), ('SetVolume', com.STDMETHOD(LONG)), ('SetPan', com.STDMETHOD(LONG)), ('SetFrequency', com.STDMETHOD(DWORD)), ('Stop', com.STDMETHOD()), ('Unlock', com.STDMETHOD(ctypes.c_void_p, DWORD, ctypes.c_void_p, DWORD)), ('Restore', com.STDMETHOD()), ] IID_IDirectSound3DListener = com.GUID( 0x279AFA84, 0x4981, 0x11CE, 0xA5, 0x21, 0x00, 0x20, 0xAF, 0x0B, 0xE5, 0x60) class IDirectSound3DListener(com.IUnknown): _methods_ = [ ('GetAllParameters', com.STDMETHOD(LPDS3DLISTENER)), ('GetDistanceFactor', com.STDMETHOD(PD3DVALUE)), ('GetDopplerFactor', com.STDMETHOD(PD3DVALUE)), ('GetOrientation', com.STDMETHOD(PD3DVECTOR)), ('GetPosition', com.STDMETHOD(PD3DVECTOR)), ('GetRolloffFactor', com.STDMETHOD(PD3DVALUE)), ('GetVelocity', com.STDMETHOD(PD3DVECTOR)), ('SetAllParameters', com.STDMETHOD(LPDS3DLISTENER)), ('SetDistanceFactor', com.STDMETHOD(D3DVALUE, DWORD)), ('SetDopplerFactor', com.STDMETHOD(D3DVALUE, DWORD)), ('SetOrientation', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ('SetPosition', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ('SetRolloffFactor', com.STDMETHOD(D3DVALUE, DWORD)), ('SetVelocity', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ('CommitDeferredSettings', com.STDMETHOD()), ] IID_IDirectSound3DBuffer = com.GUID( 0x279AFA86, 0x4981, 0x11CE, 0xA5, 0x21, 0x00, 0x20, 0xAF, 0x0B, 0xE5, 0x60) class IDirectSound3DBuffer(com.IUnknown): _methods_ = [ ('GetAllParameters', com.STDMETHOD(LPDS3DBUFFER)), ('GetConeAngles', com.STDMETHOD(LPDWORD, LPDWORD)), ('GetConeOrientation', com.STDMETHOD(PD3DVECTOR)), ('GetConeOutsideVolume', com.STDMETHOD(LPLONG)), ('GetMaxDistance', com.STDMETHOD(PD3DVALUE)), ('GetMinDistance', com.STDMETHOD(PD3DVALUE)), ('GetMode', com.STDMETHOD(LPDWORD)), ('GetPosition', com.STDMETHOD(PD3DVECTOR)), ('GetVelocity', com.STDMETHOD(PD3DVECTOR)), ('SetAllParameters', com.STDMETHOD(LPDS3DBUFFER, DWORD)), ('SetConeAngles', com.STDMETHOD(DWORD, DWORD, DWORD)), ('SetConeOrientation', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ('SetConeOutsideVolume', com.STDMETHOD(LONG, DWORD)), ('SetMaxDistance', com.STDMETHOD(D3DVALUE, DWORD)), ('SetMinDistance', com.STDMETHOD(D3DVALUE, DWORD)), ('SetMode', com.STDMETHOD(DWORD, DWORD)), ('SetPosition', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ('SetVelocity', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ] class IDirectSound(com.IUnknown): _methods_ = [ ('CreateSoundBuffer', com.STDMETHOD(LPDSBUFFERDESC, ctypes.POINTER(IDirectSoundBuffer), LPUNKNOWN)), ('GetCaps', com.STDMETHOD(LPDSCAPS)), ('DuplicateSoundBuffer', com.STDMETHOD(IDirectSoundBuffer, ctypes.POINTER(IDirectSoundBuffer))), ('SetCooperativeLevel', com.STDMETHOD(HWND, DWORD)), ('Compact', com.STDMETHOD()), ('GetSpeakerConfig', com.STDMETHOD(LPDWORD)), ('SetSpeakerConfig', com.STDMETHOD(DWORD)), ('Initialize', com.STDMETHOD(com.LPGUID)), ] _type_ = com.COMInterface DirectSoundCreate = lib.DirectSoundCreate DirectSoundCreate.argtypes = \ [com.LPGUID, ctypes.POINTER(IDirectSound), ctypes.c_void_p] DSCAPS_PRIMARYMONO = 0x00000001 DSCAPS_PRIMARYSTEREO = 0x00000002 DSCAPS_PRIMARY8BIT = 0x00000004 DSCAPS_PRIMARY16BIT = 0x00000008 DSCAPS_CONTINUOUSRATE = 0x00000010 DSCAPS_EMULDRIVER = 0x00000020 DSCAPS_CERTIFIED = 0x00000040 DSCAPS_SECONDARYMONO = 0x00000100 DSCAPS_SECONDARYSTEREO = 0x00000200 DSCAPS_SECONDARY8BIT = 0x00000400 DSCAPS_SECONDARY16BIT = 0x00000800 DSSCL_NORMAL = 0x00000001 DSSCL_PRIORITY = 0x00000002 DSSCL_EXCLUSIVE = 0x00000003 DSSCL_WRITEPRIMARY = 0x00000004 DSSPEAKER_DIRECTOUT = 0x00000000 DSSPEAKER_HEADPHONE = 0x00000001 DSSPEAKER_MONO = 0x00000002 DSSPEAKER_QUAD = 0x00000003 DSSPEAKER_STEREO = 0x00000004 DSSPEAKER_SURROUND = 0x00000005 DSSPEAKER_5POINT1 = 0x00000006 DSSPEAKER_7POINT1 = 0x00000007 DSSPEAKER_GEOMETRY_MIN = 0x00000005 # 5 degrees DSSPEAKER_GEOMETRY_NARROW = 0x0000000A # 10 degrees DSSPEAKER_GEOMETRY_WIDE = 0x00000014 # 20 degrees DSSPEAKER_GEOMETRY_MAX = 0x000000B4 # 180 degrees DSBCAPS_PRIMARYBUFFER = 0x00000001 DSBCAPS_STATIC = 0x00000002 DSBCAPS_LOCHARDWARE = 0x00000004 DSBCAPS_LOCSOFTWARE = 0x00000008 DSBCAPS_CTRL3D = 0x00000010 DSBCAPS_CTRLFREQUENCY = 0x00000020 DSBCAPS_CTRLPAN = 0x00000040 DSBCAPS_CTRLVOLUME = 0x00000080 DSBCAPS_CTRLPOSITIONNOTIFY = 0x00000100 DSBCAPS_CTRLFX = 0x00000200 DSBCAPS_STICKYFOCUS = 0x00004000 DSBCAPS_GLOBALFOCUS = 0x00008000 DSBCAPS_GETCURRENTPOSITION2 = 0x00010000 DSBCAPS_MUTE3DATMAXDISTANCE = 0x00020000 DSBCAPS_LOCDEFER = 0x00040000 DSBPLAY_LOOPING = 0x00000001 DSBPLAY_LOCHARDWARE = 0x00000002 DSBPLAY_LOCSOFTWARE = 0x00000004 DSBPLAY_TERMINATEBY_TIME = 0x00000008 DSBPLAY_TERMINATEBY_DISTANCE = 0x000000010 DSBPLAY_TERMINATEBY_PRIORITY = 0x000000020 DSBSTATUS_PLAYING = 0x00000001 DSBSTATUS_BUFFERLOST = 0x00000002 DSBSTATUS_LOOPING = 0x00000004 DSBSTATUS_LOCHARDWARE = 0x00000008 DSBSTATUS_LOCSOFTWARE = 0x00000010 DSBSTATUS_TERMINATED = 0x00000020 DSBLOCK_FROMWRITECURSOR = 0x00000001 DSBLOCK_ENTIREBUFFER = 0x00000002 DSBFREQUENCY_MIN = 100 DSBFREQUENCY_MAX = 100000 DSBFREQUENCY_ORIGINAL = 0 DSBPAN_LEFT = -10000 DSBPAN_CENTER = 0 DSBPAN_RIGHT = 10000 DSBVOLUME_MIN = -10000 DSBVOLUME_MAX = 0 DSBSIZE_MIN = 4 DSBSIZE_MAX = 0x0FFFFFFF DSBSIZE_FX_MIN = 150 # NOTE: Milliseconds, not bytes DS3DMODE_NORMAL = 0x00000000 DS3DMODE_HEADRELATIVE = 0x00000001 DS3DMODE_DISABLE = 0x00000002 DS3D_IMMEDIATE = 0x00000000 DS3D_DEFERRED = 0x00000001 DS3D_MINDISTANCEFACTOR = -1000000.0 # XXX FLT_MIN DS3D_MAXDISTANCEFACTOR = 1000000.0 # XXX FLT_MAX DS3D_DEFAULTDISTANCEFACTOR = 1.0 DS3D_MINROLLOFFFACTOR = 0.0 DS3D_MAXROLLOFFFACTOR = 10.0 DS3D_DEFAULTROLLOFFFACTOR = 1.0 DS3D_MINDOPPLERFACTOR = 0.0 DS3D_MAXDOPPLERFACTOR = 10.0 DS3D_DEFAULTDOPPLERFACTOR = 1.0 DS3D_DEFAULTMINDISTANCE = 1.0 DS3D_DEFAULTMAXDISTANCE = 1000000000.0 DS3D_MINCONEANGLE = 0 DS3D_MAXCONEANGLE = 360 DS3D_DEFAULTCONEANGLE = 360 DS3D_DEFAULTCONEOUTSIDEVOLUME = DSBVOLUME_MAX
Python
#!/usr/bin/python # $Id:$ import ctypes import math import sys import threading import time import lib_dsound as lib from pyglet.media import MediaException, MediaThread, AbstractAudioDriver, \ AbstractAudioPlayer, MediaEvent from pyglet.window.win32 import _user32, _kernel32 import pyglet _debug = pyglet.options['debug_media'] class DirectSoundException(MediaException): pass def _db(gain): '''Convert linear gain in range [0.0, 1.0] to 100ths of dB.''' if gain <= 0: return -10000 return max(-10000, min(int(1000 * math.log(min(gain, 1))), 0)) class DirectSoundWorker(MediaThread): _min_write_size = 9600 # Time to wait if there are players, but they're all full. _nap_time = 0.05 # Time to wait if there are no players. _sleep_time = None def __init__(self): super(DirectSoundWorker, self).__init__() self.players = set() def run(self): while True: # This is a big lock, but ensures a player is not deleted while # we're processing it -- this saves on extra checks in the # player's methods that would otherwise have to check that it's # still alive. if _debug: print 'DirectSoundWorker run attempt acquire' self.condition.acquire() if _debug: print 'DirectSoundWorker run acquire' if self.stopped: self.condition.release() break sleep_time = -1 if self.players: player = None write_size = 0 for p in self.players: s = p.get_write_size() if s > write_size: player = p write_size = s if write_size > self._min_write_size: player.refill(write_size) else: sleep_time = self._nap_time else: sleep_time = self._sleep_time self.condition.release() if _debug: print 'DirectSoundWorker run release' if sleep_time != -1: self.sleep(sleep_time) if _debug: print 'DirectSoundWorker exiting' def add(self, player): if _debug: print 'DirectSoundWorker add', player self.condition.acquire() self.players.add(player) self.condition.notify() self.condition.release() if _debug: print 'return DirectSoundWorker add', player def remove(self, player): if _debug: print 'DirectSoundWorker remove', player self.condition.acquire() try: self.players.remove(player) except KeyError: pass self.condition.notify() self.condition.release() if _debug: print 'return DirectSoundWorker remove', player class DirectSoundAudioPlayer(AbstractAudioPlayer): # How many bytes the ring buffer should be _buffer_size = 44800 * 1 # Need to cache these because pyglet API allows update separately, but # DSound requires both to be set at once. _cone_inner_angle = 360 _cone_outer_angle = 360 def __init__(self, source_group, player): super(DirectSoundAudioPlayer, self).__init__(source_group, player) # Locking strategy: # All DirectSound calls should be locked. All instance vars relating # to buffering/filling/time/events should be locked (used by both # application and worker thread). Other instance vars (consts and # 3d vars) do not need to be locked. self._lock = threading.RLock() # Desired play state (may be actually paused due to underrun -- not # implemented yet). self._playing = False # Up to one audio data may be buffered if too much data was received # from the source that could not be written immediately into the # buffer. See refill(). self._next_audio_data = None # Theoretical write and play cursors for an infinite buffer. play # cursor is always <= write cursor (when equal, underrun is # happening). self._write_cursor = 0 self._play_cursor = 0 # Cursor position of end of data. Silence is written after # eos for one buffer size. self._eos_cursor = None # Indexes into DSound circular buffer. Complications ensue wrt each # other to avoid writing over the play cursor. See get_write_size and # write(). self._play_cursor_ring = 0 self._write_cursor_ring = 0 # List of (play_cursor, MediaEvent), in sort order self._events = [] # List of (cursor, timestamp), in sort order (cursor gives expiry # place of the timestamp) self._timestamps = [] audio_format = source_group.audio_format wfx = lib.WAVEFORMATEX() wfx.wFormatTag = lib.WAVE_FORMAT_PCM wfx.nChannels = audio_format.channels wfx.nSamplesPerSec = audio_format.sample_rate wfx.wBitsPerSample = audio_format.sample_size wfx.nBlockAlign = wfx.wBitsPerSample * wfx.nChannels // 8 wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign dsbdesc = lib.DSBUFFERDESC() dsbdesc.dwSize = ctypes.sizeof(dsbdesc) dsbdesc.dwFlags = (lib.DSBCAPS_GLOBALFOCUS | lib.DSBCAPS_GETCURRENTPOSITION2 | lib.DSBCAPS_CTRLFREQUENCY | lib.DSBCAPS_CTRLVOLUME) if audio_format.channels == 1: dsbdesc.dwFlags |= lib.DSBCAPS_CTRL3D dsbdesc.dwBufferBytes = self._buffer_size dsbdesc.lpwfxFormat = ctypes.pointer(wfx) # DSound buffer self._buffer = lib.IDirectSoundBuffer() driver._dsound.CreateSoundBuffer(dsbdesc, ctypes.byref(self._buffer), None) if audio_format.channels == 1: self._buffer3d = lib.IDirectSound3DBuffer() self._buffer.QueryInterface(lib.IID_IDirectSound3DBuffer, ctypes.byref(self._buffer3d)) else: self._buffer3d = None self._buffer.SetCurrentPosition(0) self.refill(self._buffer_size) def __del__(self): try: self.delete() except: pass def delete(self): if driver and driver.worker: driver.worker.remove(self) self.lock() self._buffer.Stop() self._buffer.Release() self._buffer = None if self._buffer3d: self._buffer3d.Release() self._buffer3d = None self.unlock() def lock(self): self._lock.acquire() def unlock(self): self._lock.release() def play(self): if _debug: print 'DirectSound play' driver.worker.add(self) self.lock() if not self._playing: self._playing = True self._buffer.Play(0, 0, lib.DSBPLAY_LOOPING) self.unlock() if _debug: print 'return DirectSound play' def stop(self): if _debug: print 'DirectSound stop' driver.worker.remove(self) self.lock() if self._playing: self._playing = False self._buffer.Stop() self.unlock() if _debug: print 'return DirectSound stop' def clear(self): if _debug: print 'DirectSound clear' self.lock() self._buffer.SetCurrentPosition(0) self._play_cursor_ring = self._write_cursor_ring = 0 self._play_cursor = self._write_cursor self._eos_cursor = None self._next_audio_data = None del self._events[:] del self._timestamps[:] self.unlock() def refill(self, write_size): self.lock() while write_size > 0: if _debug: print 'refill, write_size =', write_size # Get next audio packet (or remains of last one) if self._next_audio_data: audio_data = self._next_audio_data self._next_audio_data = None else: audio_data = self.source_group.get_audio_data(write_size) # Write it, or silence if there are no more packets if audio_data: # Add events for event in audio_data.events: event_cursor = self._write_cursor + event.timestamp * \ self.source_group.audio_format.bytes_per_second self._events.append((event_cursor, event)) # Add timestamp (at end of this data packet) ts_cursor = self._write_cursor + audio_data.length self._timestamps.append( (ts_cursor, audio_data.timestamp + audio_data.duration)) # Write data if _debug: print 'write', audio_data.length length = min(write_size, audio_data.length) self.write(audio_data, length) if audio_data.length: self._next_audio_data = audio_data write_size -= length else: # Write silence if self._eos_cursor is None: self._eos_cursor = self._write_cursor self._events.append( (self._eos_cursor, MediaEvent(0, 'on_eos'))) self._events.append( (self._eos_cursor, MediaEvent(0, 'on_source_group_eos'))) self._events.sort() if self._write_cursor > self._eos_cursor + self._buffer_size: self.stop() else: self.write(None, write_size) write_size = 0 self.unlock() def update_play_cursor(self): self.lock() play_cursor_ring = lib.DWORD() self._buffer.GetCurrentPosition(play_cursor_ring, None) if play_cursor_ring.value < self._play_cursor_ring: # Wrapped around self._play_cursor += self._buffer_size - self._play_cursor_ring self._play_cursor_ring = 0 self._play_cursor += play_cursor_ring.value - self._play_cursor_ring self._play_cursor_ring = play_cursor_ring.value # Dispatch pending events pending_events = [] while self._events and self._events[0][0] <= self._play_cursor: _, event = self._events.pop(0) pending_events.append(event) if _debug: print 'Dispatching pending events:', pending_events print 'Remaining events:', self._events # Remove expired timestamps while self._timestamps and self._timestamps[0][0] < self._play_cursor: del self._timestamps[0] self.unlock() for event in pending_events: event._sync_dispatch_to_player(self.player) def get_write_size(self): self.update_play_cursor() self.lock() play_cursor = self._play_cursor write_cursor = self._write_cursor self.unlock() return self._buffer_size - max(write_cursor - play_cursor, 0) def write(self, audio_data, length): # Pass audio_data=None to write silence if length == 0: return 0 self.lock() p1 = ctypes.c_void_p() l1 = lib.DWORD() p2 = ctypes.c_void_p() l2 = lib.DWORD() assert 0 < length <= self._buffer_size self._buffer.Lock(self._write_cursor_ring, length, ctypes.byref(p1), l1, ctypes.byref(p2), l2, 0) assert length == l1.value + l2.value if audio_data: ctypes.memmove(p1, audio_data.data, l1.value) audio_data.consume(l1.value, self.source_group.audio_format) if l2.value: ctypes.memmove(p2, audio_data.data, l2.value) audio_data.consume(l2.value, self.source_group.audio_format) else: ctypes.memset(p1, 0, l1.value) if l2.value: ctypes.memset(p2, 0, l2.value) self._buffer.Unlock(p1, l1, p2, l2) self._write_cursor += length self._write_cursor_ring += length self._write_cursor_ring %= self._buffer_size self.unlock() def get_time(self): self.lock() if self._timestamps: cursor, ts = self._timestamps[0] result = ts + (self._play_cursor - cursor) / \ float(self.source_group.audio_format.bytes_per_second) else: result = None self.unlock() return result def set_volume(self, volume): volume = _db(volume) self.lock() self._buffer.SetVolume(volume) self.unlock() def set_position(self, position): if self._buffer3d: x, y, z = position self.lock() self._buffer3d.SetPosition(x, y, -z, lib.DS3D_IMMEDIATE) self.unlock() def set_min_distance(self, min_distance): if self._buffer3d: self.lock() self._buffer3d.SetMinDistance(min_distance, lib.DS3D_IMMEDIATE) self.unlock() def set_max_distance(self, max_distance): if self._buffer3d: self.lock() self._buffer3d.SetMaxDistance(max_distance, lib.DS3D_IMMEDIATE) self.unlock() def set_pitch(self, pitch): frequency = int(pitch * self.audio_format.sample_rate) self.lock() self._buffer.SetFrequency(frequency) self.unlock() def set_cone_orientation(self, cone_orientation): if self._buffer3d: x, y, z = cone_orientation self.lock() self._buffer3d.SetConeOrientation(x, y, -z, lib.DS3D_IMMEDIATE) self.unlock() def set_cone_inner_angle(self, cone_inner_angle): if self._buffer3d: self._cone_inner_angle = int(cone_inner_angle) self._set_cone_angles() def set_cone_outer_angle(self, cone_outer_angle): if self._buffer3d: self._cone_outer_angle = int(cone_outer_angle) self._set_cone_angles() def _set_cone_angles(self): inner = min(self._cone_inner_angle, self._cone_outer_angle) outer = max(self._cone_inner_angle, self._cone_outer_angle) self.lock() self._buffer3d.SetConeAngles(inner, outer, lib.DS3D_IMMEDIATE) self.unlock() def set_cone_outer_gain(self, cone_outer_gain): if self._buffer3d: volume = _db(cone_outer_gain) self.lock() self._buffer3d.SetConeOutsideVolume(volume, lib.DS3D_IMMEDIATE) self.unlock() class DirectSoundDriver(AbstractAudioDriver): def __init__(self): self._dsound = lib.IDirectSound() lib.DirectSoundCreate(None, ctypes.byref(self._dsound), None) # A trick used by mplayer.. use desktop as window handle since it # would be complex to use pyglet window handles (and what to do when # application is audio only?). hwnd = _user32.GetDesktopWindow() self._dsound.SetCooperativeLevel(hwnd, lib.DSSCL_NORMAL) # Create primary buffer with 3D and volume capabilities self._buffer = lib.IDirectSoundBuffer() dsbd = lib.DSBUFFERDESC() dsbd.dwSize = ctypes.sizeof(dsbd) dsbd.dwFlags = (lib.DSBCAPS_CTRL3D | lib.DSBCAPS_CTRLVOLUME | lib.DSBCAPS_PRIMARYBUFFER) self._dsound.CreateSoundBuffer(dsbd, ctypes.byref(self._buffer), None) # Create listener self._listener = lib.IDirectSound3DListener() self._buffer.QueryInterface(lib.IID_IDirectSound3DListener, ctypes.byref(self._listener)) # Create worker thread self.worker = DirectSoundWorker() self.worker.start() def __del__(self): try: if self._buffer: self.delete() except: pass def create_audio_player(self, source_group, player): return DirectSoundAudioPlayer(source_group, player) def delete(self): self.worker.stop() self._buffer.Release() self._buffer = None self._listener.Release() self._listener = None # Listener API def _set_volume(self, volume): self._volume = volume self._buffer.SetVolume(_db(volume)) def _set_position(self, position): self._position = position x, y, z = position self._listener.SetPosition(x, y, -z, lib.DS3D_IMMEDIATE) def _set_forward_orientation(self, orientation): self._forward_orientation = orientation self._set_orientation() def _set_up_orientation(self, orientation): self._up_orientation = orientation self._set_orientation() def _set_orientation(self): x, y, z = self._forward_orientation ux, uy, uz = self._up_orientation self._listener.SetOrientation(x, y, -z, ux, uy, -uz, lib.DS3D_IMMEDIATE) def create_audio_driver(): global driver driver = DirectSoundDriver() return driver # Global driver needed for access to worker thread and _dsound driver = None
Python
#!/usr/bin/python # $Id:$ import ctypes import math import sys import threading import time import lib_dsound as lib from pyglet.media import MediaException, MediaThread, AbstractAudioDriver, \ AbstractAudioPlayer, MediaEvent from pyglet.window.win32 import _user32, _kernel32 import pyglet _debug = pyglet.options['debug_media'] class DirectSoundException(MediaException): pass def _db(gain): '''Convert linear gain in range [0.0, 1.0] to 100ths of dB.''' if gain <= 0: return -10000 return max(-10000, min(int(1000 * math.log(min(gain, 1))), 0)) class DirectSoundWorker(MediaThread): _min_write_size = 9600 # Time to wait if there are players, but they're all full. _nap_time = 0.05 # Time to wait if there are no players. _sleep_time = None def __init__(self): super(DirectSoundWorker, self).__init__() self.players = set() def run(self): while True: # This is a big lock, but ensures a player is not deleted while # we're processing it -- this saves on extra checks in the # player's methods that would otherwise have to check that it's # still alive. if _debug: print 'DirectSoundWorker run attempt acquire' self.condition.acquire() if _debug: print 'DirectSoundWorker run acquire' if self.stopped: self.condition.release() break sleep_time = -1 if self.players: player = None write_size = 0 for p in self.players: s = p.get_write_size() if s > write_size: player = p write_size = s if write_size > self._min_write_size: player.refill(write_size) else: sleep_time = self._nap_time else: sleep_time = self._sleep_time self.condition.release() if _debug: print 'DirectSoundWorker run release' if sleep_time != -1: self.sleep(sleep_time) if _debug: print 'DirectSoundWorker exiting' def add(self, player): if _debug: print 'DirectSoundWorker add', player self.condition.acquire() self.players.add(player) self.condition.notify() self.condition.release() if _debug: print 'return DirectSoundWorker add', player def remove(self, player): if _debug: print 'DirectSoundWorker remove', player self.condition.acquire() try: self.players.remove(player) except KeyError: pass self.condition.notify() self.condition.release() if _debug: print 'return DirectSoundWorker remove', player class DirectSoundAudioPlayer(AbstractAudioPlayer): # How many bytes the ring buffer should be _buffer_size = 44800 * 1 # Need to cache these because pyglet API allows update separately, but # DSound requires both to be set at once. _cone_inner_angle = 360 _cone_outer_angle = 360 def __init__(self, source_group, player): super(DirectSoundAudioPlayer, self).__init__(source_group, player) # Locking strategy: # All DirectSound calls should be locked. All instance vars relating # to buffering/filling/time/events should be locked (used by both # application and worker thread). Other instance vars (consts and # 3d vars) do not need to be locked. self._lock = threading.RLock() # Desired play state (may be actually paused due to underrun -- not # implemented yet). self._playing = False # Up to one audio data may be buffered if too much data was received # from the source that could not be written immediately into the # buffer. See refill(). self._next_audio_data = None # Theoretical write and play cursors for an infinite buffer. play # cursor is always <= write cursor (when equal, underrun is # happening). self._write_cursor = 0 self._play_cursor = 0 # Cursor position of end of data. Silence is written after # eos for one buffer size. self._eos_cursor = None # Indexes into DSound circular buffer. Complications ensue wrt each # other to avoid writing over the play cursor. See get_write_size and # write(). self._play_cursor_ring = 0 self._write_cursor_ring = 0 # List of (play_cursor, MediaEvent), in sort order self._events = [] # List of (cursor, timestamp), in sort order (cursor gives expiry # place of the timestamp) self._timestamps = [] audio_format = source_group.audio_format wfx = lib.WAVEFORMATEX() wfx.wFormatTag = lib.WAVE_FORMAT_PCM wfx.nChannels = audio_format.channels wfx.nSamplesPerSec = audio_format.sample_rate wfx.wBitsPerSample = audio_format.sample_size wfx.nBlockAlign = wfx.wBitsPerSample * wfx.nChannels // 8 wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign dsbdesc = lib.DSBUFFERDESC() dsbdesc.dwSize = ctypes.sizeof(dsbdesc) dsbdesc.dwFlags = (lib.DSBCAPS_GLOBALFOCUS | lib.DSBCAPS_GETCURRENTPOSITION2 | lib.DSBCAPS_CTRLFREQUENCY | lib.DSBCAPS_CTRLVOLUME) if audio_format.channels == 1: dsbdesc.dwFlags |= lib.DSBCAPS_CTRL3D dsbdesc.dwBufferBytes = self._buffer_size dsbdesc.lpwfxFormat = ctypes.pointer(wfx) # DSound buffer self._buffer = lib.IDirectSoundBuffer() driver._dsound.CreateSoundBuffer(dsbdesc, ctypes.byref(self._buffer), None) if audio_format.channels == 1: self._buffer3d = lib.IDirectSound3DBuffer() self._buffer.QueryInterface(lib.IID_IDirectSound3DBuffer, ctypes.byref(self._buffer3d)) else: self._buffer3d = None self._buffer.SetCurrentPosition(0) self.refill(self._buffer_size) def __del__(self): try: self.delete() except: pass def delete(self): if driver and driver.worker: driver.worker.remove(self) self.lock() self._buffer.Stop() self._buffer.Release() self._buffer = None if self._buffer3d: self._buffer3d.Release() self._buffer3d = None self.unlock() def lock(self): self._lock.acquire() def unlock(self): self._lock.release() def play(self): if _debug: print 'DirectSound play' driver.worker.add(self) self.lock() if not self._playing: self._playing = True self._buffer.Play(0, 0, lib.DSBPLAY_LOOPING) self.unlock() if _debug: print 'return DirectSound play' def stop(self): if _debug: print 'DirectSound stop' driver.worker.remove(self) self.lock() if self._playing: self._playing = False self._buffer.Stop() self.unlock() if _debug: print 'return DirectSound stop' def clear(self): if _debug: print 'DirectSound clear' self.lock() self._buffer.SetCurrentPosition(0) self._play_cursor_ring = self._write_cursor_ring = 0 self._play_cursor = self._write_cursor self._eos_cursor = None self._next_audio_data = None del self._events[:] del self._timestamps[:] self.unlock() def refill(self, write_size): self.lock() while write_size > 0: if _debug: print 'refill, write_size =', write_size # Get next audio packet (or remains of last one) if self._next_audio_data: audio_data = self._next_audio_data self._next_audio_data = None else: audio_data = self.source_group.get_audio_data(write_size) # Write it, or silence if there are no more packets if audio_data: # Add events for event in audio_data.events: event_cursor = self._write_cursor + event.timestamp * \ self.source_group.audio_format.bytes_per_second self._events.append((event_cursor, event)) # Add timestamp (at end of this data packet) ts_cursor = self._write_cursor + audio_data.length self._timestamps.append( (ts_cursor, audio_data.timestamp + audio_data.duration)) # Write data if _debug: print 'write', audio_data.length length = min(write_size, audio_data.length) self.write(audio_data, length) if audio_data.length: self._next_audio_data = audio_data write_size -= length else: # Write silence if self._eos_cursor is None: self._eos_cursor = self._write_cursor self._events.append( (self._eos_cursor, MediaEvent(0, 'on_eos'))) self._events.append( (self._eos_cursor, MediaEvent(0, 'on_source_group_eos'))) self._events.sort() if self._write_cursor > self._eos_cursor + self._buffer_size: self.stop() else: self.write(None, write_size) write_size = 0 self.unlock() def update_play_cursor(self): self.lock() play_cursor_ring = lib.DWORD() self._buffer.GetCurrentPosition(play_cursor_ring, None) if play_cursor_ring.value < self._play_cursor_ring: # Wrapped around self._play_cursor += self._buffer_size - self._play_cursor_ring self._play_cursor_ring = 0 self._play_cursor += play_cursor_ring.value - self._play_cursor_ring self._play_cursor_ring = play_cursor_ring.value # Dispatch pending events pending_events = [] while self._events and self._events[0][0] <= self._play_cursor: _, event = self._events.pop(0) pending_events.append(event) if _debug: print 'Dispatching pending events:', pending_events print 'Remaining events:', self._events # Remove expired timestamps while self._timestamps and self._timestamps[0][0] < self._play_cursor: del self._timestamps[0] self.unlock() for event in pending_events: event._sync_dispatch_to_player(self.player) def get_write_size(self): self.update_play_cursor() self.lock() play_cursor = self._play_cursor write_cursor = self._write_cursor self.unlock() return self._buffer_size - max(write_cursor - play_cursor, 0) def write(self, audio_data, length): # Pass audio_data=None to write silence if length == 0: return 0 self.lock() p1 = ctypes.c_void_p() l1 = lib.DWORD() p2 = ctypes.c_void_p() l2 = lib.DWORD() assert 0 < length <= self._buffer_size self._buffer.Lock(self._write_cursor_ring, length, ctypes.byref(p1), l1, ctypes.byref(p2), l2, 0) assert length == l1.value + l2.value if audio_data: ctypes.memmove(p1, audio_data.data, l1.value) audio_data.consume(l1.value, self.source_group.audio_format) if l2.value: ctypes.memmove(p2, audio_data.data, l2.value) audio_data.consume(l2.value, self.source_group.audio_format) else: ctypes.memset(p1, 0, l1.value) if l2.value: ctypes.memset(p2, 0, l2.value) self._buffer.Unlock(p1, l1, p2, l2) self._write_cursor += length self._write_cursor_ring += length self._write_cursor_ring %= self._buffer_size self.unlock() def get_time(self): self.lock() if self._timestamps: cursor, ts = self._timestamps[0] result = ts + (self._play_cursor - cursor) / \ float(self.source_group.audio_format.bytes_per_second) else: result = None self.unlock() return result def set_volume(self, volume): volume = _db(volume) self.lock() self._buffer.SetVolume(volume) self.unlock() def set_position(self, position): if self._buffer3d: x, y, z = position self.lock() self._buffer3d.SetPosition(x, y, -z, lib.DS3D_IMMEDIATE) self.unlock() def set_min_distance(self, min_distance): if self._buffer3d: self.lock() self._buffer3d.SetMinDistance(min_distance, lib.DS3D_IMMEDIATE) self.unlock() def set_max_distance(self, max_distance): if self._buffer3d: self.lock() self._buffer3d.SetMaxDistance(max_distance, lib.DS3D_IMMEDIATE) self.unlock() def set_pitch(self, pitch): frequency = int(pitch * self.audio_format.sample_rate) self.lock() self._buffer.SetFrequency(frequency) self.unlock() def set_cone_orientation(self, cone_orientation): if self._buffer3d: x, y, z = cone_orientation self.lock() self._buffer3d.SetConeOrientation(x, y, -z, lib.DS3D_IMMEDIATE) self.unlock() def set_cone_inner_angle(self, cone_inner_angle): if self._buffer3d: self._cone_inner_angle = int(cone_inner_angle) self._set_cone_angles() def set_cone_outer_angle(self, cone_outer_angle): if self._buffer3d: self._cone_outer_angle = int(cone_outer_angle) self._set_cone_angles() def _set_cone_angles(self): inner = min(self._cone_inner_angle, self._cone_outer_angle) outer = max(self._cone_inner_angle, self._cone_outer_angle) self.lock() self._buffer3d.SetConeAngles(inner, outer, lib.DS3D_IMMEDIATE) self.unlock() def set_cone_outer_gain(self, cone_outer_gain): if self._buffer3d: volume = _db(cone_outer_gain) self.lock() self._buffer3d.SetConeOutsideVolume(volume, lib.DS3D_IMMEDIATE) self.unlock() class DirectSoundDriver(AbstractAudioDriver): def __init__(self): self._dsound = lib.IDirectSound() lib.DirectSoundCreate(None, ctypes.byref(self._dsound), None) # A trick used by mplayer.. use desktop as window handle since it # would be complex to use pyglet window handles (and what to do when # application is audio only?). hwnd = _user32.GetDesktopWindow() self._dsound.SetCooperativeLevel(hwnd, lib.DSSCL_NORMAL) # Create primary buffer with 3D and volume capabilities self._buffer = lib.IDirectSoundBuffer() dsbd = lib.DSBUFFERDESC() dsbd.dwSize = ctypes.sizeof(dsbd) dsbd.dwFlags = (lib.DSBCAPS_CTRL3D | lib.DSBCAPS_CTRLVOLUME | lib.DSBCAPS_PRIMARYBUFFER) self._dsound.CreateSoundBuffer(dsbd, ctypes.byref(self._buffer), None) # Create listener self._listener = lib.IDirectSound3DListener() self._buffer.QueryInterface(lib.IID_IDirectSound3DListener, ctypes.byref(self._listener)) # Create worker thread self.worker = DirectSoundWorker() self.worker.start() def __del__(self): try: if self._buffer: self.delete() except: pass def create_audio_player(self, source_group, player): return DirectSoundAudioPlayer(source_group, player) def delete(self): self.worker.stop() self._buffer.Release() self._buffer = None self._listener.Release() self._listener = None # Listener API def _set_volume(self, volume): self._volume = volume self._buffer.SetVolume(_db(volume)) def _set_position(self, position): self._position = position x, y, z = position self._listener.SetPosition(x, y, -z, lib.DS3D_IMMEDIATE) def _set_forward_orientation(self, orientation): self._forward_orientation = orientation self._set_orientation() def _set_up_orientation(self, orientation): self._up_orientation = orientation self._set_orientation() def _set_orientation(self): x, y, z = self._forward_orientation ux, uy, uz = self._up_orientation self._listener.SetOrientation(x, y, -z, ux, uy, -uz, lib.DS3D_IMMEDIATE) def create_audio_driver(): global driver driver = DirectSoundDriver() return driver # Global driver needed for access to worker thread and _dsound driver = None
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import time from pyglet.media import AbstractAudioPlayer, AbstractAudioDriver, \ MediaThread, MediaEvent import pyglet _debug = pyglet.options['debug_media'] class SilentAudioPacket(object): def __init__(self, timestamp, duration): self.timestamp = timestamp self.duration = duration def consume(self, dt): self.timestamp += dt self.duration -= dt class SilentAudioPlayerPacketConsumer(AbstractAudioPlayer): # When playing video, length of audio (in secs) to buffer ahead. _buffer_time = 0.4 # Minimum number of bytes to request from source _min_update_bytes = 1024 # Maximum sleep time _sleep_time = 0.2 def __init__(self, source_group, player): super(SilentAudioPlayerPacketConsumer, self).__init__(source_group, player) # System time of first timestamp self._timestamp_time = None # List of buffered SilentAudioPacket self._packets = [] self._packets_duration = 0 self._events = [] # Actual play state. self._playing = False # TODO Be nice to avoid creating this thread if user doesn't care # about EOS events and there's no video format. # NOTE Use thread.condition as lock for all instance vars used by worker self._thread = MediaThread(target=self._worker_func) if source_group.audio_format: self._thread.start() def delete(self): if _debug: print 'SilentAudioPlayer.delete' self._thread.stop() def play(self): if _debug: print 'SilentAudioPlayer.play' self._thread.condition.acquire() if not self._playing: self._playing = True self._timestamp_time = time.time() self._thread.condition.notify() self._thread.condition.release() def stop(self): if _debug: print 'SilentAudioPlayer.stop' self._thread.condition.acquire() if self._playing: timestamp = self.get_time() if self._packets: packet = self._packets[0] self._packets_duration -= timestamp - packet.timestamp packet.consume(timestamp - packet.timestamp) self._playing = False self._thread.condition.release() def clear(self): if _debug: print 'SilentAudioPlayer.clear' self._thread.condition.acquire() del self._packets[:] self._packets_duration = 0 del self._events[:] self._thread.condition.release() def get_time(self): if _debug: print 'SilentAudioPlayer.get_time()' self._thread.condition.acquire() packets = self._packets if self._playing: # Consume timestamps result = None offset = time.time() - self._timestamp_time while packets: packet = packets[0] if offset > packet.duration: del packets[0] self._timestamp_time += packet.duration offset -= packet.duration self._packets_duration -= packet.duration else: packet.consume(offset) self._packets_duration -= offset self._timestamp_time += offset result = packet.timestamp break else: # Paused if packets: result = packets[0].timestamp else: result = None self._thread.condition.release() if _debug: print 'SilentAudioPlayer.get_time() -> ', result return result # Worker func that consumes audio data and dispatches events def _worker_func(self): thread = self._thread #buffered_time = 0 eos = False events = self._events while True: thread.condition.acquire() if thread.stopped or (eos and not events): thread.condition.release() break # Use up "buffered" audio based on amount of time passed. timestamp = self.get_time() if _debug: print 'timestamp: %r' % timestamp # Dispatch events while events and timestamp is not None: if (events[0].timestamp is None or events[0].timestamp <= timestamp): events[0]._sync_dispatch_to_player(self.player) del events[0] # Calculate how much data to request from source secs = self._buffer_time - self._packets_duration bytes = secs * self.source_group.audio_format.bytes_per_second if _debug: print 'Trying to buffer %d bytes (%r secs)' % (bytes, secs) while bytes > self._min_update_bytes and not eos: # Pull audio data from source audio_data = self.source_group.get_audio_data(int(bytes)) if not audio_data and not eos: events.append(MediaEvent(timestamp, 'on_eos')) events.append(MediaEvent(timestamp, 'on_source_group_eos')) eos = True break # Pretend to buffer audio data, collect events. if self._playing and not self._packets: self._timestamp_time = time.time() self._packets.append(SilentAudioPacket(audio_data.timestamp, audio_data.duration)) self._packets_duration += audio_data.duration for event in audio_data.events: event.timestamp += audio_data.timestamp events.append(event) events.extend(audio_data.events) bytes -= audio_data.length sleep_time = self._sleep_time if not self._playing: sleep_time = None elif events and events[0].timestamp and timestamp: sleep_time = min(sleep_time, events[0].timestamp - timestamp) if _debug: print 'SilentAudioPlayer(Worker).sleep', sleep_time thread.sleep(sleep_time) thread.condition.release() class SilentTimeAudioPlayer(AbstractAudioPlayer): # Note that when using this player (automatic if playing back video with # unsupported audio codec) no events are dispatched (because they are # normally encoded in the audio packet -- so no EOS events are delivered. # This is a design flaw. # # Also, seeking is broken because the timestamps aren't synchronized with # the source group. _time = 0.0 _systime = None def play(self): self._systime = time.time() def stop(self): self._time = self.get_time() self._systime = None def delete(self): pass def clear(self): pass def get_time(self): if self._systime is None: return self._time else: return time.time() - self._systime + self._time class SilentAudioDriver(AbstractAudioDriver): def create_audio_player(self, source_group, player): if source_group.audio_format: return SilentAudioPlayerPacketConsumer(source_group, player) else: return SilentTimeAudioPlayer(source_group, player) def create_audio_driver(): return SilentAudioDriver()
Python
'''Wrapper for pulse Generated with: tools/genwrappers.py pulseaudio Do not modify this file. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: wrap.py 1694 2008-01-30 23:12:00Z Alex.Holkner $' import ctypes from ctypes import * import pyglet.lib _lib = pyglet.lib.load_library('pulse') _int_types = (c_int16, c_int32) if hasattr(ctypes, 'c_int64'): # Some builds of ctypes apparently do not have c_int64 # defined; it's a pretty good bet that these builds do not # have 64-bit pointers. _int_types += (ctypes.c_int64,) for t in _int_types: if sizeof(t) == sizeof(c_size_t): c_ptrdiff_t = t class c_void(Structure): # c_void_p is a buggy return type, converting to int, so # POINTER(None) == c_void_p is actually written as # POINTER(c_void), so it can be treated as a real pointer. _fields_ = [('dummy', c_int)] class struct_pa_mainloop_api(Structure): __slots__ = [ ] struct_pa_mainloop_api._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_mainloop_api(Structure): __slots__ = [ ] struct_pa_mainloop_api._fields_ = [ ('_opaque_struct', c_int) ] pa_mainloop_api = struct_pa_mainloop_api # /usr/include/pulse/mainloop-api.h:51 enum_pa_io_event_flags = c_int PA_IO_EVENT_NULL = 0 PA_IO_EVENT_INPUT = 1 PA_IO_EVENT_OUTPUT = 2 PA_IO_EVENT_HANGUP = 4 PA_IO_EVENT_ERROR = 8 pa_io_event_flags_t = enum_pa_io_event_flags # /usr/include/pulse/mainloop-api.h:60 class struct_pa_io_event(Structure): __slots__ = [ ] struct_pa_io_event._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_io_event(Structure): __slots__ = [ ] struct_pa_io_event._fields_ = [ ('_opaque_struct', c_int) ] pa_io_event = struct_pa_io_event # /usr/include/pulse/mainloop-api.h:63 pa_io_event_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_io_event), c_int, pa_io_event_flags_t, POINTER(None)) # /usr/include/pulse/mainloop-api.h:65 pa_io_event_destroy_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_io_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:67 class struct_pa_time_event(Structure): __slots__ = [ ] struct_pa_time_event._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_time_event(Structure): __slots__ = [ ] struct_pa_time_event._fields_ = [ ('_opaque_struct', c_int) ] pa_time_event = struct_pa_time_event # /usr/include/pulse/mainloop-api.h:70 class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] pa_time_event_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_time_event), POINTER(struct_timeval), POINTER(None)) # /usr/include/pulse/mainloop-api.h:72 pa_time_event_destroy_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_time_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:74 class struct_pa_defer_event(Structure): __slots__ = [ ] struct_pa_defer_event._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_defer_event(Structure): __slots__ = [ ] struct_pa_defer_event._fields_ = [ ('_opaque_struct', c_int) ] pa_defer_event = struct_pa_defer_event # /usr/include/pulse/mainloop-api.h:77 pa_defer_event_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_defer_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:79 pa_defer_event_destroy_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_defer_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:81 # /usr/include/pulse/mainloop-api.h:120 pa_mainloop_api_once = _lib.pa_mainloop_api_once pa_mainloop_api_once.restype = None pa_mainloop_api_once.argtypes = [POINTER(pa_mainloop_api), CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(None)), POINTER(None)] PA_CHANNELS_MAX = 32 # /usr/include/pulse/sample.h:117 PA_RATE_MAX = 192000 # /usr/include/pulse/sample.h:120 enum_pa_sample_format = c_int PA_SAMPLE_U8 = 0 PA_SAMPLE_ALAW = 1 PA_SAMPLE_ULAW = 2 PA_SAMPLE_S16LE = 3 PA_SAMPLE_S16BE = 4 PA_SAMPLE_FLOAT32LE = 5 PA_SAMPLE_FLOAT32BE = 6 PA_SAMPLE_S32LE = 7 PA_SAMPLE_S32BE = 8 PA_SAMPLE_MAX = 9 PA_SAMPLE_INVALID = 10 pa_sample_format_t = enum_pa_sample_format # /usr/include/pulse/sample.h:135 class struct_pa_sample_spec(Structure): __slots__ = [ 'format', 'rate', 'channels', ] struct_pa_sample_spec._fields_ = [ ('format', pa_sample_format_t), ('rate', c_uint32), ('channels', c_uint8), ] pa_sample_spec = struct_pa_sample_spec # /usr/include/pulse/sample.h:173 pa_usec_t = c_uint64 # /usr/include/pulse/sample.h:176 # /usr/include/pulse/sample.h:179 pa_bytes_per_second = _lib.pa_bytes_per_second pa_bytes_per_second.restype = c_size_t pa_bytes_per_second.argtypes = [POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:182 pa_frame_size = _lib.pa_frame_size pa_frame_size.restype = c_size_t pa_frame_size.argtypes = [POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:185 pa_sample_size = _lib.pa_sample_size pa_sample_size.restype = c_size_t pa_sample_size.argtypes = [POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:188 pa_bytes_to_usec = _lib.pa_bytes_to_usec pa_bytes_to_usec.restype = pa_usec_t pa_bytes_to_usec.argtypes = [c_uint64, POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:191 pa_usec_to_bytes = _lib.pa_usec_to_bytes pa_usec_to_bytes.restype = c_size_t pa_usec_to_bytes.argtypes = [pa_usec_t, POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:194 pa_sample_spec_valid = _lib.pa_sample_spec_valid pa_sample_spec_valid.restype = c_int pa_sample_spec_valid.argtypes = [POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:197 pa_sample_spec_equal = _lib.pa_sample_spec_equal pa_sample_spec_equal.restype = c_int pa_sample_spec_equal.argtypes = [POINTER(pa_sample_spec), POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:200 pa_sample_format_to_string = _lib.pa_sample_format_to_string pa_sample_format_to_string.restype = c_char_p pa_sample_format_to_string.argtypes = [pa_sample_format_t] # /usr/include/pulse/sample.h:203 pa_parse_sample_format = _lib.pa_parse_sample_format pa_parse_sample_format.restype = pa_sample_format_t pa_parse_sample_format.argtypes = [c_char_p] PA_SAMPLE_SPEC_SNPRINT_MAX = 32 # /usr/include/pulse/sample.h:206 # /usr/include/pulse/sample.h:209 pa_sample_spec_snprint = _lib.pa_sample_spec_snprint pa_sample_spec_snprint.restype = c_char_p pa_sample_spec_snprint.argtypes = [c_char_p, c_size_t, POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:212 pa_bytes_snprint = _lib.pa_bytes_snprint pa_bytes_snprint.restype = c_char_p pa_bytes_snprint.argtypes = [c_char_p, c_size_t, c_uint] enum_pa_context_state = c_int PA_CONTEXT_UNCONNECTED = 0 PA_CONTEXT_CONNECTING = 1 PA_CONTEXT_AUTHORIZING = 2 PA_CONTEXT_SETTING_NAME = 3 PA_CONTEXT_READY = 4 PA_CONTEXT_FAILED = 5 PA_CONTEXT_TERMINATED = 6 pa_context_state_t = enum_pa_context_state # /usr/include/pulse/def.h:49 enum_pa_stream_state = c_int PA_STREAM_UNCONNECTED = 0 PA_STREAM_CREATING = 1 PA_STREAM_READY = 2 PA_STREAM_FAILED = 3 PA_STREAM_TERMINATED = 4 pa_stream_state_t = enum_pa_stream_state # /usr/include/pulse/def.h:58 enum_pa_operation_state = c_int PA_OPERATION_RUNNING = 0 PA_OPERATION_DONE = 1 PA_OPERATION_CANCELED = 2 pa_operation_state_t = enum_pa_operation_state # /usr/include/pulse/def.h:65 enum_pa_context_flags = c_int PA_CONTEXT_NOAUTOSPAWN = 1 pa_context_flags_t = enum_pa_context_flags # /usr/include/pulse/def.h:73 enum_pa_stream_direction = c_int PA_STREAM_NODIRECTION = 0 PA_STREAM_PLAYBACK = 1 PA_STREAM_RECORD = 2 PA_STREAM_UPLOAD = 3 pa_stream_direction_t = enum_pa_stream_direction # /usr/include/pulse/def.h:81 enum_pa_stream_flags = c_int PA_STREAM_START_CORKED = 1 PA_STREAM_INTERPOLATE_TIMING = 2 PA_STREAM_NOT_MONOTONOUS = 4 PA_STREAM_AUTO_TIMING_UPDATE = 8 PA_STREAM_NO_REMAP_CHANNELS = 16 PA_STREAM_NO_REMIX_CHANNELS = 32 PA_STREAM_FIX_FORMAT = 64 PA_STREAM_FIX_RATE = 128 PA_STREAM_FIX_CHANNELS = 256 PA_STREAM_DONT_MOVE = 512 PA_STREAM_VARIABLE_RATE = 1024 pa_stream_flags_t = enum_pa_stream_flags # /usr/include/pulse/def.h:212 class struct_pa_buffer_attr(Structure): __slots__ = [ 'maxlength', 'tlength', 'prebuf', 'minreq', 'fragsize', ] struct_pa_buffer_attr._fields_ = [ ('maxlength', c_uint32), ('tlength', c_uint32), ('prebuf', c_uint32), ('minreq', c_uint32), ('fragsize', c_uint32), ] pa_buffer_attr = struct_pa_buffer_attr # /usr/include/pulse/def.h:221 enum_pa_subscription_mask = c_int PA_SUBSCRIPTION_MASK_NULL = 0 PA_SUBSCRIPTION_MASK_SINK = 1 PA_SUBSCRIPTION_MASK_SOURCE = 2 PA_SUBSCRIPTION_MASK_SINK_INPUT = 4 PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT = 8 PA_SUBSCRIPTION_MASK_MODULE = 16 PA_SUBSCRIPTION_MASK_CLIENT = 32 PA_SUBSCRIPTION_MASK_SAMPLE_CACHE = 64 PA_SUBSCRIPTION_MASK_SERVER = 128 PA_SUBSCRIPTION_MASK_AUTOLOAD = 256 PA_SUBSCRIPTION_MASK_ALL = 511 pa_subscription_mask_t = enum_pa_subscription_mask # /usr/include/pulse/def.h:261 enum_pa_subscription_event_type = c_int PA_SUBSCRIPTION_EVENT_SINK = 0 PA_SUBSCRIPTION_EVENT_SOURCE = 1 PA_SUBSCRIPTION_EVENT_SINK_INPUT = 2 PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT = 3 PA_SUBSCRIPTION_EVENT_MODULE = 4 PA_SUBSCRIPTION_EVENT_CLIENT = 5 PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE = 6 PA_SUBSCRIPTION_EVENT_SERVER = 7 PA_SUBSCRIPTION_EVENT_AUTOLOAD = 8 PA_SUBSCRIPTION_EVENT_FACILITY_MASK = 15 PA_SUBSCRIPTION_EVENT_NEW = 0 PA_SUBSCRIPTION_EVENT_CHANGE = 16 PA_SUBSCRIPTION_EVENT_REMOVE = 32 PA_SUBSCRIPTION_EVENT_TYPE_MASK = 1632 pa_subscription_event_type_t = enum_pa_subscription_event_type # /usr/include/pulse/def.h:280 class struct_pa_timing_info(Structure): __slots__ = [ 'timestamp', 'synchronized_clocks', 'sink_usec', 'source_usec', 'transport_usec', 'playing', 'write_index_corrupt', 'write_index', 'read_index_corrupt', 'read_index', ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ # XXX HACK struct timeval wasn't picked up by wraptypes #('_opaque_struct', c_int) ('tv_sec', c_long), ('tv_usec', c_long), ] struct_pa_timing_info._fields_ = [ ('timestamp', struct_timeval), ('synchronized_clocks', c_int), ('sink_usec', pa_usec_t), ('source_usec', pa_usec_t), ('transport_usec', pa_usec_t), ('playing', c_int), ('write_index_corrupt', c_int), ('write_index', c_int64), ('read_index_corrupt', c_int), ('read_index', c_int64), ] pa_timing_info = struct_pa_timing_info # /usr/include/pulse/def.h:347 class struct_pa_spawn_api(Structure): __slots__ = [ 'prefork', 'postfork', 'atfork', ] struct_pa_spawn_api._fields_ = [ ('prefork', POINTER(CFUNCTYPE(None))), ('postfork', POINTER(CFUNCTYPE(None))), ('atfork', POINTER(CFUNCTYPE(None))), ] pa_spawn_api = struct_pa_spawn_api # /usr/include/pulse/def.h:366 enum_pa_seek_mode = c_int PA_SEEK_RELATIVE = 0 PA_SEEK_ABSOLUTE = 1 PA_SEEK_RELATIVE_ON_READ = 2 PA_SEEK_RELATIVE_END = 3 pa_seek_mode_t = enum_pa_seek_mode # /usr/include/pulse/def.h:374 enum_pa_sink_flags = c_int PA_SINK_HW_VOLUME_CTRL = 1 PA_SINK_LATENCY = 2 PA_SINK_HARDWARE = 4 PA_SINK_NETWORK = 8 pa_sink_flags_t = enum_pa_sink_flags # /usr/include/pulse/def.h:382 enum_pa_source_flags = c_int PA_SOURCE_HW_VOLUME_CTRL = 1 PA_SOURCE_LATENCY = 2 PA_SOURCE_HARDWARE = 4 PA_SOURCE_NETWORK = 8 pa_source_flags_t = enum_pa_source_flags # /usr/include/pulse/def.h:390 pa_free_cb_t = CFUNCTYPE(None, POINTER(None)) # /usr/include/pulse/def.h:393 class struct_pa_operation(Structure): __slots__ = [ ] struct_pa_operation._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_operation(Structure): __slots__ = [ ] struct_pa_operation._fields_ = [ ('_opaque_struct', c_int) ] pa_operation = struct_pa_operation # /usr/include/pulse/operation.h:36 # /usr/include/pulse/operation.h:39 pa_operation_ref = _lib.pa_operation_ref pa_operation_ref.restype = POINTER(pa_operation) pa_operation_ref.argtypes = [POINTER(pa_operation)] # /usr/include/pulse/operation.h:42 pa_operation_unref = _lib.pa_operation_unref pa_operation_unref.restype = None pa_operation_unref.argtypes = [POINTER(pa_operation)] # /usr/include/pulse/operation.h:45 pa_operation_cancel = _lib.pa_operation_cancel pa_operation_cancel.restype = None pa_operation_cancel.argtypes = [POINTER(pa_operation)] # /usr/include/pulse/operation.h:48 pa_operation_get_state = _lib.pa_operation_get_state pa_operation_get_state.restype = pa_operation_state_t pa_operation_get_state.argtypes = [POINTER(pa_operation)] class struct_pa_context(Structure): __slots__ = [ ] struct_pa_context._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_context(Structure): __slots__ = [ ] struct_pa_context._fields_ = [ ('_opaque_struct', c_int) ] pa_context = struct_pa_context # /usr/include/pulse/context.h:160 pa_context_notify_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(None)) # /usr/include/pulse/context.h:163 pa_context_success_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_int, POINTER(None)) # /usr/include/pulse/context.h:166 # /usr/include/pulse/context.h:170 pa_context_new = _lib.pa_context_new pa_context_new.restype = POINTER(pa_context) pa_context_new.argtypes = [POINTER(pa_mainloop_api), c_char_p] # /usr/include/pulse/context.h:173 pa_context_unref = _lib.pa_context_unref pa_context_unref.restype = None pa_context_unref.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:176 pa_context_ref = _lib.pa_context_ref pa_context_ref.restype = POINTER(pa_context) pa_context_ref.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:179 pa_context_set_state_callback = _lib.pa_context_set_state_callback pa_context_set_state_callback.restype = None pa_context_set_state_callback.argtypes = [POINTER(pa_context), pa_context_notify_cb_t, POINTER(None)] # /usr/include/pulse/context.h:182 pa_context_errno = _lib.pa_context_errno pa_context_errno.restype = c_int pa_context_errno.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:185 pa_context_is_pending = _lib.pa_context_is_pending pa_context_is_pending.restype = c_int pa_context_is_pending.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:188 pa_context_get_state = _lib.pa_context_get_state pa_context_get_state.restype = pa_context_state_t pa_context_get_state.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:197 pa_context_connect = _lib.pa_context_connect pa_context_connect.restype = c_int pa_context_connect.argtypes = [POINTER(pa_context), c_char_p, pa_context_flags_t, POINTER(pa_spawn_api)] # /usr/include/pulse/context.h:200 pa_context_disconnect = _lib.pa_context_disconnect pa_context_disconnect.restype = None pa_context_disconnect.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:203 pa_context_drain = _lib.pa_context_drain pa_context_drain.restype = POINTER(pa_operation) pa_context_drain.argtypes = [POINTER(pa_context), pa_context_notify_cb_t, POINTER(None)] # /usr/include/pulse/context.h:208 pa_context_exit_daemon = _lib.pa_context_exit_daemon pa_context_exit_daemon.restype = POINTER(pa_operation) pa_context_exit_daemon.argtypes = [POINTER(pa_context), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/context.h:211 pa_context_set_default_sink = _lib.pa_context_set_default_sink pa_context_set_default_sink.restype = POINTER(pa_operation) pa_context_set_default_sink.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/context.h:214 pa_context_set_default_source = _lib.pa_context_set_default_source pa_context_set_default_source.restype = POINTER(pa_operation) pa_context_set_default_source.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/context.h:217 pa_context_is_local = _lib.pa_context_is_local pa_context_is_local.restype = c_int pa_context_is_local.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:220 pa_context_set_name = _lib.pa_context_set_name pa_context_set_name.restype = POINTER(pa_operation) pa_context_set_name.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/context.h:223 pa_context_get_server = _lib.pa_context_get_server pa_context_get_server.restype = c_char_p pa_context_get_server.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:226 pa_context_get_protocol_version = _lib.pa_context_get_protocol_version pa_context_get_protocol_version.restype = c_uint32 pa_context_get_protocol_version.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:229 pa_context_get_server_protocol_version = _lib.pa_context_get_server_protocol_version pa_context_get_server_protocol_version.restype = c_uint32 pa_context_get_server_protocol_version.argtypes = [POINTER(pa_context)] enum_pa_channel_position = c_int PA_CHANNEL_POSITION_INVALID = 0 PA_CHANNEL_POSITION_MONO = 0 PA_CHANNEL_POSITION_LEFT = 1 PA_CHANNEL_POSITION_RIGHT = 2 PA_CHANNEL_POSITION_CENTER = 3 PA_CHANNEL_POSITION_FRONT_LEFT = 0 PA_CHANNEL_POSITION_FRONT_RIGHT = 0 PA_CHANNEL_POSITION_FRONT_CENTER = 0 PA_CHANNEL_POSITION_REAR_CENTER = 1 PA_CHANNEL_POSITION_REAR_LEFT = 2 PA_CHANNEL_POSITION_REAR_RIGHT = 3 PA_CHANNEL_POSITION_LFE = 4 PA_CHANNEL_POSITION_SUBWOOFER = 0 PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER = 1 PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER = 2 PA_CHANNEL_POSITION_SIDE_LEFT = 3 PA_CHANNEL_POSITION_SIDE_RIGHT = 4 PA_CHANNEL_POSITION_AUX0 = 5 PA_CHANNEL_POSITION_AUX1 = 6 PA_CHANNEL_POSITION_AUX2 = 7 PA_CHANNEL_POSITION_AUX3 = 8 PA_CHANNEL_POSITION_AUX4 = 9 PA_CHANNEL_POSITION_AUX5 = 10 PA_CHANNEL_POSITION_AUX6 = 11 PA_CHANNEL_POSITION_AUX7 = 12 PA_CHANNEL_POSITION_AUX8 = 13 PA_CHANNEL_POSITION_AUX9 = 14 PA_CHANNEL_POSITION_AUX10 = 15 PA_CHANNEL_POSITION_AUX11 = 16 PA_CHANNEL_POSITION_AUX12 = 17 PA_CHANNEL_POSITION_AUX13 = 18 PA_CHANNEL_POSITION_AUX14 = 19 PA_CHANNEL_POSITION_AUX15 = 20 PA_CHANNEL_POSITION_AUX16 = 21 PA_CHANNEL_POSITION_AUX17 = 22 PA_CHANNEL_POSITION_AUX18 = 23 PA_CHANNEL_POSITION_AUX19 = 24 PA_CHANNEL_POSITION_AUX20 = 25 PA_CHANNEL_POSITION_AUX21 = 26 PA_CHANNEL_POSITION_AUX22 = 27 PA_CHANNEL_POSITION_AUX23 = 28 PA_CHANNEL_POSITION_AUX24 = 29 PA_CHANNEL_POSITION_AUX25 = 30 PA_CHANNEL_POSITION_AUX26 = 31 PA_CHANNEL_POSITION_AUX27 = 32 PA_CHANNEL_POSITION_AUX28 = 33 PA_CHANNEL_POSITION_AUX29 = 34 PA_CHANNEL_POSITION_AUX30 = 35 PA_CHANNEL_POSITION_AUX31 = 36 PA_CHANNEL_POSITION_TOP_CENTER = 37 PA_CHANNEL_POSITION_TOP_FRONT_LEFT = 38 PA_CHANNEL_POSITION_TOP_FRONT_RIGHT = 39 PA_CHANNEL_POSITION_TOP_FRONT_CENTER = 40 PA_CHANNEL_POSITION_TOP_REAR_LEFT = 41 PA_CHANNEL_POSITION_TOP_REAR_RIGHT = 42 PA_CHANNEL_POSITION_TOP_REAR_CENTER = 43 PA_CHANNEL_POSITION_MAX = 44 pa_channel_position_t = enum_pa_channel_position # /usr/include/pulse/channelmap.h:140 enum_pa_channel_map_def = c_int PA_CHANNEL_MAP_AIFF = 0 PA_CHANNEL_MAP_ALSA = 1 PA_CHANNEL_MAP_AUX = 2 PA_CHANNEL_MAP_WAVEEX = 3 PA_CHANNEL_MAP_OSS = 4 PA_CHANNEL_MAP_DEFAULT = 0 pa_channel_map_def_t = enum_pa_channel_map_def # /usr/include/pulse/channelmap.h:151 class struct_pa_channel_map(Structure): __slots__ = [ 'channels', 'map', ] struct_pa_channel_map._fields_ = [ ('channels', c_uint8), ('map', pa_channel_position_t * 32), ] pa_channel_map = struct_pa_channel_map # /usr/include/pulse/channelmap.h:159 # /usr/include/pulse/channelmap.h:162 pa_channel_map_init = _lib.pa_channel_map_init pa_channel_map_init.restype = POINTER(pa_channel_map) pa_channel_map_init.argtypes = [POINTER(pa_channel_map)] # /usr/include/pulse/channelmap.h:165 pa_channel_map_init_mono = _lib.pa_channel_map_init_mono pa_channel_map_init_mono.restype = POINTER(pa_channel_map) pa_channel_map_init_mono.argtypes = [POINTER(pa_channel_map)] # /usr/include/pulse/channelmap.h:168 pa_channel_map_init_stereo = _lib.pa_channel_map_init_stereo pa_channel_map_init_stereo.restype = POINTER(pa_channel_map) pa_channel_map_init_stereo.argtypes = [POINTER(pa_channel_map)] # /usr/include/pulse/channelmap.h:172 pa_channel_map_init_auto = _lib.pa_channel_map_init_auto pa_channel_map_init_auto.restype = POINTER(pa_channel_map) pa_channel_map_init_auto.argtypes = [POINTER(pa_channel_map), c_uint, pa_channel_map_def_t] # /usr/include/pulse/channelmap.h:175 pa_channel_position_to_string = _lib.pa_channel_position_to_string pa_channel_position_to_string.restype = c_char_p pa_channel_position_to_string.argtypes = [pa_channel_position_t] # /usr/include/pulse/channelmap.h:178 pa_channel_position_to_pretty_string = _lib.pa_channel_position_to_pretty_string pa_channel_position_to_pretty_string.restype = c_char_p pa_channel_position_to_pretty_string.argtypes = [pa_channel_position_t] PA_CHANNEL_MAP_SNPRINT_MAX = 336 # /usr/include/pulse/channelmap.h:181 # /usr/include/pulse/channelmap.h:184 pa_channel_map_snprint = _lib.pa_channel_map_snprint pa_channel_map_snprint.restype = c_char_p pa_channel_map_snprint.argtypes = [c_char_p, c_size_t, POINTER(pa_channel_map)] # /usr/include/pulse/channelmap.h:187 pa_channel_map_parse = _lib.pa_channel_map_parse pa_channel_map_parse.restype = POINTER(pa_channel_map) pa_channel_map_parse.argtypes = [POINTER(pa_channel_map), c_char_p] # /usr/include/pulse/channelmap.h:190 pa_channel_map_equal = _lib.pa_channel_map_equal pa_channel_map_equal.restype = c_int pa_channel_map_equal.argtypes = [POINTER(pa_channel_map), POINTER(pa_channel_map)] # /usr/include/pulse/channelmap.h:193 pa_channel_map_valid = _lib.pa_channel_map_valid pa_channel_map_valid.restype = c_int pa_channel_map_valid.argtypes = [POINTER(pa_channel_map)] pa_volume_t = c_uint32 # /usr/include/pulse/volume.h:101 PA_VOLUME_NORM = 65536 # /usr/include/pulse/volume.h:104 PA_VOLUME_MUTED = 0 # /usr/include/pulse/volume.h:107 class struct_pa_cvolume(Structure): __slots__ = [ 'channels', 'values', ] struct_pa_cvolume._fields_ = [ ('channels', c_uint8), ('values', pa_volume_t * 32), ] pa_cvolume = struct_pa_cvolume # /usr/include/pulse/volume.h:113 # /usr/include/pulse/volume.h:116 pa_cvolume_equal = _lib.pa_cvolume_equal pa_cvolume_equal.restype = c_int pa_cvolume_equal.argtypes = [POINTER(pa_cvolume), POINTER(pa_cvolume)] # /usr/include/pulse/volume.h:125 pa_cvolume_set = _lib.pa_cvolume_set pa_cvolume_set.restype = POINTER(pa_cvolume) pa_cvolume_set.argtypes = [POINTER(pa_cvolume), c_uint, pa_volume_t] PA_CVOLUME_SNPRINT_MAX = 64 # /usr/include/pulse/volume.h:128 # /usr/include/pulse/volume.h:131 pa_cvolume_snprint = _lib.pa_cvolume_snprint pa_cvolume_snprint.restype = c_char_p pa_cvolume_snprint.argtypes = [c_char_p, c_size_t, POINTER(pa_cvolume)] # /usr/include/pulse/volume.h:134 pa_cvolume_avg = _lib.pa_cvolume_avg pa_cvolume_avg.restype = pa_volume_t pa_cvolume_avg.argtypes = [POINTER(pa_cvolume)] # /usr/include/pulse/volume.h:137 pa_cvolume_valid = _lib.pa_cvolume_valid pa_cvolume_valid.restype = c_int pa_cvolume_valid.argtypes = [POINTER(pa_cvolume)] # /usr/include/pulse/volume.h:140 pa_cvolume_channels_equal_to = _lib.pa_cvolume_channels_equal_to pa_cvolume_channels_equal_to.restype = c_int pa_cvolume_channels_equal_to.argtypes = [POINTER(pa_cvolume), pa_volume_t] # /usr/include/pulse/volume.h:149 pa_sw_volume_multiply = _lib.pa_sw_volume_multiply pa_sw_volume_multiply.restype = pa_volume_t pa_sw_volume_multiply.argtypes = [pa_volume_t, pa_volume_t] # /usr/include/pulse/volume.h:152 pa_sw_cvolume_multiply = _lib.pa_sw_cvolume_multiply pa_sw_cvolume_multiply.restype = POINTER(pa_cvolume) pa_sw_cvolume_multiply.argtypes = [POINTER(pa_cvolume), POINTER(pa_cvolume), POINTER(pa_cvolume)] # /usr/include/pulse/volume.h:155 pa_sw_volume_from_dB = _lib.pa_sw_volume_from_dB pa_sw_volume_from_dB.restype = pa_volume_t pa_sw_volume_from_dB.argtypes = [c_double] # /usr/include/pulse/volume.h:158 pa_sw_volume_to_dB = _lib.pa_sw_volume_to_dB pa_sw_volume_to_dB.restype = c_double pa_sw_volume_to_dB.argtypes = [pa_volume_t] # /usr/include/pulse/volume.h:161 pa_sw_volume_from_linear = _lib.pa_sw_volume_from_linear pa_sw_volume_from_linear.restype = pa_volume_t pa_sw_volume_from_linear.argtypes = [c_double] # /usr/include/pulse/volume.h:164 pa_sw_volume_to_linear = _lib.pa_sw_volume_to_linear pa_sw_volume_to_linear.restype = c_double pa_sw_volume_to_linear.argtypes = [pa_volume_t] PA_DECIBEL_MININFTY = -200 # /usr/include/pulse/volume.h:170 class struct_pa_stream(Structure): __slots__ = [ ] struct_pa_stream._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_stream(Structure): __slots__ = [ ] struct_pa_stream._fields_ = [ ('_opaque_struct', c_int) ] pa_stream = struct_pa_stream # /usr/include/pulse/stream.h:268 pa_stream_success_cb_t = CFUNCTYPE(None, POINTER(pa_stream), c_int, POINTER(None)) # /usr/include/pulse/stream.h:271 pa_stream_request_cb_t = CFUNCTYPE(None, POINTER(pa_stream), c_size_t, POINTER(None)) # /usr/include/pulse/stream.h:274 pa_stream_notify_cb_t = CFUNCTYPE(None, POINTER(pa_stream), POINTER(None)) # /usr/include/pulse/stream.h:277 # /usr/include/pulse/stream.h:280 pa_stream_new = _lib.pa_stream_new pa_stream_new.restype = POINTER(pa_stream) pa_stream_new.argtypes = [POINTER(pa_context), c_char_p, POINTER(pa_sample_spec), POINTER(pa_channel_map)] # /usr/include/pulse/stream.h:287 pa_stream_unref = _lib.pa_stream_unref pa_stream_unref.restype = None pa_stream_unref.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:290 pa_stream_ref = _lib.pa_stream_ref pa_stream_ref.restype = POINTER(pa_stream) pa_stream_ref.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:293 pa_stream_get_state = _lib.pa_stream_get_state pa_stream_get_state.restype = pa_stream_state_t pa_stream_get_state.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:296 pa_stream_get_context = _lib.pa_stream_get_context pa_stream_get_context.restype = POINTER(pa_context) pa_stream_get_context.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:302 pa_stream_get_index = _lib.pa_stream_get_index pa_stream_get_index.restype = c_uint32 pa_stream_get_index.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:312 pa_stream_get_device_index = _lib.pa_stream_get_device_index pa_stream_get_device_index.restype = c_uint32 pa_stream_get_device_index.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:322 pa_stream_get_device_name = _lib.pa_stream_get_device_name pa_stream_get_device_name.restype = c_char_p pa_stream_get_device_name.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:328 pa_stream_is_suspended = _lib.pa_stream_is_suspended pa_stream_is_suspended.restype = c_int pa_stream_is_suspended.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:331 pa_stream_connect_playback = _lib.pa_stream_connect_playback pa_stream_connect_playback.restype = c_int pa_stream_connect_playback.argtypes = [POINTER(pa_stream), c_char_p, POINTER(pa_buffer_attr), pa_stream_flags_t, POINTER(pa_cvolume), POINTER(pa_stream)] # /usr/include/pulse/stream.h:340 pa_stream_connect_record = _lib.pa_stream_connect_record pa_stream_connect_record.restype = c_int pa_stream_connect_record.argtypes = [POINTER(pa_stream), c_char_p, POINTER(pa_buffer_attr), pa_stream_flags_t] # /usr/include/pulse/stream.h:347 pa_stream_disconnect = _lib.pa_stream_disconnect pa_stream_disconnect.restype = c_int pa_stream_disconnect.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:356 pa_stream_write = _lib.pa_stream_write pa_stream_write.restype = c_int pa_stream_write.argtypes = [POINTER(pa_stream), POINTER(None), c_size_t, pa_free_cb_t, c_int64, pa_seek_mode_t] # /usr/include/pulse/stream.h:369 pa_stream_peek = _lib.pa_stream_peek pa_stream_peek.restype = c_int pa_stream_peek.argtypes = [POINTER(pa_stream), POINTER(POINTER(None)), POINTER(c_size_t)] # /usr/include/pulse/stream.h:376 pa_stream_drop = _lib.pa_stream_drop pa_stream_drop.restype = c_int pa_stream_drop.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:379 pa_stream_writable_size = _lib.pa_stream_writable_size pa_stream_writable_size.restype = c_size_t pa_stream_writable_size.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:382 pa_stream_readable_size = _lib.pa_stream_readable_size pa_stream_readable_size.restype = c_size_t pa_stream_readable_size.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:385 pa_stream_drain = _lib.pa_stream_drain pa_stream_drain.restype = POINTER(pa_operation) pa_stream_drain.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:391 pa_stream_update_timing_info = _lib.pa_stream_update_timing_info pa_stream_update_timing_info.restype = POINTER(pa_operation) pa_stream_update_timing_info.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:394 pa_stream_set_state_callback = _lib.pa_stream_set_state_callback pa_stream_set_state_callback.restype = None pa_stream_set_state_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:398 pa_stream_set_write_callback = _lib.pa_stream_set_write_callback pa_stream_set_write_callback.restype = None pa_stream_set_write_callback.argtypes = [POINTER(pa_stream), pa_stream_request_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:402 pa_stream_set_read_callback = _lib.pa_stream_set_read_callback pa_stream_set_read_callback.restype = None pa_stream_set_read_callback.argtypes = [POINTER(pa_stream), pa_stream_request_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:405 pa_stream_set_overflow_callback = _lib.pa_stream_set_overflow_callback pa_stream_set_overflow_callback.restype = None pa_stream_set_overflow_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:408 pa_stream_set_underflow_callback = _lib.pa_stream_set_underflow_callback pa_stream_set_underflow_callback.restype = None pa_stream_set_underflow_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:413 pa_stream_set_latency_update_callback = _lib.pa_stream_set_latency_update_callback pa_stream_set_latency_update_callback.restype = None pa_stream_set_latency_update_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:420 pa_stream_set_moved_callback = _lib.pa_stream_set_moved_callback pa_stream_set_moved_callback.restype = None pa_stream_set_moved_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:430 pa_stream_set_suspended_callback = _lib.pa_stream_set_suspended_callback pa_stream_set_suspended_callback.restype = None pa_stream_set_suspended_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:433 pa_stream_cork = _lib.pa_stream_cork pa_stream_cork.restype = POINTER(pa_operation) pa_stream_cork.argtypes = [POINTER(pa_stream), c_int, pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:438 pa_stream_flush = _lib.pa_stream_flush pa_stream_flush.restype = POINTER(pa_operation) pa_stream_flush.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:442 pa_stream_prebuf = _lib.pa_stream_prebuf pa_stream_prebuf.restype = POINTER(pa_operation) pa_stream_prebuf.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:447 pa_stream_trigger = _lib.pa_stream_trigger pa_stream_trigger.restype = POINTER(pa_operation) pa_stream_trigger.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:450 pa_stream_set_name = _lib.pa_stream_set_name pa_stream_set_name.restype = POINTER(pa_operation) pa_stream_set_name.argtypes = [POINTER(pa_stream), c_char_p, pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:467 pa_stream_get_time = _lib.pa_stream_get_time pa_stream_get_time.restype = c_int pa_stream_get_time.argtypes = [POINTER(pa_stream), POINTER(pa_usec_t)] # /usr/include/pulse/stream.h:473 pa_stream_get_latency = _lib.pa_stream_get_latency pa_stream_get_latency.restype = c_int pa_stream_get_latency.argtypes = [POINTER(pa_stream), POINTER(pa_usec_t), POINTER(c_int)] # /usr/include/pulse/stream.h:485 pa_stream_get_timing_info = _lib.pa_stream_get_timing_info pa_stream_get_timing_info.restype = POINTER(pa_timing_info) pa_stream_get_timing_info.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:488 pa_stream_get_sample_spec = _lib.pa_stream_get_sample_spec pa_stream_get_sample_spec.restype = POINTER(pa_sample_spec) pa_stream_get_sample_spec.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:491 pa_stream_get_channel_map = _lib.pa_stream_get_channel_map pa_stream_get_channel_map.restype = POINTER(pa_channel_map) pa_stream_get_channel_map.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:496 pa_stream_get_buffer_attr = _lib.pa_stream_get_buffer_attr pa_stream_get_buffer_attr.restype = POINTER(pa_buffer_attr) pa_stream_get_buffer_attr.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:504 pa_stream_set_buffer_attr = _lib.pa_stream_set_buffer_attr pa_stream_set_buffer_attr.restype = POINTER(pa_operation) pa_stream_set_buffer_attr.argtypes = [POINTER(pa_stream), POINTER(pa_buffer_attr), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:511 pa_stream_update_sample_rate = _lib.pa_stream_update_sample_rate pa_stream_update_sample_rate.restype = POINTER(pa_operation) pa_stream_update_sample_rate.argtypes = [POINTER(pa_stream), c_uint32, pa_stream_success_cb_t, POINTER(None)] class struct_pa_sink_info(Structure): __slots__ = [ 'name', 'index', 'description', 'sample_spec', 'channel_map', 'owner_module', 'volume', 'mute', 'monitor_source', 'monitor_source_name', 'latency', 'driver', 'flags', ] struct_pa_sink_info._fields_ = [ ('name', c_char_p), ('index', c_uint32), ('description', c_char_p), ('sample_spec', pa_sample_spec), ('channel_map', pa_channel_map), ('owner_module', c_uint32), ('volume', pa_cvolume), ('mute', c_int), ('monitor_source', c_uint32), ('monitor_source_name', c_char_p), ('latency', pa_usec_t), ('driver', c_char_p), ('flags', pa_sink_flags_t), ] pa_sink_info = struct_pa_sink_info # /usr/include/pulse/introspect.h:224 pa_sink_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_sink_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:227 # /usr/include/pulse/introspect.h:230 pa_context_get_sink_info_by_name = _lib.pa_context_get_sink_info_by_name pa_context_get_sink_info_by_name.restype = POINTER(pa_operation) pa_context_get_sink_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_sink_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:233 pa_context_get_sink_info_by_index = _lib.pa_context_get_sink_info_by_index pa_context_get_sink_info_by_index.restype = POINTER(pa_operation) pa_context_get_sink_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_sink_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:236 pa_context_get_sink_info_list = _lib.pa_context_get_sink_info_list pa_context_get_sink_info_list.restype = POINTER(pa_operation) pa_context_get_sink_info_list.argtypes = [POINTER(pa_context), pa_sink_info_cb_t, POINTER(None)] class struct_pa_source_info(Structure): __slots__ = [ 'name', 'index', 'description', 'sample_spec', 'channel_map', 'owner_module', 'volume', 'mute', 'monitor_of_sink', 'monitor_of_sink_name', 'latency', 'driver', 'flags', ] struct_pa_source_info._fields_ = [ ('name', c_char_p), ('index', c_uint32), ('description', c_char_p), ('sample_spec', pa_sample_spec), ('channel_map', pa_channel_map), ('owner_module', c_uint32), ('volume', pa_cvolume), ('mute', c_int), ('monitor_of_sink', c_uint32), ('monitor_of_sink_name', c_char_p), ('latency', pa_usec_t), ('driver', c_char_p), ('flags', pa_source_flags_t), ] pa_source_info = struct_pa_source_info # /usr/include/pulse/introspect.h:253 pa_source_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_source_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:256 # /usr/include/pulse/introspect.h:259 pa_context_get_source_info_by_name = _lib.pa_context_get_source_info_by_name pa_context_get_source_info_by_name.restype = POINTER(pa_operation) pa_context_get_source_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_source_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:262 pa_context_get_source_info_by_index = _lib.pa_context_get_source_info_by_index pa_context_get_source_info_by_index.restype = POINTER(pa_operation) pa_context_get_source_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_source_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:265 pa_context_get_source_info_list = _lib.pa_context_get_source_info_list pa_context_get_source_info_list.restype = POINTER(pa_operation) pa_context_get_source_info_list.argtypes = [POINTER(pa_context), pa_source_info_cb_t, POINTER(None)] class struct_pa_server_info(Structure): __slots__ = [ 'user_name', 'host_name', 'server_version', 'server_name', 'sample_spec', 'default_sink_name', 'default_source_name', 'cookie', ] struct_pa_server_info._fields_ = [ ('user_name', c_char_p), ('host_name', c_char_p), ('server_version', c_char_p), ('server_name', c_char_p), ('sample_spec', pa_sample_spec), ('default_sink_name', c_char_p), ('default_source_name', c_char_p), ('cookie', c_uint32), ] pa_server_info = struct_pa_server_info # /usr/include/pulse/introspect.h:277 pa_server_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_server_info), POINTER(None)) # /usr/include/pulse/introspect.h:280 # /usr/include/pulse/introspect.h:283 pa_context_get_server_info = _lib.pa_context_get_server_info pa_context_get_server_info.restype = POINTER(pa_operation) pa_context_get_server_info.argtypes = [POINTER(pa_context), pa_server_info_cb_t, POINTER(None)] class struct_pa_module_info(Structure): __slots__ = [ 'index', 'name', 'argument', 'n_used', 'auto_unload', ] struct_pa_module_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('argument', c_char_p), ('n_used', c_uint32), ('auto_unload', c_int), ] pa_module_info = struct_pa_module_info # /usr/include/pulse/introspect.h:292 pa_module_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_module_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:295 # /usr/include/pulse/introspect.h:298 pa_context_get_module_info = _lib.pa_context_get_module_info pa_context_get_module_info.restype = POINTER(pa_operation) pa_context_get_module_info.argtypes = [POINTER(pa_context), c_uint32, pa_module_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:301 pa_context_get_module_info_list = _lib.pa_context_get_module_info_list pa_context_get_module_info_list.restype = POINTER(pa_operation) pa_context_get_module_info_list.argtypes = [POINTER(pa_context), pa_module_info_cb_t, POINTER(None)] class struct_pa_client_info(Structure): __slots__ = [ 'index', 'name', 'owner_module', 'driver', ] struct_pa_client_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('owner_module', c_uint32), ('driver', c_char_p), ] pa_client_info = struct_pa_client_info # /usr/include/pulse/introspect.h:309 pa_client_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_client_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:312 # /usr/include/pulse/introspect.h:315 pa_context_get_client_info = _lib.pa_context_get_client_info pa_context_get_client_info.restype = POINTER(pa_operation) pa_context_get_client_info.argtypes = [POINTER(pa_context), c_uint32, pa_client_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:318 pa_context_get_client_info_list = _lib.pa_context_get_client_info_list pa_context_get_client_info_list.restype = POINTER(pa_operation) pa_context_get_client_info_list.argtypes = [POINTER(pa_context), pa_client_info_cb_t, POINTER(None)] class struct_pa_sink_input_info(Structure): __slots__ = [ 'index', 'name', 'owner_module', 'client', 'sink', 'sample_spec', 'channel_map', 'volume', 'buffer_usec', 'sink_usec', 'resample_method', 'driver', 'mute', ] struct_pa_sink_input_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('owner_module', c_uint32), ('client', c_uint32), ('sink', c_uint32), ('sample_spec', pa_sample_spec), ('channel_map', pa_channel_map), ('volume', pa_cvolume), ('buffer_usec', pa_usec_t), ('sink_usec', pa_usec_t), ('resample_method', c_char_p), ('driver', c_char_p), ('mute', c_int), ] pa_sink_input_info = struct_pa_sink_input_info # /usr/include/pulse/introspect.h:335 pa_sink_input_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_sink_input_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:338 # /usr/include/pulse/introspect.h:341 pa_context_get_sink_input_info = _lib.pa_context_get_sink_input_info pa_context_get_sink_input_info.restype = POINTER(pa_operation) pa_context_get_sink_input_info.argtypes = [POINTER(pa_context), c_uint32, pa_sink_input_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:344 pa_context_get_sink_input_info_list = _lib.pa_context_get_sink_input_info_list pa_context_get_sink_input_info_list.restype = POINTER(pa_operation) pa_context_get_sink_input_info_list.argtypes = [POINTER(pa_context), pa_sink_input_info_cb_t, POINTER(None)] class struct_pa_source_output_info(Structure): __slots__ = [ 'index', 'name', 'owner_module', 'client', 'source', 'sample_spec', 'channel_map', 'buffer_usec', 'source_usec', 'resample_method', 'driver', ] struct_pa_source_output_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('owner_module', c_uint32), ('client', c_uint32), ('source', c_uint32), ('sample_spec', pa_sample_spec), ('channel_map', pa_channel_map), ('buffer_usec', pa_usec_t), ('source_usec', pa_usec_t), ('resample_method', c_char_p), ('driver', c_char_p), ] pa_source_output_info = struct_pa_source_output_info # /usr/include/pulse/introspect.h:359 pa_source_output_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_source_output_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:362 # /usr/include/pulse/introspect.h:365 pa_context_get_source_output_info = _lib.pa_context_get_source_output_info pa_context_get_source_output_info.restype = POINTER(pa_operation) pa_context_get_source_output_info.argtypes = [POINTER(pa_context), c_uint32, pa_source_output_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:368 pa_context_get_source_output_info_list = _lib.pa_context_get_source_output_info_list pa_context_get_source_output_info_list.restype = POINTER(pa_operation) pa_context_get_source_output_info_list.argtypes = [POINTER(pa_context), pa_source_output_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:371 pa_context_set_sink_volume_by_index = _lib.pa_context_set_sink_volume_by_index pa_context_set_sink_volume_by_index.restype = POINTER(pa_operation) pa_context_set_sink_volume_by_index.argtypes = [POINTER(pa_context), c_uint32, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:374 pa_context_set_sink_volume_by_name = _lib.pa_context_set_sink_volume_by_name pa_context_set_sink_volume_by_name.restype = POINTER(pa_operation) pa_context_set_sink_volume_by_name.argtypes = [POINTER(pa_context), c_char_p, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:377 pa_context_set_sink_mute_by_index = _lib.pa_context_set_sink_mute_by_index pa_context_set_sink_mute_by_index.restype = POINTER(pa_operation) pa_context_set_sink_mute_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:380 pa_context_set_sink_mute_by_name = _lib.pa_context_set_sink_mute_by_name pa_context_set_sink_mute_by_name.restype = POINTER(pa_operation) pa_context_set_sink_mute_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:383 pa_context_set_sink_input_volume = _lib.pa_context_set_sink_input_volume pa_context_set_sink_input_volume.restype = POINTER(pa_operation) pa_context_set_sink_input_volume.argtypes = [POINTER(pa_context), c_uint32, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:386 pa_context_set_sink_input_mute = _lib.pa_context_set_sink_input_mute pa_context_set_sink_input_mute.restype = POINTER(pa_operation) pa_context_set_sink_input_mute.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:389 pa_context_set_source_volume_by_index = _lib.pa_context_set_source_volume_by_index pa_context_set_source_volume_by_index.restype = POINTER(pa_operation) pa_context_set_source_volume_by_index.argtypes = [POINTER(pa_context), c_uint32, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:392 pa_context_set_source_volume_by_name = _lib.pa_context_set_source_volume_by_name pa_context_set_source_volume_by_name.restype = POINTER(pa_operation) pa_context_set_source_volume_by_name.argtypes = [POINTER(pa_context), c_char_p, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:395 pa_context_set_source_mute_by_index = _lib.pa_context_set_source_mute_by_index pa_context_set_source_mute_by_index.restype = POINTER(pa_operation) pa_context_set_source_mute_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:398 pa_context_set_source_mute_by_name = _lib.pa_context_set_source_mute_by_name pa_context_set_source_mute_by_name.restype = POINTER(pa_operation) pa_context_set_source_mute_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)] class struct_pa_stat_info(Structure): __slots__ = [ 'memblock_total', 'memblock_total_size', 'memblock_allocated', 'memblock_allocated_size', 'scache_size', ] struct_pa_stat_info._fields_ = [ ('memblock_total', c_uint32), ('memblock_total_size', c_uint32), ('memblock_allocated', c_uint32), ('memblock_allocated_size', c_uint32), ('scache_size', c_uint32), ] pa_stat_info = struct_pa_stat_info # /usr/include/pulse/introspect.h:407 pa_stat_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_stat_info), POINTER(None)) # /usr/include/pulse/introspect.h:410 # /usr/include/pulse/introspect.h:413 pa_context_stat = _lib.pa_context_stat pa_context_stat.restype = POINTER(pa_operation) pa_context_stat.argtypes = [POINTER(pa_context), pa_stat_info_cb_t, POINTER(None)] class struct_pa_sample_info(Structure): __slots__ = [ 'index', 'name', 'volume', 'sample_spec', 'channel_map', 'duration', 'bytes', 'lazy', 'filename', ] struct_pa_sample_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('volume', pa_cvolume), ('sample_spec', pa_sample_spec), ('channel_map', pa_channel_map), ('duration', pa_usec_t), ('bytes', c_uint32), ('lazy', c_int), ('filename', c_char_p), ] pa_sample_info = struct_pa_sample_info # /usr/include/pulse/introspect.h:426 pa_sample_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_sample_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:429 # /usr/include/pulse/introspect.h:432 pa_context_get_sample_info_by_name = _lib.pa_context_get_sample_info_by_name pa_context_get_sample_info_by_name.restype = POINTER(pa_operation) pa_context_get_sample_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_sample_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:435 pa_context_get_sample_info_by_index = _lib.pa_context_get_sample_info_by_index pa_context_get_sample_info_by_index.restype = POINTER(pa_operation) pa_context_get_sample_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_sample_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:438 pa_context_get_sample_info_list = _lib.pa_context_get_sample_info_list pa_context_get_sample_info_list.restype = POINTER(pa_operation) pa_context_get_sample_info_list.argtypes = [POINTER(pa_context), pa_sample_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:441 pa_context_kill_client = _lib.pa_context_kill_client pa_context_kill_client.restype = POINTER(pa_operation) pa_context_kill_client.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:444 pa_context_kill_sink_input = _lib.pa_context_kill_sink_input pa_context_kill_sink_input.restype = POINTER(pa_operation) pa_context_kill_sink_input.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:447 pa_context_kill_source_output = _lib.pa_context_kill_source_output pa_context_kill_source_output.restype = POINTER(pa_operation) pa_context_kill_source_output.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)] pa_context_index_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_uint32, POINTER(None)) # /usr/include/pulse/introspect.h:450 # /usr/include/pulse/introspect.h:453 pa_context_load_module = _lib.pa_context_load_module pa_context_load_module.restype = POINTER(pa_operation) pa_context_load_module.argtypes = [POINTER(pa_context), c_char_p, c_char_p, pa_context_index_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:456 pa_context_unload_module = _lib.pa_context_unload_module pa_context_unload_module.restype = POINTER(pa_operation) pa_context_unload_module.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)] enum_pa_autoload_type = c_int PA_AUTOLOAD_SINK = 0 PA_AUTOLOAD_SOURCE = 1 pa_autoload_type_t = enum_pa_autoload_type # /usr/include/pulse/introspect.h:462 class struct_pa_autoload_info(Structure): __slots__ = [ 'index', 'name', 'type', 'module', 'argument', ] struct_pa_autoload_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('type', pa_autoload_type_t), ('module', c_char_p), ('argument', c_char_p), ] pa_autoload_info = struct_pa_autoload_info # /usr/include/pulse/introspect.h:471 pa_autoload_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_autoload_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:474 # /usr/include/pulse/introspect.h:477 pa_context_get_autoload_info_by_name = _lib.pa_context_get_autoload_info_by_name pa_context_get_autoload_info_by_name.restype = POINTER(pa_operation) pa_context_get_autoload_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_autoload_type_t, pa_autoload_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:480 pa_context_get_autoload_info_by_index = _lib.pa_context_get_autoload_info_by_index pa_context_get_autoload_info_by_index.restype = POINTER(pa_operation) pa_context_get_autoload_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_autoload_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:483 pa_context_get_autoload_info_list = _lib.pa_context_get_autoload_info_list pa_context_get_autoload_info_list.restype = POINTER(pa_operation) pa_context_get_autoload_info_list.argtypes = [POINTER(pa_context), pa_autoload_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:486 pa_context_add_autoload = _lib.pa_context_add_autoload pa_context_add_autoload.restype = POINTER(pa_operation) pa_context_add_autoload.argtypes = [POINTER(pa_context), c_char_p, pa_autoload_type_t, c_char_p, c_char_p, pa_context_index_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:489 pa_context_remove_autoload_by_name = _lib.pa_context_remove_autoload_by_name pa_context_remove_autoload_by_name.restype = POINTER(pa_operation) pa_context_remove_autoload_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_autoload_type_t, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:492 pa_context_remove_autoload_by_index = _lib.pa_context_remove_autoload_by_index pa_context_remove_autoload_by_index.restype = POINTER(pa_operation) pa_context_remove_autoload_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:495 pa_context_move_sink_input_by_name = _lib.pa_context_move_sink_input_by_name pa_context_move_sink_input_by_name.restype = POINTER(pa_operation) pa_context_move_sink_input_by_name.argtypes = [POINTER(pa_context), c_uint32, c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:498 pa_context_move_sink_input_by_index = _lib.pa_context_move_sink_input_by_index pa_context_move_sink_input_by_index.restype = POINTER(pa_operation) pa_context_move_sink_input_by_index.argtypes = [POINTER(pa_context), c_uint32, c_uint32, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:501 pa_context_move_source_output_by_name = _lib.pa_context_move_source_output_by_name pa_context_move_source_output_by_name.restype = POINTER(pa_operation) pa_context_move_source_output_by_name.argtypes = [POINTER(pa_context), c_uint32, c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:504 pa_context_move_source_output_by_index = _lib.pa_context_move_source_output_by_index pa_context_move_source_output_by_index.restype = POINTER(pa_operation) pa_context_move_source_output_by_index.argtypes = [POINTER(pa_context), c_uint32, c_uint32, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:507 pa_context_suspend_sink_by_name = _lib.pa_context_suspend_sink_by_name pa_context_suspend_sink_by_name.restype = POINTER(pa_operation) pa_context_suspend_sink_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:510 pa_context_suspend_sink_by_index = _lib.pa_context_suspend_sink_by_index pa_context_suspend_sink_by_index.restype = POINTER(pa_operation) pa_context_suspend_sink_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:513 pa_context_suspend_source_by_name = _lib.pa_context_suspend_source_by_name pa_context_suspend_source_by_name.restype = POINTER(pa_operation) pa_context_suspend_source_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:516 pa_context_suspend_source_by_index = _lib.pa_context_suspend_source_by_index pa_context_suspend_source_by_index.restype = POINTER(pa_operation) pa_context_suspend_source_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)] pa_context_subscribe_cb_t = CFUNCTYPE(None, POINTER(pa_context), pa_subscription_event_type_t, c_uint32, POINTER(None)) # /usr/include/pulse/subscribe.h:54 # /usr/include/pulse/subscribe.h:57 pa_context_subscribe = _lib.pa_context_subscribe pa_context_subscribe.restype = POINTER(pa_operation) pa_context_subscribe.argtypes = [POINTER(pa_context), pa_subscription_mask_t, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/subscribe.h:60 pa_context_set_subscribe_callback = _lib.pa_context_set_subscribe_callback pa_context_set_subscribe_callback.restype = None pa_context_set_subscribe_callback.argtypes = [POINTER(pa_context), pa_context_subscribe_cb_t, POINTER(None)] # /usr/include/pulse/scache.h:83 pa_stream_connect_upload = _lib.pa_stream_connect_upload pa_stream_connect_upload.restype = c_int pa_stream_connect_upload.argtypes = [POINTER(pa_stream), c_size_t] # /usr/include/pulse/scache.h:87 pa_stream_finish_upload = _lib.pa_stream_finish_upload pa_stream_finish_upload.restype = c_int pa_stream_finish_upload.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/scache.h:90 pa_context_play_sample = _lib.pa_context_play_sample pa_context_play_sample.restype = POINTER(pa_operation) pa_context_play_sample.argtypes = [POINTER(pa_context), c_char_p, c_char_p, pa_volume_t, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/scache.h:99 pa_context_remove_sample = _lib.pa_context_remove_sample pa_context_remove_sample.restype = POINTER(pa_operation) pa_context_remove_sample.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/version.h:43 pa_get_library_version = _lib.pa_get_library_version pa_get_library_version.restype = c_char_p pa_get_library_version.argtypes = [] PA_API_VERSION = 11 # /usr/include/pulse/version.h:48 PA_PROTOCOL_VERSION = 12 # /usr/include/pulse/version.h:52 # /usr/include/pulse/error.h:37 pa_strerror = _lib.pa_strerror pa_strerror.restype = c_char_p pa_strerror.argtypes = [c_int] # /usr/include/pulse/xmalloc.h:40 pa_xmalloc = _lib.pa_xmalloc pa_xmalloc.restype = POINTER(c_void) pa_xmalloc.argtypes = [c_size_t] # /usr/include/pulse/xmalloc.h:43 pa_xmalloc0 = _lib.pa_xmalloc0 pa_xmalloc0.restype = POINTER(c_void) pa_xmalloc0.argtypes = [c_size_t] # /usr/include/pulse/xmalloc.h:46 pa_xrealloc = _lib.pa_xrealloc pa_xrealloc.restype = POINTER(c_void) pa_xrealloc.argtypes = [POINTER(None), c_size_t] # /usr/include/pulse/xmalloc.h:49 pa_xfree = _lib.pa_xfree pa_xfree.restype = None pa_xfree.argtypes = [POINTER(None)] # /usr/include/pulse/xmalloc.h:52 pa_xstrdup = _lib.pa_xstrdup pa_xstrdup.restype = c_char_p pa_xstrdup.argtypes = [c_char_p] # /usr/include/pulse/xmalloc.h:55 pa_xstrndup = _lib.pa_xstrndup pa_xstrndup.restype = c_char_p pa_xstrndup.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/xmalloc.h:58 pa_xmemdup = _lib.pa_xmemdup pa_xmemdup.restype = POINTER(c_void) pa_xmemdup.argtypes = [POINTER(None), c_size_t] # /usr/include/pulse/utf8.h:37 pa_utf8_valid = _lib.pa_utf8_valid pa_utf8_valid.restype = c_char_p pa_utf8_valid.argtypes = [c_char_p] # /usr/include/pulse/utf8.h:40 pa_utf8_filter = _lib.pa_utf8_filter pa_utf8_filter.restype = c_char_p pa_utf8_filter.argtypes = [c_char_p] # /usr/include/pulse/utf8.h:43 pa_utf8_to_locale = _lib.pa_utf8_to_locale pa_utf8_to_locale.restype = c_char_p pa_utf8_to_locale.argtypes = [c_char_p] # /usr/include/pulse/utf8.h:46 pa_locale_to_utf8 = _lib.pa_locale_to_utf8 pa_locale_to_utf8.restype = c_char_p pa_locale_to_utf8.argtypes = [c_char_p] class struct_pa_threaded_mainloop(Structure): __slots__ = [ ] struct_pa_threaded_mainloop._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_threaded_mainloop(Structure): __slots__ = [ ] struct_pa_threaded_mainloop._fields_ = [ ('_opaque_struct', c_int) ] pa_threaded_mainloop = struct_pa_threaded_mainloop # /usr/include/pulse/thread-mainloop.h:242 # /usr/include/pulse/thread-mainloop.h:247 pa_threaded_mainloop_new = _lib.pa_threaded_mainloop_new pa_threaded_mainloop_new.restype = POINTER(pa_threaded_mainloop) pa_threaded_mainloop_new.argtypes = [] # /usr/include/pulse/thread-mainloop.h:252 pa_threaded_mainloop_free = _lib.pa_threaded_mainloop_free pa_threaded_mainloop_free.restype = None pa_threaded_mainloop_free.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:255 pa_threaded_mainloop_start = _lib.pa_threaded_mainloop_start pa_threaded_mainloop_start.restype = c_int pa_threaded_mainloop_start.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:259 pa_threaded_mainloop_stop = _lib.pa_threaded_mainloop_stop pa_threaded_mainloop_stop.restype = None pa_threaded_mainloop_stop.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:267 pa_threaded_mainloop_lock = _lib.pa_threaded_mainloop_lock pa_threaded_mainloop_lock.restype = None pa_threaded_mainloop_lock.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:270 pa_threaded_mainloop_unlock = _lib.pa_threaded_mainloop_unlock pa_threaded_mainloop_unlock.restype = None pa_threaded_mainloop_unlock.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:279 pa_threaded_mainloop_wait = _lib.pa_threaded_mainloop_wait pa_threaded_mainloop_wait.restype = None pa_threaded_mainloop_wait.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:286 pa_threaded_mainloop_signal = _lib.pa_threaded_mainloop_signal pa_threaded_mainloop_signal.restype = None pa_threaded_mainloop_signal.argtypes = [POINTER(pa_threaded_mainloop), c_int] # /usr/include/pulse/thread-mainloop.h:292 pa_threaded_mainloop_accept = _lib.pa_threaded_mainloop_accept pa_threaded_mainloop_accept.restype = None pa_threaded_mainloop_accept.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:295 pa_threaded_mainloop_get_retval = _lib.pa_threaded_mainloop_get_retval pa_threaded_mainloop_get_retval.restype = c_int pa_threaded_mainloop_get_retval.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:298 pa_threaded_mainloop_get_api = _lib.pa_threaded_mainloop_get_api pa_threaded_mainloop_get_api.restype = POINTER(pa_mainloop_api) pa_threaded_mainloop_get_api.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:301 pa_threaded_mainloop_in_thread = _lib.pa_threaded_mainloop_in_thread pa_threaded_mainloop_in_thread.restype = c_int pa_threaded_mainloop_in_thread.argtypes = [POINTER(pa_threaded_mainloop)] class struct_pa_mainloop(Structure): __slots__ = [ ] struct_pa_mainloop._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_mainloop(Structure): __slots__ = [ ] struct_pa_mainloop._fields_ = [ ('_opaque_struct', c_int) ] pa_mainloop = struct_pa_mainloop # /usr/include/pulse/mainloop.h:79 # /usr/include/pulse/mainloop.h:82 pa_mainloop_new = _lib.pa_mainloop_new pa_mainloop_new.restype = POINTER(pa_mainloop) pa_mainloop_new.argtypes = [] # /usr/include/pulse/mainloop.h:85 pa_mainloop_free = _lib.pa_mainloop_free pa_mainloop_free.restype = None pa_mainloop_free.argtypes = [POINTER(pa_mainloop)] # /usr/include/pulse/mainloop.h:90 pa_mainloop_prepare = _lib.pa_mainloop_prepare pa_mainloop_prepare.restype = c_int pa_mainloop_prepare.argtypes = [POINTER(pa_mainloop), c_int] # /usr/include/pulse/mainloop.h:93 pa_mainloop_poll = _lib.pa_mainloop_poll pa_mainloop_poll.restype = c_int pa_mainloop_poll.argtypes = [POINTER(pa_mainloop)] # /usr/include/pulse/mainloop.h:97 pa_mainloop_dispatch = _lib.pa_mainloop_dispatch pa_mainloop_dispatch.restype = c_int pa_mainloop_dispatch.argtypes = [POINTER(pa_mainloop)] # /usr/include/pulse/mainloop.h:100 pa_mainloop_get_retval = _lib.pa_mainloop_get_retval pa_mainloop_get_retval.restype = c_int pa_mainloop_get_retval.argtypes = [POINTER(pa_mainloop)] # /usr/include/pulse/mainloop.h:108 pa_mainloop_iterate = _lib.pa_mainloop_iterate pa_mainloop_iterate.restype = c_int pa_mainloop_iterate.argtypes = [POINTER(pa_mainloop), c_int, POINTER(c_int)] # /usr/include/pulse/mainloop.h:111 pa_mainloop_run = _lib.pa_mainloop_run pa_mainloop_run.restype = c_int pa_mainloop_run.argtypes = [POINTER(pa_mainloop), POINTER(c_int)] # /usr/include/pulse/mainloop.h:114 pa_mainloop_get_api = _lib.pa_mainloop_get_api pa_mainloop_get_api.restype = POINTER(pa_mainloop_api) pa_mainloop_get_api.argtypes = [POINTER(pa_mainloop)] # /usr/include/pulse/mainloop.h:117 pa_mainloop_quit = _lib.pa_mainloop_quit pa_mainloop_quit.restype = None pa_mainloop_quit.argtypes = [POINTER(pa_mainloop), c_int] # /usr/include/pulse/mainloop.h:120 pa_mainloop_wakeup = _lib.pa_mainloop_wakeup pa_mainloop_wakeup.restype = None pa_mainloop_wakeup.argtypes = [POINTER(pa_mainloop)] class struct_pollfd(Structure): __slots__ = [ ] struct_pollfd._fields_ = [ ('_opaque_struct', c_int) ] class struct_pollfd(Structure): __slots__ = [ ] struct_pollfd._fields_ = [ ('_opaque_struct', c_int) ] pa_poll_func = CFUNCTYPE(c_int, POINTER(struct_pollfd), c_ulong, c_int, POINTER(None)) # /usr/include/pulse/mainloop.h:123 # /usr/include/pulse/mainloop.h:126 pa_mainloop_set_poll_func = _lib.pa_mainloop_set_poll_func pa_mainloop_set_poll_func.restype = None pa_mainloop_set_poll_func.argtypes = [POINTER(pa_mainloop), pa_poll_func, POINTER(None)] # /usr/include/pulse/mainloop-signal.h:43 pa_signal_init = _lib.pa_signal_init pa_signal_init.restype = c_int pa_signal_init.argtypes = [POINTER(pa_mainloop_api)] # /usr/include/pulse/mainloop-signal.h:46 pa_signal_done = _lib.pa_signal_done pa_signal_done.restype = None pa_signal_done.argtypes = [] class struct_pa_signal_event(Structure): __slots__ = [ ] struct_pa_signal_event._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_signal_event(Structure): __slots__ = [ ] struct_pa_signal_event._fields_ = [ ('_opaque_struct', c_int) ] pa_signal_event = struct_pa_signal_event # /usr/include/pulse/mainloop-signal.h:49 # /usr/include/pulse/mainloop-signal.h:52 pa_signal_new = _lib.pa_signal_new pa_signal_new.restype = POINTER(pa_signal_event) pa_signal_new.argtypes = [c_int, CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_signal_event), c_int, POINTER(None)), POINTER(None)] # /usr/include/pulse/mainloop-signal.h:55 pa_signal_free = _lib.pa_signal_free pa_signal_free.restype = None pa_signal_free.argtypes = [POINTER(pa_signal_event)] # /usr/include/pulse/mainloop-signal.h:58 pa_signal_set_destroy = _lib.pa_signal_set_destroy pa_signal_set_destroy.restype = None pa_signal_set_destroy.argtypes = [POINTER(pa_signal_event), CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_signal_event), POINTER(None))] # /usr/include/pulse/util.h:38 pa_get_user_name = _lib.pa_get_user_name pa_get_user_name.restype = c_char_p pa_get_user_name.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/util.h:41 pa_get_host_name = _lib.pa_get_host_name pa_get_host_name.restype = c_char_p pa_get_host_name.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/util.h:44 pa_get_fqdn = _lib.pa_get_fqdn pa_get_fqdn.restype = c_char_p pa_get_fqdn.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/util.h:47 pa_get_home_dir = _lib.pa_get_home_dir pa_get_home_dir.restype = c_char_p pa_get_home_dir.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/util.h:51 pa_get_binary_name = _lib.pa_get_binary_name pa_get_binary_name.restype = c_char_p pa_get_binary_name.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/util.h:55 pa_path_get_filename = _lib.pa_path_get_filename pa_path_get_filename.restype = c_char_p pa_path_get_filename.argtypes = [c_char_p] # /usr/include/pulse/util.h:58 pa_msleep = _lib.pa_msleep pa_msleep.restype = c_int pa_msleep.argtypes = [c_ulong] PA_MSEC_PER_SEC = 1000 # /usr/include/pulse/timeval.h:36 PA_USEC_PER_SEC = 1000000 # /usr/include/pulse/timeval.h:37 PA_NSEC_PER_SEC = 1000000000 # /usr/include/pulse/timeval.h:38 PA_USEC_PER_MSEC = 1000 # /usr/include/pulse/timeval.h:39 class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:44 pa_gettimeofday = _lib.pa_gettimeofday pa_gettimeofday.restype = POINTER(struct_timeval) pa_gettimeofday.argtypes = [POINTER(struct_timeval)] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:48 pa_timeval_diff = _lib.pa_timeval_diff pa_timeval_diff.restype = pa_usec_t pa_timeval_diff.argtypes = [POINTER(struct_timeval), POINTER(struct_timeval)] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:51 pa_timeval_cmp = _lib.pa_timeval_cmp pa_timeval_cmp.restype = c_int pa_timeval_cmp.argtypes = [POINTER(struct_timeval), POINTER(struct_timeval)] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:54 pa_timeval_age = _lib.pa_timeval_age pa_timeval_age.restype = pa_usec_t pa_timeval_age.argtypes = [POINTER(struct_timeval)] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:57 pa_timeval_add = _lib.pa_timeval_add pa_timeval_add.restype = POINTER(struct_timeval) pa_timeval_add.argtypes = [POINTER(struct_timeval), pa_usec_t] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:60 pa_timeval_store = _lib.pa_timeval_store pa_timeval_store.restype = POINTER(struct_timeval) pa_timeval_store.argtypes = [POINTER(struct_timeval), pa_usec_t] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:63 pa_timeval_load = _lib.pa_timeval_load pa_timeval_load.restype = pa_usec_t pa_timeval_load.argtypes = [POINTER(struct_timeval)] __all__ = ['pa_mainloop_api', 'pa_io_event_flags_t', 'PA_IO_EVENT_NULL', 'PA_IO_EVENT_INPUT', 'PA_IO_EVENT_OUTPUT', 'PA_IO_EVENT_HANGUP', 'PA_IO_EVENT_ERROR', 'pa_io_event', 'pa_io_event_cb_t', 'pa_io_event_destroy_cb_t', 'pa_time_event', 'pa_time_event_cb_t', 'pa_time_event_destroy_cb_t', 'pa_defer_event', 'pa_defer_event_cb_t', 'pa_defer_event_destroy_cb_t', 'pa_mainloop_api_once', 'PA_CHANNELS_MAX', 'PA_RATE_MAX', 'pa_sample_format_t', 'PA_SAMPLE_U8', 'PA_SAMPLE_ALAW', 'PA_SAMPLE_ULAW', 'PA_SAMPLE_S16LE', 'PA_SAMPLE_S16BE', 'PA_SAMPLE_FLOAT32LE', 'PA_SAMPLE_FLOAT32BE', 'PA_SAMPLE_S32LE', 'PA_SAMPLE_S32BE', 'PA_SAMPLE_MAX', 'PA_SAMPLE_INVALID', 'pa_sample_spec', 'pa_usec_t', 'pa_bytes_per_second', 'pa_frame_size', 'pa_sample_size', 'pa_bytes_to_usec', 'pa_usec_to_bytes', 'pa_sample_spec_valid', 'pa_sample_spec_equal', 'pa_sample_format_to_string', 'pa_parse_sample_format', 'PA_SAMPLE_SPEC_SNPRINT_MAX', 'pa_sample_spec_snprint', 'pa_bytes_snprint', 'pa_context_state_t', 'PA_CONTEXT_UNCONNECTED', 'PA_CONTEXT_CONNECTING', 'PA_CONTEXT_AUTHORIZING', 'PA_CONTEXT_SETTING_NAME', 'PA_CONTEXT_READY', 'PA_CONTEXT_FAILED', 'PA_CONTEXT_TERMINATED', 'pa_stream_state_t', 'PA_STREAM_UNCONNECTED', 'PA_STREAM_CREATING', 'PA_STREAM_READY', 'PA_STREAM_FAILED', 'PA_STREAM_TERMINATED', 'pa_operation_state_t', 'PA_OPERATION_RUNNING', 'PA_OPERATION_DONE', 'PA_OPERATION_CANCELED', 'pa_context_flags_t', 'PA_CONTEXT_NOAUTOSPAWN', 'pa_stream_direction_t', 'PA_STREAM_NODIRECTION', 'PA_STREAM_PLAYBACK', 'PA_STREAM_RECORD', 'PA_STREAM_UPLOAD', 'pa_stream_flags_t', 'PA_STREAM_START_CORKED', 'PA_STREAM_INTERPOLATE_TIMING', 'PA_STREAM_NOT_MONOTONOUS', 'PA_STREAM_AUTO_TIMING_UPDATE', 'PA_STREAM_NO_REMAP_CHANNELS', 'PA_STREAM_NO_REMIX_CHANNELS', 'PA_STREAM_FIX_FORMAT', 'PA_STREAM_FIX_RATE', 'PA_STREAM_FIX_CHANNELS', 'PA_STREAM_DONT_MOVE', 'PA_STREAM_VARIABLE_RATE', 'pa_buffer_attr', 'pa_subscription_mask_t', 'PA_SUBSCRIPTION_MASK_NULL', 'PA_SUBSCRIPTION_MASK_SINK', 'PA_SUBSCRIPTION_MASK_SOURCE', 'PA_SUBSCRIPTION_MASK_SINK_INPUT', 'PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT', 'PA_SUBSCRIPTION_MASK_MODULE', 'PA_SUBSCRIPTION_MASK_CLIENT', 'PA_SUBSCRIPTION_MASK_SAMPLE_CACHE', 'PA_SUBSCRIPTION_MASK_SERVER', 'PA_SUBSCRIPTION_MASK_AUTOLOAD', 'PA_SUBSCRIPTION_MASK_ALL', 'pa_subscription_event_type_t', 'PA_SUBSCRIPTION_EVENT_SINK', 'PA_SUBSCRIPTION_EVENT_SOURCE', 'PA_SUBSCRIPTION_EVENT_SINK_INPUT', 'PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT', 'PA_SUBSCRIPTION_EVENT_MODULE', 'PA_SUBSCRIPTION_EVENT_CLIENT', 'PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE', 'PA_SUBSCRIPTION_EVENT_SERVER', 'PA_SUBSCRIPTION_EVENT_AUTOLOAD', 'PA_SUBSCRIPTION_EVENT_FACILITY_MASK', 'PA_SUBSCRIPTION_EVENT_NEW', 'PA_SUBSCRIPTION_EVENT_CHANGE', 'PA_SUBSCRIPTION_EVENT_REMOVE', 'PA_SUBSCRIPTION_EVENT_TYPE_MASK', 'pa_timing_info', 'pa_spawn_api', 'pa_seek_mode_t', 'PA_SEEK_RELATIVE', 'PA_SEEK_ABSOLUTE', 'PA_SEEK_RELATIVE_ON_READ', 'PA_SEEK_RELATIVE_END', 'pa_sink_flags_t', 'PA_SINK_HW_VOLUME_CTRL', 'PA_SINK_LATENCY', 'PA_SINK_HARDWARE', 'PA_SINK_NETWORK', 'pa_source_flags_t', 'PA_SOURCE_HW_VOLUME_CTRL', 'PA_SOURCE_LATENCY', 'PA_SOURCE_HARDWARE', 'PA_SOURCE_NETWORK', 'pa_free_cb_t', 'pa_operation', 'pa_operation_ref', 'pa_operation_unref', 'pa_operation_cancel', 'pa_operation_get_state', 'pa_context', 'pa_context_notify_cb_t', 'pa_context_success_cb_t', 'pa_context_new', 'pa_context_unref', 'pa_context_ref', 'pa_context_set_state_callback', 'pa_context_errno', 'pa_context_is_pending', 'pa_context_get_state', 'pa_context_connect', 'pa_context_disconnect', 'pa_context_drain', 'pa_context_exit_daemon', 'pa_context_set_default_sink', 'pa_context_set_default_source', 'pa_context_is_local', 'pa_context_set_name', 'pa_context_get_server', 'pa_context_get_protocol_version', 'pa_context_get_server_protocol_version', 'pa_channel_position_t', 'PA_CHANNEL_POSITION_INVALID', 'PA_CHANNEL_POSITION_MONO', 'PA_CHANNEL_POSITION_LEFT', 'PA_CHANNEL_POSITION_RIGHT', 'PA_CHANNEL_POSITION_CENTER', 'PA_CHANNEL_POSITION_FRONT_LEFT', 'PA_CHANNEL_POSITION_FRONT_RIGHT', 'PA_CHANNEL_POSITION_FRONT_CENTER', 'PA_CHANNEL_POSITION_REAR_CENTER', 'PA_CHANNEL_POSITION_REAR_LEFT', 'PA_CHANNEL_POSITION_REAR_RIGHT', 'PA_CHANNEL_POSITION_LFE', 'PA_CHANNEL_POSITION_SUBWOOFER', 'PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER', 'PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER', 'PA_CHANNEL_POSITION_SIDE_LEFT', 'PA_CHANNEL_POSITION_SIDE_RIGHT', 'PA_CHANNEL_POSITION_AUX0', 'PA_CHANNEL_POSITION_AUX1', 'PA_CHANNEL_POSITION_AUX2', 'PA_CHANNEL_POSITION_AUX3', 'PA_CHANNEL_POSITION_AUX4', 'PA_CHANNEL_POSITION_AUX5', 'PA_CHANNEL_POSITION_AUX6', 'PA_CHANNEL_POSITION_AUX7', 'PA_CHANNEL_POSITION_AUX8', 'PA_CHANNEL_POSITION_AUX9', 'PA_CHANNEL_POSITION_AUX10', 'PA_CHANNEL_POSITION_AUX11', 'PA_CHANNEL_POSITION_AUX12', 'PA_CHANNEL_POSITION_AUX13', 'PA_CHANNEL_POSITION_AUX14', 'PA_CHANNEL_POSITION_AUX15', 'PA_CHANNEL_POSITION_AUX16', 'PA_CHANNEL_POSITION_AUX17', 'PA_CHANNEL_POSITION_AUX18', 'PA_CHANNEL_POSITION_AUX19', 'PA_CHANNEL_POSITION_AUX20', 'PA_CHANNEL_POSITION_AUX21', 'PA_CHANNEL_POSITION_AUX22', 'PA_CHANNEL_POSITION_AUX23', 'PA_CHANNEL_POSITION_AUX24', 'PA_CHANNEL_POSITION_AUX25', 'PA_CHANNEL_POSITION_AUX26', 'PA_CHANNEL_POSITION_AUX27', 'PA_CHANNEL_POSITION_AUX28', 'PA_CHANNEL_POSITION_AUX29', 'PA_CHANNEL_POSITION_AUX30', 'PA_CHANNEL_POSITION_AUX31', 'PA_CHANNEL_POSITION_TOP_CENTER', 'PA_CHANNEL_POSITION_TOP_FRONT_LEFT', 'PA_CHANNEL_POSITION_TOP_FRONT_RIGHT', 'PA_CHANNEL_POSITION_TOP_FRONT_CENTER', 'PA_CHANNEL_POSITION_TOP_REAR_LEFT', 'PA_CHANNEL_POSITION_TOP_REAR_RIGHT', 'PA_CHANNEL_POSITION_TOP_REAR_CENTER', 'PA_CHANNEL_POSITION_MAX', 'pa_channel_map_def_t', 'PA_CHANNEL_MAP_AIFF', 'PA_CHANNEL_MAP_ALSA', 'PA_CHANNEL_MAP_AUX', 'PA_CHANNEL_MAP_WAVEEX', 'PA_CHANNEL_MAP_OSS', 'PA_CHANNEL_MAP_DEFAULT', 'pa_channel_map', 'pa_channel_map_init', 'pa_channel_map_init_mono', 'pa_channel_map_init_stereo', 'pa_channel_map_init_auto', 'pa_channel_position_to_string', 'pa_channel_position_to_pretty_string', 'PA_CHANNEL_MAP_SNPRINT_MAX', 'pa_channel_map_snprint', 'pa_channel_map_parse', 'pa_channel_map_equal', 'pa_channel_map_valid', 'pa_volume_t', 'PA_VOLUME_NORM', 'PA_VOLUME_MUTED', 'pa_cvolume', 'pa_cvolume_equal', 'pa_cvolume_set', 'PA_CVOLUME_SNPRINT_MAX', 'pa_cvolume_snprint', 'pa_cvolume_avg', 'pa_cvolume_valid', 'pa_cvolume_channels_equal_to', 'pa_sw_volume_multiply', 'pa_sw_cvolume_multiply', 'pa_sw_volume_from_dB', 'pa_sw_volume_to_dB', 'pa_sw_volume_from_linear', 'pa_sw_volume_to_linear', 'PA_DECIBEL_MININFTY', 'pa_stream', 'pa_stream_success_cb_t', 'pa_stream_request_cb_t', 'pa_stream_notify_cb_t', 'pa_stream_new', 'pa_stream_unref', 'pa_stream_ref', 'pa_stream_get_state', 'pa_stream_get_context', 'pa_stream_get_index', 'pa_stream_get_device_index', 'pa_stream_get_device_name', 'pa_stream_is_suspended', 'pa_stream_connect_playback', 'pa_stream_connect_record', 'pa_stream_disconnect', 'pa_stream_write', 'pa_stream_peek', 'pa_stream_drop', 'pa_stream_writable_size', 'pa_stream_readable_size', 'pa_stream_drain', 'pa_stream_update_timing_info', 'pa_stream_set_state_callback', 'pa_stream_set_write_callback', 'pa_stream_set_read_callback', 'pa_stream_set_overflow_callback', 'pa_stream_set_underflow_callback', 'pa_stream_set_latency_update_callback', 'pa_stream_set_moved_callback', 'pa_stream_set_suspended_callback', 'pa_stream_cork', 'pa_stream_flush', 'pa_stream_prebuf', 'pa_stream_trigger', 'pa_stream_set_name', 'pa_stream_get_time', 'pa_stream_get_latency', 'pa_stream_get_timing_info', 'pa_stream_get_sample_spec', 'pa_stream_get_channel_map', 'pa_stream_get_buffer_attr', 'pa_stream_set_buffer_attr', 'pa_stream_update_sample_rate', 'pa_sink_info', 'pa_sink_info_cb_t', 'pa_context_get_sink_info_by_name', 'pa_context_get_sink_info_by_index', 'pa_context_get_sink_info_list', 'pa_source_info', 'pa_source_info_cb_t', 'pa_context_get_source_info_by_name', 'pa_context_get_source_info_by_index', 'pa_context_get_source_info_list', 'pa_server_info', 'pa_server_info_cb_t', 'pa_context_get_server_info', 'pa_module_info', 'pa_module_info_cb_t', 'pa_context_get_module_info', 'pa_context_get_module_info_list', 'pa_client_info', 'pa_client_info_cb_t', 'pa_context_get_client_info', 'pa_context_get_client_info_list', 'pa_sink_input_info', 'pa_sink_input_info_cb_t', 'pa_context_get_sink_input_info', 'pa_context_get_sink_input_info_list', 'pa_source_output_info', 'pa_source_output_info_cb_t', 'pa_context_get_source_output_info', 'pa_context_get_source_output_info_list', 'pa_context_set_sink_volume_by_index', 'pa_context_set_sink_volume_by_name', 'pa_context_set_sink_mute_by_index', 'pa_context_set_sink_mute_by_name', 'pa_context_set_sink_input_volume', 'pa_context_set_sink_input_mute', 'pa_context_set_source_volume_by_index', 'pa_context_set_source_volume_by_name', 'pa_context_set_source_mute_by_index', 'pa_context_set_source_mute_by_name', 'pa_stat_info', 'pa_stat_info_cb_t', 'pa_context_stat', 'pa_sample_info', 'pa_sample_info_cb_t', 'pa_context_get_sample_info_by_name', 'pa_context_get_sample_info_by_index', 'pa_context_get_sample_info_list', 'pa_context_kill_client', 'pa_context_kill_sink_input', 'pa_context_kill_source_output', 'pa_context_index_cb_t', 'pa_context_load_module', 'pa_context_unload_module', 'pa_autoload_type_t', 'PA_AUTOLOAD_SINK', 'PA_AUTOLOAD_SOURCE', 'pa_autoload_info', 'pa_autoload_info_cb_t', 'pa_context_get_autoload_info_by_name', 'pa_context_get_autoload_info_by_index', 'pa_context_get_autoload_info_list', 'pa_context_add_autoload', 'pa_context_remove_autoload_by_name', 'pa_context_remove_autoload_by_index', 'pa_context_move_sink_input_by_name', 'pa_context_move_sink_input_by_index', 'pa_context_move_source_output_by_name', 'pa_context_move_source_output_by_index', 'pa_context_suspend_sink_by_name', 'pa_context_suspend_sink_by_index', 'pa_context_suspend_source_by_name', 'pa_context_suspend_source_by_index', 'pa_context_subscribe_cb_t', 'pa_context_subscribe', 'pa_context_set_subscribe_callback', 'pa_stream_connect_upload', 'pa_stream_finish_upload', 'pa_context_play_sample', 'pa_context_remove_sample', 'pa_get_library_version', 'PA_API_VERSION', 'PA_PROTOCOL_VERSION', 'pa_strerror', 'pa_xmalloc', 'pa_xmalloc0', 'pa_xrealloc', 'pa_xfree', 'pa_xstrdup', 'pa_xstrndup', 'pa_xmemdup', 'pa_utf8_valid', 'pa_utf8_filter', 'pa_utf8_to_locale', 'pa_locale_to_utf8', 'pa_threaded_mainloop', 'pa_threaded_mainloop_new', 'pa_threaded_mainloop_free', 'pa_threaded_mainloop_start', 'pa_threaded_mainloop_stop', 'pa_threaded_mainloop_lock', 'pa_threaded_mainloop_unlock', 'pa_threaded_mainloop_wait', 'pa_threaded_mainloop_signal', 'pa_threaded_mainloop_accept', 'pa_threaded_mainloop_get_retval', 'pa_threaded_mainloop_get_api', 'pa_threaded_mainloop_in_thread', 'pa_mainloop', 'pa_mainloop_new', 'pa_mainloop_free', 'pa_mainloop_prepare', 'pa_mainloop_poll', 'pa_mainloop_dispatch', 'pa_mainloop_get_retval', 'pa_mainloop_iterate', 'pa_mainloop_run', 'pa_mainloop_get_api', 'pa_mainloop_quit', 'pa_mainloop_wakeup', 'pa_poll_func', 'pa_mainloop_set_poll_func', 'pa_signal_init', 'pa_signal_done', 'pa_signal_event', 'pa_signal_new', 'pa_signal_free', 'pa_signal_set_destroy', 'pa_get_user_name', 'pa_get_host_name', 'pa_get_fqdn', 'pa_get_home_dir', 'pa_get_binary_name', 'pa_path_get_filename', 'pa_msleep', 'PA_MSEC_PER_SEC', 'PA_USEC_PER_SEC', 'PA_NSEC_PER_SEC', 'PA_USEC_PER_MSEC', 'pa_gettimeofday', 'pa_timeval_diff', 'pa_timeval_cmp', 'pa_timeval_age', 'pa_timeval_add', 'pa_timeval_store', 'pa_timeval_load']
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import sys import lib_pulseaudio as pa from pyglet.media import AbstractAudioDriver, AbstractAudioPlayer, \ AbstractListener, MediaException, MediaEvent import pyglet _debug = pyglet.options['debug_media'] def check(result): if result < 0: error = pa.pa_context_errno(context._context) raise MediaException(pa.pa_strerror(error)) return result def check_not_null(value): if not value: error = pa.pa_context_errno(context._context) raise MediaException(pa.pa_strerror(error)) return value class PulseAudioDriver(AbstractAudioDriver): _context = None def __init__(self): self.threaded_mainloop = pa.pa_threaded_mainloop_new() self.mainloop = pa.pa_threaded_mainloop_get_api( self.threaded_mainloop) self._players = pyglet.app.WeakSet() self._listener = PulseAudioListener(self) def create_audio_player(self, source_group, player): player = PulseAudioPlayer(source_group, player) self._players.add(player) return player def connect(self, server=None): '''Connect to pulseaudio server. :Parameters: `server` : str Server to connect to, or ``None`` for the default local server (which may be spawned as a daemon if no server is found). ''' # TODO disconnect from old assert not self._context, 'Already connected' # Create context app_name = self.get_app_name() self._context = pa.pa_context_new(self.mainloop, app_name) # Context state callback self._state_cb_func = pa.pa_context_notify_cb_t(self._state_cb) pa.pa_context_set_state_callback(self._context, self._state_cb_func, None) # Connect check( pa.pa_context_connect(self._context, server, 0, None) ) self.lock() check( pa.pa_threaded_mainloop_start(self.threaded_mainloop) ) try: # Wait for context ready. self.wait() if pa.pa_context_get_state(self._context) != pa.PA_CONTEXT_READY: check(-1) finally: self.unlock() def _state_cb(self, context, userdata): if _debug: print 'context state cb' state = pa.pa_context_get_state(self._context) if state in (pa.PA_CONTEXT_READY, pa.PA_CONTEXT_TERMINATED, pa.PA_CONTEXT_FAILED): self.signal() def lock(self): '''Lock the threaded mainloop against events. Required for all calls into PA.''' pa.pa_threaded_mainloop_lock(self.threaded_mainloop) def unlock(self): '''Unlock the mainloop thread.''' pa.pa_threaded_mainloop_unlock(self.threaded_mainloop) def signal(self): '''Signal the mainloop thread to break from a wait.''' pa.pa_threaded_mainloop_signal(self.threaded_mainloop, 0) def wait(self): '''Wait for a signal.''' pa.pa_threaded_mainloop_wait(self.threaded_mainloop) def sync_operation(self, op): '''Wait for an operation to be done or cancelled, then release it. Uses a busy-loop -- make sure a callback is registered to signal this listener.''' while pa.pa_operation_get_state(op) == pa.PA_OPERATION_RUNNING: pa.pa_threaded_mainloop_wait(self.threaded_mainloop) pa.pa_operation_unref(op) def async_operation(self, op): '''Release the operation immediately without waiting for it to complete.''' pa.pa_operation_unref(op) def get_app_name(self): '''Get the application name as advertised to the pulseaudio server.''' # TODO move app name into pyglet.app (also useful for OS X menu bar?). return sys.argv[0] def dump_debug_info(self): print 'Client version: ', pa.pa_get_library_version() print 'Server: ', pa.pa_context_get_server(self._context) print 'Protocol: ', pa.pa_context_get_protocol_version( self._context) print 'Server protocol:', pa.pa_context_get_server_protocol_version( self._context) print 'Local context: ', ( pa.pa_context_is_local(self._context) and 'Yes' or 'No') def delete(self): '''Completely shut down pulseaudio client.''' self.lock() pa.pa_context_unref(self._context) self.unlock() pa.pa_threaded_mainloop_stop(self.threaded_mainloop) pa.pa_threaded_mainloop_free(self.threaded_mainloop) self.threaded_mainloop = None self.mainloop = None def get_listener(self): return self._listener class PulseAudioListener(AbstractListener): def __init__(self, driver): self.driver = driver def _set_volume(self, volume): self._volume = volume for player in self.driver._players: player.set_volume(player._volume) def _set_position(self, position): self._position = position def _set_forward_orientation(self, orientation): self._forward_orientation = orientation def _set_up_orientation(self, orientation): self._up_orientation = orientation class PulseAudioPlayer(AbstractAudioPlayer): _volume = 1.0 def __init__(self, source_group, player): super(PulseAudioPlayer, self).__init__(source_group, player) self._events = [] self._timestamps = [] # List of (ref_time, timestamp) self._write_index = 0 # Current write index (tracked manually) self._read_index_valid = False # True only if buffer has non-stale data self._clear_write = False self._buffered_audio_data = None self._underflow_is_eos = False self._playing = False audio_format = source_group.audio_format assert audio_format # Create sample_spec sample_spec = pa.pa_sample_spec() if audio_format.sample_size == 8: sample_spec.format = pa.PA_SAMPLE_U8 elif audio_format.sample_size == 16: if sys.byteorder == 'little': sample_spec.format = pa.PA_SAMPLE_S16LE else: sample_spec.format = pa.PA_SAMPLE_S16BE else: raise MediaException('Unsupported sample size') sample_spec.rate = audio_format.sample_rate sample_spec.channels = audio_format.channels channel_map = None self.sample_rate = audio_format.sample_rate try: context.lock() # Create stream self.stream = pa.pa_stream_new(context._context, str(id(self)), sample_spec, channel_map) check_not_null(self.stream) # Callback trampoline for success operations self._success_cb_func = pa.pa_stream_success_cb_t(self._success_cb) self._context_success_cb_func = \ pa.pa_context_success_cb_t(self._context_success_cb) # Callback for underflow (to detect EOS when expected pa_timestamp # does not get reached). self._underflow_cb_func = \ pa.pa_stream_notify_cb_t(self._underflow_cb) pa.pa_stream_set_underflow_callback(self.stream, self._underflow_cb_func, None) # Callback for data write self._write_cb_func = pa.pa_stream_request_cb_t(self._write_cb) pa.pa_stream_set_write_callback(self.stream, self._write_cb_func, None) # Connect to sink device = None buffer_attr = None flags = (pa.PA_STREAM_START_CORKED | pa.PA_STREAM_INTERPOLATE_TIMING | pa.PA_STREAM_VARIABLE_RATE) sync_stream = None # TODO use this check( pa.pa_stream_connect_playback(self.stream, device, buffer_attr, flags, None, sync_stream) ) # Wait for stream readiness self._state_cb_func = pa.pa_stream_notify_cb_t(self._state_cb) pa.pa_stream_set_state_callback(self.stream, self._state_cb_func, None) while pa.pa_stream_get_state(self.stream) == pa.PA_STREAM_CREATING: context.wait() if pa.pa_stream_get_state(self.stream) != pa.PA_STREAM_READY: check(-1) finally: context.unlock() self.set_volume(self._volume) if _debug: print 'stream ready' def _state_cb(self, stream, data): context.signal() def _success_cb(self, stream, success, data): context.signal() def _context_success_cb(self, ctxt, success, data): context.signal() def _write_cb(self, stream, bytes, data): if _debug: print 'write callback: %d bytes' % bytes # Asynchronously update time if self._events: context.async_operation( pa.pa_stream_update_timing_info(self.stream, self._success_cb_func, None) ) # Grab next audio packet, or leftovers from last callback. if self._buffered_audio_data: audio_data = self._buffered_audio_data self._buffered_audio_data = None else: audio_data = self.source_group.get_audio_data(bytes) seek_flag = pa.PA_SEEK_RELATIVE if self._clear_write: if _debug: print 'seek PA_SEEK_RELATIVE_ON_READ' seek_flag = pa.PA_SEEK_RELATIVE_ON_READ self._clear_write = False # Keep writing packets until `bytes` is depleted while audio_data and bytes > 0: if _debug: print 'packet', audio_data.timestamp if _debug and audio_data.events: print 'events', audio_data.events for event in audio_data.events: event_index = self._write_index + event.timestamp * \ self.source_group.audio_format.bytes_per_second self._events.append((event_index, event)) consumption = min(bytes, audio_data.length) check( pa.pa_stream_write(self.stream, audio_data.data, consumption, pa.pa_free_cb_t(0), # Data is copied 0, seek_flag) ) seek_flag = pa.PA_SEEK_RELATIVE self._read_index_valid = True self._timestamps.append((self._write_index, audio_data.timestamp)) self._write_index += consumption self._underflow_is_eos = False if _debug: print 'write', consumption if consumption < audio_data.length: audio_data.consume(consumption, self.source_group.audio_format) self._buffered_audio_data = audio_data break bytes -= consumption if bytes > 0: audio_data = self.source_group.get_audio_data(bytes) #XXX name change if not audio_data: # Whole source group has been written. Any underflow encountered # after now is the EOS. self._underflow_is_eos = True # In case the source group wasn't long enough to prebuffer stream # to PA's satisfaction, trigger immediate playback (has no effect # if stream is already playing). if self._playing: context.async_operation( pa.pa_stream_trigger(self.stream, pa.pa_stream_success_cb_t(0), None) ) self._process_events() def _underflow_cb(self, stream, data): self._process_events() if self._underflow_is_eos: self._sync_dispatch_player_event('on_eos') self._sync_dispatch_player_event('on_source_group_eos') self._underflow_is_eos = False if _debug: print 'eos' else: if _debug: print 'underflow' # TODO: does PA automatically restart stream when buffered again? # XXX: sometimes receive an underflow after EOS... need to filter? def _process_events(self): if not self._events: return timing_info = pa.pa_stream_get_timing_info(self.stream) if not timing_info: if _debug: print 'abort _process_events' return read_index = timing_info.contents.read_index while self._events and self._events[0][0] < read_index: _, event = self._events.pop(0) if _debug: print 'dispatch event', event event._sync_dispatch_to_player(self.player) def _sync_dispatch_player_event(self, event, *args): pyglet.app.platform_event_loop.post_event(self.player, event, *args) def __del__(self): try: self.delete() except: pass def delete(self): if _debug: print 'delete' if not self.stream: return context.lock() pa.pa_stream_disconnect(self.stream) context.unlock() pa.pa_stream_unref(self.stream) self.stream = None def clear(self): if _debug: print 'clear' self._clear_write = True self._write_index = self._get_read_index() self._timestamps = [] self._events = [] context.lock() self._read_index_valid = False context.sync_operation( pa.pa_stream_prebuf(self.stream, self._success_cb_func, None) ) context.unlock() def play(self): if _debug: print 'play' context.lock() context.async_operation( pa.pa_stream_cork(self.stream, 0, pa.pa_stream_success_cb_t(0), None) ) # If whole stream has already been written, trigger immediate # playback. if self._underflow_is_eos: context.async_operation( pa.pa_stream_trigger(self.stream, pa.pa_stream_success_cb_t(0), None) ) context.unlock() self._playing = True def stop(self): if _debug: print 'stop' context.lock() context.async_operation( pa.pa_stream_cork(self.stream, 1, pa.pa_stream_success_cb_t(0), None) ) context.unlock() self._playing = False def _get_read_index(self): #time = pa.pa_usec_t() context.lock() context.sync_operation( pa.pa_stream_update_timing_info(self.stream, self._success_cb_func, None) ) context.unlock() timing_info = pa.pa_stream_get_timing_info(self.stream) if timing_info: read_index = timing_info.contents.read_index else: read_index = 0 if _debug: print '_get_read_index ->', read_index return read_index def _get_write_index(self): timing_info = pa.pa_stream_get_timing_info(self.stream) if timing_info: write_index = timing_info.contents.write_index else: write_index = 0 if _debug: print '_get_write_index ->', write_index return write_index def get_time(self): if not self._read_index_valid: if _debug: print 'get_time <_read_index_valid = False> -> None' return read_index = self._get_read_index() write_index = 0 timestamp = 0.0 try: write_index, timestamp = self._timestamps[0] write_index, timestamp = self._timestamps[1] while read_index >= write_index: del self._timestamps[0] write_index, timestamp = self._timestamps[1] except IndexError: pass bytes_per_second = self.source_group.audio_format.bytes_per_second time = timestamp + (read_index - write_index) / float(bytes_per_second) if _debug: print 'get_time ->', time return time def set_volume(self, volume): self._volume = volume if not self.stream: return volume *= context._listener._volume cvolume = pa.pa_cvolume() volume = pa.pa_sw_volume_from_linear(volume) pa.pa_cvolume_set(cvolume, self.source_group.audio_format.channels, volume) context.lock() idx = pa.pa_stream_get_index(self.stream) context.sync_operation( pa.pa_context_set_sink_input_volume(context._context, idx, cvolume, self._context_success_cb_func, None) ) context.unlock() def set_pitch(self, pitch): pa.pa_stream_update_sample_rate(self.stream, int(pitch*self.sample_rate), self._success_cb_func, None) def create_audio_driver(): global context context = PulseAudioDriver() context.connect() if _debug: context.dump_debug_info() return context
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import sys import lib_pulseaudio as pa from pyglet.media import AbstractAudioDriver, AbstractAudioPlayer, \ AbstractListener, MediaException, MediaEvent import pyglet _debug = pyglet.options['debug_media'] def check(result): if result < 0: error = pa.pa_context_errno(context._context) raise MediaException(pa.pa_strerror(error)) return result def check_not_null(value): if not value: error = pa.pa_context_errno(context._context) raise MediaException(pa.pa_strerror(error)) return value class PulseAudioDriver(AbstractAudioDriver): _context = None def __init__(self): self.threaded_mainloop = pa.pa_threaded_mainloop_new() self.mainloop = pa.pa_threaded_mainloop_get_api( self.threaded_mainloop) self._players = pyglet.app.WeakSet() self._listener = PulseAudioListener(self) def create_audio_player(self, source_group, player): player = PulseAudioPlayer(source_group, player) self._players.add(player) return player def connect(self, server=None): '''Connect to pulseaudio server. :Parameters: `server` : str Server to connect to, or ``None`` for the default local server (which may be spawned as a daemon if no server is found). ''' # TODO disconnect from old assert not self._context, 'Already connected' # Create context app_name = self.get_app_name() self._context = pa.pa_context_new(self.mainloop, app_name) # Context state callback self._state_cb_func = pa.pa_context_notify_cb_t(self._state_cb) pa.pa_context_set_state_callback(self._context, self._state_cb_func, None) # Connect check( pa.pa_context_connect(self._context, server, 0, None) ) self.lock() check( pa.pa_threaded_mainloop_start(self.threaded_mainloop) ) try: # Wait for context ready. self.wait() if pa.pa_context_get_state(self._context) != pa.PA_CONTEXT_READY: check(-1) finally: self.unlock() def _state_cb(self, context, userdata): if _debug: print 'context state cb' state = pa.pa_context_get_state(self._context) if state in (pa.PA_CONTEXT_READY, pa.PA_CONTEXT_TERMINATED, pa.PA_CONTEXT_FAILED): self.signal() def lock(self): '''Lock the threaded mainloop against events. Required for all calls into PA.''' pa.pa_threaded_mainloop_lock(self.threaded_mainloop) def unlock(self): '''Unlock the mainloop thread.''' pa.pa_threaded_mainloop_unlock(self.threaded_mainloop) def signal(self): '''Signal the mainloop thread to break from a wait.''' pa.pa_threaded_mainloop_signal(self.threaded_mainloop, 0) def wait(self): '''Wait for a signal.''' pa.pa_threaded_mainloop_wait(self.threaded_mainloop) def sync_operation(self, op): '''Wait for an operation to be done or cancelled, then release it. Uses a busy-loop -- make sure a callback is registered to signal this listener.''' while pa.pa_operation_get_state(op) == pa.PA_OPERATION_RUNNING: pa.pa_threaded_mainloop_wait(self.threaded_mainloop) pa.pa_operation_unref(op) def async_operation(self, op): '''Release the operation immediately without waiting for it to complete.''' pa.pa_operation_unref(op) def get_app_name(self): '''Get the application name as advertised to the pulseaudio server.''' # TODO move app name into pyglet.app (also useful for OS X menu bar?). return sys.argv[0] def dump_debug_info(self): print 'Client version: ', pa.pa_get_library_version() print 'Server: ', pa.pa_context_get_server(self._context) print 'Protocol: ', pa.pa_context_get_protocol_version( self._context) print 'Server protocol:', pa.pa_context_get_server_protocol_version( self._context) print 'Local context: ', ( pa.pa_context_is_local(self._context) and 'Yes' or 'No') def delete(self): '''Completely shut down pulseaudio client.''' self.lock() pa.pa_context_unref(self._context) self.unlock() pa.pa_threaded_mainloop_stop(self.threaded_mainloop) pa.pa_threaded_mainloop_free(self.threaded_mainloop) self.threaded_mainloop = None self.mainloop = None def get_listener(self): return self._listener class PulseAudioListener(AbstractListener): def __init__(self, driver): self.driver = driver def _set_volume(self, volume): self._volume = volume for player in self.driver._players: player.set_volume(player._volume) def _set_position(self, position): self._position = position def _set_forward_orientation(self, orientation): self._forward_orientation = orientation def _set_up_orientation(self, orientation): self._up_orientation = orientation class PulseAudioPlayer(AbstractAudioPlayer): _volume = 1.0 def __init__(self, source_group, player): super(PulseAudioPlayer, self).__init__(source_group, player) self._events = [] self._timestamps = [] # List of (ref_time, timestamp) self._write_index = 0 # Current write index (tracked manually) self._read_index_valid = False # True only if buffer has non-stale data self._clear_write = False self._buffered_audio_data = None self._underflow_is_eos = False self._playing = False audio_format = source_group.audio_format assert audio_format # Create sample_spec sample_spec = pa.pa_sample_spec() if audio_format.sample_size == 8: sample_spec.format = pa.PA_SAMPLE_U8 elif audio_format.sample_size == 16: if sys.byteorder == 'little': sample_spec.format = pa.PA_SAMPLE_S16LE else: sample_spec.format = pa.PA_SAMPLE_S16BE else: raise MediaException('Unsupported sample size') sample_spec.rate = audio_format.sample_rate sample_spec.channels = audio_format.channels channel_map = None self.sample_rate = audio_format.sample_rate try: context.lock() # Create stream self.stream = pa.pa_stream_new(context._context, str(id(self)), sample_spec, channel_map) check_not_null(self.stream) # Callback trampoline for success operations self._success_cb_func = pa.pa_stream_success_cb_t(self._success_cb) self._context_success_cb_func = \ pa.pa_context_success_cb_t(self._context_success_cb) # Callback for underflow (to detect EOS when expected pa_timestamp # does not get reached). self._underflow_cb_func = \ pa.pa_stream_notify_cb_t(self._underflow_cb) pa.pa_stream_set_underflow_callback(self.stream, self._underflow_cb_func, None) # Callback for data write self._write_cb_func = pa.pa_stream_request_cb_t(self._write_cb) pa.pa_stream_set_write_callback(self.stream, self._write_cb_func, None) # Connect to sink device = None buffer_attr = None flags = (pa.PA_STREAM_START_CORKED | pa.PA_STREAM_INTERPOLATE_TIMING | pa.PA_STREAM_VARIABLE_RATE) sync_stream = None # TODO use this check( pa.pa_stream_connect_playback(self.stream, device, buffer_attr, flags, None, sync_stream) ) # Wait for stream readiness self._state_cb_func = pa.pa_stream_notify_cb_t(self._state_cb) pa.pa_stream_set_state_callback(self.stream, self._state_cb_func, None) while pa.pa_stream_get_state(self.stream) == pa.PA_STREAM_CREATING: context.wait() if pa.pa_stream_get_state(self.stream) != pa.PA_STREAM_READY: check(-1) finally: context.unlock() self.set_volume(self._volume) if _debug: print 'stream ready' def _state_cb(self, stream, data): context.signal() def _success_cb(self, stream, success, data): context.signal() def _context_success_cb(self, ctxt, success, data): context.signal() def _write_cb(self, stream, bytes, data): if _debug: print 'write callback: %d bytes' % bytes # Asynchronously update time if self._events: context.async_operation( pa.pa_stream_update_timing_info(self.stream, self._success_cb_func, None) ) # Grab next audio packet, or leftovers from last callback. if self._buffered_audio_data: audio_data = self._buffered_audio_data self._buffered_audio_data = None else: audio_data = self.source_group.get_audio_data(bytes) seek_flag = pa.PA_SEEK_RELATIVE if self._clear_write: if _debug: print 'seek PA_SEEK_RELATIVE_ON_READ' seek_flag = pa.PA_SEEK_RELATIVE_ON_READ self._clear_write = False # Keep writing packets until `bytes` is depleted while audio_data and bytes > 0: if _debug: print 'packet', audio_data.timestamp if _debug and audio_data.events: print 'events', audio_data.events for event in audio_data.events: event_index = self._write_index + event.timestamp * \ self.source_group.audio_format.bytes_per_second self._events.append((event_index, event)) consumption = min(bytes, audio_data.length) check( pa.pa_stream_write(self.stream, audio_data.data, consumption, pa.pa_free_cb_t(0), # Data is copied 0, seek_flag) ) seek_flag = pa.PA_SEEK_RELATIVE self._read_index_valid = True self._timestamps.append((self._write_index, audio_data.timestamp)) self._write_index += consumption self._underflow_is_eos = False if _debug: print 'write', consumption if consumption < audio_data.length: audio_data.consume(consumption, self.source_group.audio_format) self._buffered_audio_data = audio_data break bytes -= consumption if bytes > 0: audio_data = self.source_group.get_audio_data(bytes) #XXX name change if not audio_data: # Whole source group has been written. Any underflow encountered # after now is the EOS. self._underflow_is_eos = True # In case the source group wasn't long enough to prebuffer stream # to PA's satisfaction, trigger immediate playback (has no effect # if stream is already playing). if self._playing: context.async_operation( pa.pa_stream_trigger(self.stream, pa.pa_stream_success_cb_t(0), None) ) self._process_events() def _underflow_cb(self, stream, data): self._process_events() if self._underflow_is_eos: self._sync_dispatch_player_event('on_eos') self._sync_dispatch_player_event('on_source_group_eos') self._underflow_is_eos = False if _debug: print 'eos' else: if _debug: print 'underflow' # TODO: does PA automatically restart stream when buffered again? # XXX: sometimes receive an underflow after EOS... need to filter? def _process_events(self): if not self._events: return timing_info = pa.pa_stream_get_timing_info(self.stream) if not timing_info: if _debug: print 'abort _process_events' return read_index = timing_info.contents.read_index while self._events and self._events[0][0] < read_index: _, event = self._events.pop(0) if _debug: print 'dispatch event', event event._sync_dispatch_to_player(self.player) def _sync_dispatch_player_event(self, event, *args): pyglet.app.platform_event_loop.post_event(self.player, event, *args) def __del__(self): try: self.delete() except: pass def delete(self): if _debug: print 'delete' if not self.stream: return context.lock() pa.pa_stream_disconnect(self.stream) context.unlock() pa.pa_stream_unref(self.stream) self.stream = None def clear(self): if _debug: print 'clear' self._clear_write = True self._write_index = self._get_read_index() self._timestamps = [] self._events = [] context.lock() self._read_index_valid = False context.sync_operation( pa.pa_stream_prebuf(self.stream, self._success_cb_func, None) ) context.unlock() def play(self): if _debug: print 'play' context.lock() context.async_operation( pa.pa_stream_cork(self.stream, 0, pa.pa_stream_success_cb_t(0), None) ) # If whole stream has already been written, trigger immediate # playback. if self._underflow_is_eos: context.async_operation( pa.pa_stream_trigger(self.stream, pa.pa_stream_success_cb_t(0), None) ) context.unlock() self._playing = True def stop(self): if _debug: print 'stop' context.lock() context.async_operation( pa.pa_stream_cork(self.stream, 1, pa.pa_stream_success_cb_t(0), None) ) context.unlock() self._playing = False def _get_read_index(self): #time = pa.pa_usec_t() context.lock() context.sync_operation( pa.pa_stream_update_timing_info(self.stream, self._success_cb_func, None) ) context.unlock() timing_info = pa.pa_stream_get_timing_info(self.stream) if timing_info: read_index = timing_info.contents.read_index else: read_index = 0 if _debug: print '_get_read_index ->', read_index return read_index def _get_write_index(self): timing_info = pa.pa_stream_get_timing_info(self.stream) if timing_info: write_index = timing_info.contents.write_index else: write_index = 0 if _debug: print '_get_write_index ->', write_index return write_index def get_time(self): if not self._read_index_valid: if _debug: print 'get_time <_read_index_valid = False> -> None' return read_index = self._get_read_index() write_index = 0 timestamp = 0.0 try: write_index, timestamp = self._timestamps[0] write_index, timestamp = self._timestamps[1] while read_index >= write_index: del self._timestamps[0] write_index, timestamp = self._timestamps[1] except IndexError: pass bytes_per_second = self.source_group.audio_format.bytes_per_second time = timestamp + (read_index - write_index) / float(bytes_per_second) if _debug: print 'get_time ->', time return time def set_volume(self, volume): self._volume = volume if not self.stream: return volume *= context._listener._volume cvolume = pa.pa_cvolume() volume = pa.pa_sw_volume_from_linear(volume) pa.pa_cvolume_set(cvolume, self.source_group.audio_format.channels, volume) context.lock() idx = pa.pa_stream_get_index(self.stream) context.sync_operation( pa.pa_context_set_sink_input_volume(context._context, idx, cvolume, self._context_success_cb_func, None) ) context.unlock() def set_pitch(self, pitch): pa.pa_stream_update_sample_rate(self.stream, int(pitch*self.sample_rate), self._success_cb_func, None) def create_audio_driver(): global context context = PulseAudioDriver() context.connect() if _debug: context.dump_debug_info() return context
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Wrapper for openal Generated with: ../tools/wraptypes/wrap.py /usr/include/AL/al.h -lopenal -olib_openal.py .. Hacked to remove non-existent library functions. TODO add alGetError check. .. alListener3i and alListeneriv are present in my OS X 10.4 but not another 10.4 user's installation. They've also been removed for compatibility. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * import sys import pyglet.lib _lib = pyglet.lib.load_library('openal', win32='openal32', framework='/System/Library/Frameworks/OpenAL.framework') _int_types = (c_int16, c_int32) if hasattr(ctypes, 'c_int64'): # Some builds of ctypes apparently do not have c_int64 # defined; it's a pretty good bet that these builds do not # have 64-bit pointers. _int_types += (ctypes.c_int64,) for t in _int_types: if sizeof(t) == sizeof(c_size_t): c_ptrdiff_t = t class c_void(Structure): # c_void_p is a buggy return type, converting to int, so # POINTER(None) == c_void_p is actually written as # POINTER(c_void), so it can be treated as a real pointer. _fields_ = [('dummy', c_int)] AL_API = 0 # /usr/include/AL/al.h:39 ALAPI = 0 # /usr/include/AL/al.h:59 AL_INVALID = -1 # /usr/include/AL/al.h:61 AL_ILLEGAL_ENUM = 0 # /usr/include/AL/al.h:62 AL_ILLEGAL_COMMAND = 0 # /usr/include/AL/al.h:63 ALboolean = c_int # Better return type than c_char, as generated ALchar = c_char # /usr/include/AL/al.h:73 ALbyte = c_char # /usr/include/AL/al.h:76 ALubyte = c_ubyte # /usr/include/AL/al.h:79 ALshort = c_short # /usr/include/AL/al.h:82 ALushort = c_ushort # /usr/include/AL/al.h:85 ALint = c_int # /usr/include/AL/al.h:88 ALuint = c_uint # /usr/include/AL/al.h:91 ALsizei = c_int # /usr/include/AL/al.h:94 ALenum = c_int # /usr/include/AL/al.h:97 ALfloat = c_float # /usr/include/AL/al.h:100 ALdouble = c_double # /usr/include/AL/al.h:103 ALvoid = None # /usr/include/AL/al.h:106 AL_NONE = 0 # /usr/include/AL/al.h:112 AL_FALSE = 0 # /usr/include/AL/al.h:115 AL_TRUE = 1 # /usr/include/AL/al.h:118 AL_SOURCE_RELATIVE = 514 # /usr/include/AL/al.h:121 AL_CONE_INNER_ANGLE = 4097 # /usr/include/AL/al.h:130 AL_CONE_OUTER_ANGLE = 4098 # /usr/include/AL/al.h:137 AL_PITCH = 4099 # /usr/include/AL/al.h:145 AL_POSITION = 4100 # /usr/include/AL/al.h:157 AL_DIRECTION = 4101 # /usr/include/AL/al.h:160 AL_VELOCITY = 4102 # /usr/include/AL/al.h:163 AL_LOOPING = 4103 # /usr/include/AL/al.h:171 AL_BUFFER = 4105 # /usr/include/AL/al.h:178 AL_GAIN = 4106 # /usr/include/AL/al.h:191 AL_MIN_GAIN = 4109 # /usr/include/AL/al.h:200 AL_MAX_GAIN = 4110 # /usr/include/AL/al.h:209 AL_ORIENTATION = 4111 # /usr/include/AL/al.h:216 AL_SOURCE_STATE = 4112 # /usr/include/AL/al.h:221 AL_INITIAL = 4113 # /usr/include/AL/al.h:222 AL_PLAYING = 4114 # /usr/include/AL/al.h:223 AL_PAUSED = 4115 # /usr/include/AL/al.h:224 AL_STOPPED = 4116 # /usr/include/AL/al.h:225 AL_BUFFERS_QUEUED = 4117 # /usr/include/AL/al.h:230 AL_BUFFERS_PROCESSED = 4118 # /usr/include/AL/al.h:231 AL_SEC_OFFSET = 4132 # /usr/include/AL/al.h:236 AL_SAMPLE_OFFSET = 4133 # /usr/include/AL/al.h:237 AL_BYTE_OFFSET = 4134 # /usr/include/AL/al.h:238 AL_SOURCE_TYPE = 4135 # /usr/include/AL/al.h:246 AL_STATIC = 4136 # /usr/include/AL/al.h:247 AL_STREAMING = 4137 # /usr/include/AL/al.h:248 AL_UNDETERMINED = 4144 # /usr/include/AL/al.h:249 AL_FORMAT_MONO8 = 4352 # /usr/include/AL/al.h:252 AL_FORMAT_MONO16 = 4353 # /usr/include/AL/al.h:253 AL_FORMAT_STEREO8 = 4354 # /usr/include/AL/al.h:254 AL_FORMAT_STEREO16 = 4355 # /usr/include/AL/al.h:255 AL_REFERENCE_DISTANCE = 4128 # /usr/include/AL/al.h:265 AL_ROLLOFF_FACTOR = 4129 # /usr/include/AL/al.h:273 AL_CONE_OUTER_GAIN = 4130 # /usr/include/AL/al.h:282 AL_MAX_DISTANCE = 4131 # /usr/include/AL/al.h:292 AL_FREQUENCY = 8193 # /usr/include/AL/al.h:300 AL_BITS = 8194 # /usr/include/AL/al.h:301 AL_CHANNELS = 8195 # /usr/include/AL/al.h:302 AL_SIZE = 8196 # /usr/include/AL/al.h:303 AL_UNUSED = 8208 # /usr/include/AL/al.h:310 AL_PENDING = 8209 # /usr/include/AL/al.h:311 AL_PROCESSED = 8210 # /usr/include/AL/al.h:312 AL_NO_ERROR = 0 # /usr/include/AL/al.h:316 AL_INVALID_NAME = 40961 # /usr/include/AL/al.h:321 AL_INVALID_ENUM = 40962 # /usr/include/AL/al.h:326 AL_INVALID_VALUE = 40963 # /usr/include/AL/al.h:331 AL_INVALID_OPERATION = 40964 # /usr/include/AL/al.h:336 AL_OUT_OF_MEMORY = 40965 # /usr/include/AL/al.h:342 AL_VENDOR = 45057 # /usr/include/AL/al.h:346 AL_VERSION = 45058 # /usr/include/AL/al.h:347 AL_RENDERER = 45059 # /usr/include/AL/al.h:348 AL_EXTENSIONS = 45060 # /usr/include/AL/al.h:349 AL_DOPPLER_FACTOR = 49152 # /usr/include/AL/al.h:356 AL_DOPPLER_VELOCITY = 49153 # /usr/include/AL/al.h:361 AL_SPEED_OF_SOUND = 49155 # /usr/include/AL/al.h:366 AL_DISTANCE_MODEL = 53248 # /usr/include/AL/al.h:375 AL_INVERSE_DISTANCE = 53249 # /usr/include/AL/al.h:376 AL_INVERSE_DISTANCE_CLAMPED = 53250 # /usr/include/AL/al.h:377 AL_LINEAR_DISTANCE = 53251 # /usr/include/AL/al.h:378 AL_LINEAR_DISTANCE_CLAMPED = 53252 # /usr/include/AL/al.h:379 AL_EXPONENT_DISTANCE = 53253 # /usr/include/AL/al.h:380 AL_EXPONENT_DISTANCE_CLAMPED = 53254 # /usr/include/AL/al.h:381 # /usr/include/AL/al.h:386 alEnable = _lib.alEnable alEnable.restype = None alEnable.argtypes = [ALenum] # /usr/include/AL/al.h:388 alDisable = _lib.alDisable alDisable.restype = None alDisable.argtypes = [ALenum] # /usr/include/AL/al.h:390 alIsEnabled = _lib.alIsEnabled alIsEnabled.restype = ALboolean alIsEnabled.argtypes = [ALenum] # /usr/include/AL/al.h:396 alGetString = _lib.alGetString alGetString.restype = POINTER(ALchar) alGetString.argtypes = [ALenum] # /usr/include/AL/al.h:398 alGetBooleanv = _lib.alGetBooleanv alGetBooleanv.restype = None alGetBooleanv.argtypes = [ALenum, POINTER(ALboolean)] # /usr/include/AL/al.h:400 alGetIntegerv = _lib.alGetIntegerv alGetIntegerv.restype = None alGetIntegerv.argtypes = [ALenum, POINTER(ALint)] # /usr/include/AL/al.h:402 alGetFloatv = _lib.alGetFloatv alGetFloatv.restype = None alGetFloatv.argtypes = [ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:404 alGetDoublev = _lib.alGetDoublev alGetDoublev.restype = None alGetDoublev.argtypes = [ALenum, POINTER(ALdouble)] # /usr/include/AL/al.h:406 alGetBoolean = _lib.alGetBoolean alGetBoolean.restype = ALboolean alGetBoolean.argtypes = [ALenum] # /usr/include/AL/al.h:408 alGetInteger = _lib.alGetInteger alGetInteger.restype = ALint alGetInteger.argtypes = [ALenum] # /usr/include/AL/al.h:410 alGetFloat = _lib.alGetFloat alGetFloat.restype = ALfloat alGetFloat.argtypes = [ALenum] # /usr/include/AL/al.h:412 alGetDouble = _lib.alGetDouble alGetDouble.restype = ALdouble alGetDouble.argtypes = [ALenum] # /usr/include/AL/al.h:419 alGetError = _lib.alGetError alGetError.restype = ALenum alGetError.argtypes = [] # /usr/include/AL/al.h:427 alIsExtensionPresent = _lib.alIsExtensionPresent alIsExtensionPresent.restype = ALboolean alIsExtensionPresent.argtypes = [POINTER(ALchar)] # /usr/include/AL/al.h:429 alGetProcAddress = _lib.alGetProcAddress alGetProcAddress.restype = POINTER(c_void) alGetProcAddress.argtypes = [POINTER(ALchar)] # /usr/include/AL/al.h:431 alGetEnumValue = _lib.alGetEnumValue alGetEnumValue.restype = ALenum alGetEnumValue.argtypes = [POINTER(ALchar)] # /usr/include/AL/al.h:450 alListenerf = _lib.alListenerf alListenerf.restype = None alListenerf.argtypes = [ALenum, ALfloat] # /usr/include/AL/al.h:452 alListener3f = _lib.alListener3f alListener3f.restype = None alListener3f.argtypes = [ALenum, ALfloat, ALfloat, ALfloat] # /usr/include/AL/al.h:454 alListenerfv = _lib.alListenerfv alListenerfv.restype = None alListenerfv.argtypes = [ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:456 alListeneri = _lib.alListeneri alListeneri.restype = None alListeneri.argtypes = [ALenum, ALint] # /usr/include/AL/al.h:458 #alListener3i = _lib.alListener3i #alListener3i.restype = None #alListener3i.argtypes = [ALenum, ALint, ALint, ALint] # /usr/include/AL/al.h:460 #alListeneriv = _lib.alListeneriv #alListeneriv.restype = None #alListeneriv.argtypes = [ALenum, POINTER(ALint)] # /usr/include/AL/al.h:465 alGetListenerf = _lib.alGetListenerf alGetListenerf.restype = None alGetListenerf.argtypes = [ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:467 alGetListener3f = _lib.alGetListener3f alGetListener3f.restype = None alGetListener3f.argtypes = [ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)] # /usr/include/AL/al.h:469 alGetListenerfv = _lib.alGetListenerfv alGetListenerfv.restype = None alGetListenerfv.argtypes = [ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:471 alGetListeneri = _lib.alGetListeneri alGetListeneri.restype = None alGetListeneri.argtypes = [ALenum, POINTER(ALint)] # /usr/include/AL/al.h:473 alGetListener3i = _lib.alGetListener3i alGetListener3i.restype = None alGetListener3i.argtypes = [ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)] # /usr/include/AL/al.h:475 alGetListeneriv = _lib.alGetListeneriv alGetListeneriv.restype = None alGetListeneriv.argtypes = [ALenum, POINTER(ALint)] # /usr/include/AL/al.h:512 alGenSources = _lib.alGenSources alGenSources.restype = None alGenSources.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:515 alDeleteSources = _lib.alDeleteSources alDeleteSources.restype = None alDeleteSources.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:518 alIsSource = _lib.alIsSource alIsSource.restype = ALboolean alIsSource.argtypes = [ALuint] # /usr/include/AL/al.h:523 alSourcef = _lib.alSourcef alSourcef.restype = None alSourcef.argtypes = [ALuint, ALenum, ALfloat] # /usr/include/AL/al.h:525 alSource3f = _lib.alSource3f alSource3f.restype = None alSource3f.argtypes = [ALuint, ALenum, ALfloat, ALfloat, ALfloat] # /usr/include/AL/al.h:527 alSourcefv = _lib.alSourcefv alSourcefv.restype = None alSourcefv.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:529 alSourcei = _lib.alSourcei alSourcei.restype = None alSourcei.argtypes = [ALuint, ALenum, ALint] # /usr/include/AL/al.h:531 #alSource3i = _lib.alSource3i #alSource3i.restype = None #alSource3i.argtypes = [ALuint, ALenum, ALint, ALint, ALint] # /usr/include/AL/al.h:533 #alSourceiv = _lib.alSourceiv #alSourceiv.restype = None #alSourceiv.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:538 alGetSourcef = _lib.alGetSourcef alGetSourcef.restype = None alGetSourcef.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:540 alGetSource3f = _lib.alGetSource3f alGetSource3f.restype = None alGetSource3f.argtypes = [ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)] # /usr/include/AL/al.h:542 alGetSourcefv = _lib.alGetSourcefv alGetSourcefv.restype = None alGetSourcefv.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:544 alGetSourcei = _lib.alGetSourcei alGetSourcei.restype = None alGetSourcei.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:546 #alGetSource3i = _lib.alGetSource3i #alGetSource3i.restype = None #alGetSource3i.argtypes = [ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)] # /usr/include/AL/al.h:548 alGetSourceiv = _lib.alGetSourceiv alGetSourceiv.restype = None alGetSourceiv.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:556 alSourcePlayv = _lib.alSourcePlayv alSourcePlayv.restype = None alSourcePlayv.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:559 alSourceStopv = _lib.alSourceStopv alSourceStopv.restype = None alSourceStopv.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:562 alSourceRewindv = _lib.alSourceRewindv alSourceRewindv.restype = None alSourceRewindv.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:565 alSourcePausev = _lib.alSourcePausev alSourcePausev.restype = None alSourcePausev.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:572 alSourcePlay = _lib.alSourcePlay alSourcePlay.restype = None alSourcePlay.argtypes = [ALuint] # /usr/include/AL/al.h:575 alSourceStop = _lib.alSourceStop alSourceStop.restype = None alSourceStop.argtypes = [ALuint] # /usr/include/AL/al.h:578 alSourceRewind = _lib.alSourceRewind alSourceRewind.restype = None alSourceRewind.argtypes = [ALuint] # /usr/include/AL/al.h:581 alSourcePause = _lib.alSourcePause alSourcePause.restype = None alSourcePause.argtypes = [ALuint] # /usr/include/AL/al.h:586 alSourceQueueBuffers = _lib.alSourceQueueBuffers alSourceQueueBuffers.restype = None alSourceQueueBuffers.argtypes = [ALuint, ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:588 alSourceUnqueueBuffers = _lib.alSourceUnqueueBuffers alSourceUnqueueBuffers.restype = None alSourceUnqueueBuffers.argtypes = [ALuint, ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:606 alGenBuffers = _lib.alGenBuffers alGenBuffers.restype = None alGenBuffers.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:609 alDeleteBuffers = _lib.alDeleteBuffers alDeleteBuffers.restype = None alDeleteBuffers.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:612 alIsBuffer = _lib.alIsBuffer alIsBuffer.restype = ALboolean alIsBuffer.argtypes = [ALuint] # /usr/include/AL/al.h:615 alBufferData = _lib.alBufferData alBufferData.restype = None alBufferData.argtypes = [ALuint, ALenum, POINTER(ALvoid), ALsizei, ALsizei] # /usr/include/AL/al.h:620 alBufferf = _lib.alBufferf alBufferf.restype = None alBufferf.argtypes = [ALuint, ALenum, ALfloat] # /usr/include/AL/al.h:622 alBuffer3f = _lib.alBuffer3f alBuffer3f.restype = None alBuffer3f.argtypes = [ALuint, ALenum, ALfloat, ALfloat, ALfloat] # /usr/include/AL/al.h:624 alBufferfv = _lib.alBufferfv alBufferfv.restype = None alBufferfv.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:626 alBufferi = _lib.alBufferi alBufferi.restype = None alBufferi.argtypes = [ALuint, ALenum, ALint] # /usr/include/AL/al.h:628 alBuffer3i = _lib.alBuffer3i alBuffer3i.restype = None alBuffer3i.argtypes = [ALuint, ALenum, ALint, ALint, ALint] # /usr/include/AL/al.h:630 alBufferiv = _lib.alBufferiv alBufferiv.restype = None alBufferiv.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:635 alGetBufferf = _lib.alGetBufferf alGetBufferf.restype = None alGetBufferf.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:637 alGetBuffer3f = _lib.alGetBuffer3f alGetBuffer3f.restype = None alGetBuffer3f.argtypes = [ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)] # /usr/include/AL/al.h:639 alGetBufferfv = _lib.alGetBufferfv alGetBufferfv.restype = None alGetBufferfv.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:641 alGetBufferi = _lib.alGetBufferi alGetBufferi.restype = None alGetBufferi.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:643 alGetBuffer3i = _lib.alGetBuffer3i alGetBuffer3i.restype = None alGetBuffer3i.argtypes = [ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)] # /usr/include/AL/al.h:645 alGetBufferiv = _lib.alGetBufferiv alGetBufferiv.restype = None alGetBufferiv.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:651 alDopplerFactor = _lib.alDopplerFactor alDopplerFactor.restype = None alDopplerFactor.argtypes = [ALfloat] # /usr/include/AL/al.h:653 alDopplerVelocity = _lib.alDopplerVelocity alDopplerVelocity.restype = None alDopplerVelocity.argtypes = [ALfloat] # /usr/include/AL/al.h:655 alSpeedOfSound = _lib.alSpeedOfSound alSpeedOfSound.restype = None alSpeedOfSound.argtypes = [ALfloat] # /usr/include/AL/al.h:657 alDistanceModel = _lib.alDistanceModel alDistanceModel.restype = None alDistanceModel.argtypes = [ALenum] LPALENABLE = CFUNCTYPE(None, ALenum) # /usr/include/AL/al.h:662 LPALDISABLE = CFUNCTYPE(None, ALenum) # /usr/include/AL/al.h:663 LPALISENABLED = CFUNCTYPE(ALboolean, ALenum) # /usr/include/AL/al.h:664 LPALGETSTRING = CFUNCTYPE(POINTER(ALchar), ALenum) # /usr/include/AL/al.h:665 LPALGETBOOLEANV = CFUNCTYPE(None, ALenum, POINTER(ALboolean)) # /usr/include/AL/al.h:666 LPALGETINTEGERV = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:667 LPALGETFLOATV = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:668 LPALGETDOUBLEV = CFUNCTYPE(None, ALenum, POINTER(ALdouble)) # /usr/include/AL/al.h:669 LPALGETBOOLEAN = CFUNCTYPE(ALboolean, ALenum) # /usr/include/AL/al.h:670 LPALGETINTEGER = CFUNCTYPE(ALint, ALenum) # /usr/include/AL/al.h:671 LPALGETFLOAT = CFUNCTYPE(ALfloat, ALenum) # /usr/include/AL/al.h:672 LPALGETDOUBLE = CFUNCTYPE(ALdouble, ALenum) # /usr/include/AL/al.h:673 LPALGETERROR = CFUNCTYPE(ALenum) # /usr/include/AL/al.h:674 LPALISEXTENSIONPRESENT = CFUNCTYPE(ALboolean, POINTER(ALchar)) # /usr/include/AL/al.h:675 LPALGETPROCADDRESS = CFUNCTYPE(POINTER(c_void), POINTER(ALchar)) # /usr/include/AL/al.h:676 LPALGETENUMVALUE = CFUNCTYPE(ALenum, POINTER(ALchar)) # /usr/include/AL/al.h:677 LPALLISTENERF = CFUNCTYPE(None, ALenum, ALfloat) # /usr/include/AL/al.h:678 LPALLISTENER3F = CFUNCTYPE(None, ALenum, ALfloat, ALfloat, ALfloat) # /usr/include/AL/al.h:679 LPALLISTENERFV = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:680 LPALLISTENERI = CFUNCTYPE(None, ALenum, ALint) # /usr/include/AL/al.h:681 LPALLISTENER3I = CFUNCTYPE(None, ALenum, ALint, ALint, ALint) # /usr/include/AL/al.h:682 LPALLISTENERIV = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:683 LPALGETLISTENERF = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:684 LPALGETLISTENER3F = CFUNCTYPE(None, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)) # /usr/include/AL/al.h:685 LPALGETLISTENERFV = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:686 LPALGETLISTENERI = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:687 LPALGETLISTENER3I = CFUNCTYPE(None, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)) # /usr/include/AL/al.h:688 LPALGETLISTENERIV = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:689 LPALGENSOURCES = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:690 LPALDELETESOURCES = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:691 LPALISSOURCE = CFUNCTYPE(ALboolean, ALuint) # /usr/include/AL/al.h:692 LPALSOURCEF = CFUNCTYPE(None, ALuint, ALenum, ALfloat) # /usr/include/AL/al.h:693 LPALSOURCE3F = CFUNCTYPE(None, ALuint, ALenum, ALfloat, ALfloat, ALfloat) # /usr/include/AL/al.h:694 LPALSOURCEFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:695 LPALSOURCEI = CFUNCTYPE(None, ALuint, ALenum, ALint) # /usr/include/AL/al.h:696 LPALSOURCE3I = CFUNCTYPE(None, ALuint, ALenum, ALint, ALint, ALint) # /usr/include/AL/al.h:697 LPALSOURCEIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:698 LPALGETSOURCEF = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:699 LPALGETSOURCE3F = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)) # /usr/include/AL/al.h:700 LPALGETSOURCEFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:701 LPALGETSOURCEI = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:702 LPALGETSOURCE3I = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)) # /usr/include/AL/al.h:703 LPALGETSOURCEIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:704 LPALSOURCEPLAYV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:705 LPALSOURCESTOPV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:706 LPALSOURCEREWINDV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:707 LPALSOURCEPAUSEV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:708 LPALSOURCEPLAY = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:709 LPALSOURCESTOP = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:710 LPALSOURCEREWIND = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:711 LPALSOURCEPAUSE = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:712 LPALSOURCEQUEUEBUFFERS = CFUNCTYPE(None, ALuint, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:713 LPALSOURCEUNQUEUEBUFFERS = CFUNCTYPE(None, ALuint, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:714 LPALGENBUFFERS = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:715 LPALDELETEBUFFERS = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:716 LPALISBUFFER = CFUNCTYPE(ALboolean, ALuint) # /usr/include/AL/al.h:717 LPALBUFFERDATA = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALvoid), ALsizei, ALsizei) # /usr/include/AL/al.h:718 LPALBUFFERF = CFUNCTYPE(None, ALuint, ALenum, ALfloat) # /usr/include/AL/al.h:719 LPALBUFFER3F = CFUNCTYPE(None, ALuint, ALenum, ALfloat, ALfloat, ALfloat) # /usr/include/AL/al.h:720 LPALBUFFERFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:721 LPALBUFFERI = CFUNCTYPE(None, ALuint, ALenum, ALint) # /usr/include/AL/al.h:722 LPALBUFFER3I = CFUNCTYPE(None, ALuint, ALenum, ALint, ALint, ALint) # /usr/include/AL/al.h:723 LPALBUFFERIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:724 LPALGETBUFFERF = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:725 LPALGETBUFFER3F = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)) # /usr/include/AL/al.h:726 LPALGETBUFFERFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:727 LPALGETBUFFERI = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:728 LPALGETBUFFER3I = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)) # /usr/include/AL/al.h:729 LPALGETBUFFERIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:730 LPALDOPPLERFACTOR = CFUNCTYPE(None, ALfloat) # /usr/include/AL/al.h:731 LPALDOPPLERVELOCITY = CFUNCTYPE(None, ALfloat) # /usr/include/AL/al.h:732 LPALSPEEDOFSOUND = CFUNCTYPE(None, ALfloat) # /usr/include/AL/al.h:733 LPALDISTANCEMODEL = CFUNCTYPE(None, ALenum) # /usr/include/AL/al.h:734 __all__ = ['AL_API', 'ALAPI', 'AL_INVALID', 'AL_ILLEGAL_ENUM', 'AL_ILLEGAL_COMMAND', 'ALboolean', 'ALchar', 'ALbyte', 'ALubyte', 'ALshort', 'ALushort', 'ALint', 'ALuint', 'ALsizei', 'ALenum', 'ALfloat', 'ALdouble', 'ALvoid', 'AL_NONE', 'AL_FALSE', 'AL_TRUE', 'AL_SOURCE_RELATIVE', 'AL_CONE_INNER_ANGLE', 'AL_CONE_OUTER_ANGLE', 'AL_PITCH', 'AL_POSITION', 'AL_DIRECTION', 'AL_VELOCITY', 'AL_LOOPING', 'AL_BUFFER', 'AL_GAIN', 'AL_MIN_GAIN', 'AL_MAX_GAIN', 'AL_ORIENTATION', 'AL_SOURCE_STATE', 'AL_INITIAL', 'AL_PLAYING', 'AL_PAUSED', 'AL_STOPPED', 'AL_BUFFERS_QUEUED', 'AL_BUFFERS_PROCESSED', 'AL_SEC_OFFSET', 'AL_SAMPLE_OFFSET', 'AL_BYTE_OFFSET', 'AL_SOURCE_TYPE', 'AL_STATIC', 'AL_STREAMING', 'AL_UNDETERMINED', 'AL_FORMAT_MONO8', 'AL_FORMAT_MONO16', 'AL_FORMAT_STEREO8', 'AL_FORMAT_STEREO16', 'AL_REFERENCE_DISTANCE', 'AL_ROLLOFF_FACTOR', 'AL_CONE_OUTER_GAIN', 'AL_MAX_DISTANCE', 'AL_FREQUENCY', 'AL_BITS', 'AL_CHANNELS', 'AL_SIZE', 'AL_UNUSED', 'AL_PENDING', 'AL_PROCESSED', 'AL_NO_ERROR', 'AL_INVALID_NAME', 'AL_INVALID_ENUM', 'AL_INVALID_VALUE', 'AL_INVALID_OPERATION', 'AL_OUT_OF_MEMORY', 'AL_VENDOR', 'AL_VERSION', 'AL_RENDERER', 'AL_EXTENSIONS', 'AL_DOPPLER_FACTOR', 'AL_DOPPLER_VELOCITY', 'AL_SPEED_OF_SOUND', 'AL_DISTANCE_MODEL', 'AL_INVERSE_DISTANCE', 'AL_INVERSE_DISTANCE_CLAMPED', 'AL_LINEAR_DISTANCE', 'AL_LINEAR_DISTANCE_CLAMPED', 'AL_EXPONENT_DISTANCE', 'AL_EXPONENT_DISTANCE_CLAMPED', 'alEnable', 'alDisable', 'alIsEnabled', 'alGetString', 'alGetBooleanv', 'alGetIntegerv', 'alGetFloatv', 'alGetDoublev', 'alGetBoolean', 'alGetInteger', 'alGetFloat', 'alGetDouble', 'alGetError', 'alIsExtensionPresent', 'alGetProcAddress', 'alGetEnumValue', 'alListenerf', 'alListener3f', 'alListenerfv', 'alListeneri', 'alListener3i', 'alListeneriv', 'alGetListenerf', 'alGetListener3f', 'alGetListenerfv', 'alGetListeneri', 'alGetListener3i', 'alGetListeneriv', 'alGenSources', 'alDeleteSources', 'alIsSource', 'alSourcef', 'alSource3f', 'alSourcefv', 'alSourcei', 'alSource3i', 'alSourceiv', 'alGetSourcef', 'alGetSource3f', 'alGetSourcefv', 'alGetSourcei', 'alGetSource3i', 'alGetSourceiv', 'alSourcePlayv', 'alSourceStopv', 'alSourceRewindv', 'alSourcePausev', 'alSourcePlay', 'alSourceStop', 'alSourceRewind', 'alSourcePause', 'alSourceQueueBuffers', 'alSourceUnqueueBuffers', 'alGenBuffers', 'alDeleteBuffers', 'alIsBuffer', 'alBufferData', 'alBufferf', 'alBuffer3f', 'alBufferfv', 'alBufferi', 'alBuffer3i', 'alBufferiv', 'alGetBufferf', 'alGetBuffer3f', 'alGetBufferfv', 'alGetBufferi', 'alGetBuffer3i', 'alGetBufferiv', 'alDopplerFactor', 'alDopplerVelocity', 'alSpeedOfSound', 'alDistanceModel', 'LPALENABLE', 'LPALDISABLE', 'LPALISENABLED', 'LPALGETSTRING', 'LPALGETBOOLEANV', 'LPALGETINTEGERV', 'LPALGETFLOATV', 'LPALGETDOUBLEV', 'LPALGETBOOLEAN', 'LPALGETINTEGER', 'LPALGETFLOAT', 'LPALGETDOUBLE', 'LPALGETERROR', 'LPALISEXTENSIONPRESENT', 'LPALGETPROCADDRESS', 'LPALGETENUMVALUE', 'LPALLISTENERF', 'LPALLISTENER3F', 'LPALLISTENERFV', 'LPALLISTENERI', 'LPALLISTENER3I', 'LPALLISTENERIV', 'LPALGETLISTENERF', 'LPALGETLISTENER3F', 'LPALGETLISTENERFV', 'LPALGETLISTENERI', 'LPALGETLISTENER3I', 'LPALGETLISTENERIV', 'LPALGENSOURCES', 'LPALDELETESOURCES', 'LPALISSOURCE', 'LPALSOURCEF', 'LPALSOURCE3F', 'LPALSOURCEFV', 'LPALSOURCEI', 'LPALSOURCE3I', 'LPALSOURCEIV', 'LPALGETSOURCEF', 'LPALGETSOURCE3F', 'LPALGETSOURCEFV', 'LPALGETSOURCEI', 'LPALGETSOURCE3I', 'LPALGETSOURCEIV', 'LPALSOURCEPLAYV', 'LPALSOURCESTOPV', 'LPALSOURCEREWINDV', 'LPALSOURCEPAUSEV', 'LPALSOURCEPLAY', 'LPALSOURCESTOP', 'LPALSOURCEREWIND', 'LPALSOURCEPAUSE', 'LPALSOURCEQUEUEBUFFERS', 'LPALSOURCEUNQUEUEBUFFERS', 'LPALGENBUFFERS', 'LPALDELETEBUFFERS', 'LPALISBUFFER', 'LPALBUFFERDATA', 'LPALBUFFERF', 'LPALBUFFER3F', 'LPALBUFFERFV', 'LPALBUFFERI', 'LPALBUFFER3I', 'LPALBUFFERIV', 'LPALGETBUFFERF', 'LPALGETBUFFER3F', 'LPALGETBUFFERFV', 'LPALGETBUFFERI', 'LPALGETBUFFER3I', 'LPALGETBUFFERIV', 'LPALDOPPLERFACTOR', 'LPALDOPPLERVELOCITY', 'LPALSPEEDOFSOUND', 'LPALDISTANCEMODEL']
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Wrapper for openal Generated with: ../tools/wraptypes/wrap.py /usr/include/AL/alc.h -lopenal -olib_alc.py .. Hacked to fix ALCvoid argtypes. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * import sys import pyglet.lib _lib = pyglet.lib.load_library('openal', win32='openal32', framework='/System/Library/Frameworks/OpenAL.framework') _int_types = (c_int16, c_int32) if hasattr(ctypes, 'c_int64'): # Some builds of ctypes apparently do not have c_int64 # defined; it's a pretty good bet that these builds do not # have 64-bit pointers. _int_types += (ctypes.c_int64,) for t in _int_types: if sizeof(t) == sizeof(c_size_t): c_ptrdiff_t = t class c_void(Structure): # c_void_p is a buggy return type, converting to int, so # POINTER(None) == c_void_p is actually written as # POINTER(c_void), so it can be treated as a real pointer. _fields_ = [('dummy', c_int)] ALC_API = 0 # /usr/include/AL/alc.h:19 ALCAPI = 0 # /usr/include/AL/alc.h:37 ALC_INVALID = 0 # /usr/include/AL/alc.h:39 ALC_VERSION_0_1 = 1 # /usr/include/AL/alc.h:42 class struct_ALCdevice_struct(Structure): __slots__ = [ ] struct_ALCdevice_struct._fields_ = [ ('_opaque_struct', c_int) ] class struct_ALCdevice_struct(Structure): __slots__ = [ ] struct_ALCdevice_struct._fields_ = [ ('_opaque_struct', c_int) ] ALCdevice = struct_ALCdevice_struct # /usr/include/AL/alc.h:44 class struct_ALCcontext_struct(Structure): __slots__ = [ ] struct_ALCcontext_struct._fields_ = [ ('_opaque_struct', c_int) ] class struct_ALCcontext_struct(Structure): __slots__ = [ ] struct_ALCcontext_struct._fields_ = [ ('_opaque_struct', c_int) ] ALCcontext = struct_ALCcontext_struct # /usr/include/AL/alc.h:45 ALCboolean = c_char # /usr/include/AL/alc.h:49 ALCchar = c_char # /usr/include/AL/alc.h:52 ALCbyte = c_char # /usr/include/AL/alc.h:55 ALCubyte = c_ubyte # /usr/include/AL/alc.h:58 ALCshort = c_short # /usr/include/AL/alc.h:61 ALCushort = c_ushort # /usr/include/AL/alc.h:64 ALCint = c_int # /usr/include/AL/alc.h:67 ALCuint = c_uint # /usr/include/AL/alc.h:70 ALCsizei = c_int # /usr/include/AL/alc.h:73 ALCenum = c_int # /usr/include/AL/alc.h:76 ALCfloat = c_float # /usr/include/AL/alc.h:79 ALCdouble = c_double # /usr/include/AL/alc.h:82 ALCvoid = None # /usr/include/AL/alc.h:85 ALC_FALSE = 0 # /usr/include/AL/alc.h:91 ALC_TRUE = 1 # /usr/include/AL/alc.h:94 ALC_FREQUENCY = 4103 # /usr/include/AL/alc.h:99 ALC_REFRESH = 4104 # /usr/include/AL/alc.h:104 ALC_SYNC = 4105 # /usr/include/AL/alc.h:109 ALC_MONO_SOURCES = 4112 # /usr/include/AL/alc.h:114 ALC_STEREO_SOURCES = 4113 # /usr/include/AL/alc.h:119 ALC_NO_ERROR = 0 # /usr/include/AL/alc.h:128 ALC_INVALID_DEVICE = 40961 # /usr/include/AL/alc.h:133 ALC_INVALID_CONTEXT = 40962 # /usr/include/AL/alc.h:138 ALC_INVALID_ENUM = 40963 # /usr/include/AL/alc.h:143 ALC_INVALID_VALUE = 40964 # /usr/include/AL/alc.h:148 ALC_OUT_OF_MEMORY = 40965 # /usr/include/AL/alc.h:153 ALC_DEFAULT_DEVICE_SPECIFIER = 4100 # /usr/include/AL/alc.h:159 ALC_DEVICE_SPECIFIER = 4101 # /usr/include/AL/alc.h:160 ALC_EXTENSIONS = 4102 # /usr/include/AL/alc.h:161 ALC_MAJOR_VERSION = 4096 # /usr/include/AL/alc.h:163 ALC_MINOR_VERSION = 4097 # /usr/include/AL/alc.h:164 ALC_ATTRIBUTES_SIZE = 4098 # /usr/include/AL/alc.h:166 ALC_ALL_ATTRIBUTES = 4099 # /usr/include/AL/alc.h:167 ALC_CAPTURE_DEVICE_SPECIFIER = 784 # /usr/include/AL/alc.h:172 ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER = 785 # /usr/include/AL/alc.h:173 ALC_CAPTURE_SAMPLES = 786 # /usr/include/AL/alc.h:174 # /usr/include/AL/alc.h:180 alcCreateContext = _lib.alcCreateContext alcCreateContext.restype = POINTER(ALCcontext) alcCreateContext.argtypes = [POINTER(ALCdevice), POINTER(ALCint)] # /usr/include/AL/alc.h:182 alcMakeContextCurrent = _lib.alcMakeContextCurrent alcMakeContextCurrent.restype = ALCboolean alcMakeContextCurrent.argtypes = [POINTER(ALCcontext)] # /usr/include/AL/alc.h:184 alcProcessContext = _lib.alcProcessContext alcProcessContext.restype = None alcProcessContext.argtypes = [POINTER(ALCcontext)] # /usr/include/AL/alc.h:186 alcSuspendContext = _lib.alcSuspendContext alcSuspendContext.restype = None alcSuspendContext.argtypes = [POINTER(ALCcontext)] # /usr/include/AL/alc.h:188 alcDestroyContext = _lib.alcDestroyContext alcDestroyContext.restype = None alcDestroyContext.argtypes = [POINTER(ALCcontext)] # /usr/include/AL/alc.h:190 alcGetCurrentContext = _lib.alcGetCurrentContext alcGetCurrentContext.restype = POINTER(ALCcontext) alcGetCurrentContext.argtypes = [] # /usr/include/AL/alc.h:192 alcGetContextsDevice = _lib.alcGetContextsDevice alcGetContextsDevice.restype = POINTER(ALCdevice) alcGetContextsDevice.argtypes = [POINTER(ALCcontext)] # /usr/include/AL/alc.h:198 alcOpenDevice = _lib.alcOpenDevice alcOpenDevice.restype = POINTER(ALCdevice) alcOpenDevice.argtypes = [POINTER(ALCchar)] # /usr/include/AL/alc.h:200 alcCloseDevice = _lib.alcCloseDevice alcCloseDevice.restype = ALCboolean alcCloseDevice.argtypes = [POINTER(ALCdevice)] # /usr/include/AL/alc.h:207 alcGetError = _lib.alcGetError alcGetError.restype = ALCenum alcGetError.argtypes = [POINTER(ALCdevice)] # /usr/include/AL/alc.h:215 alcIsExtensionPresent = _lib.alcIsExtensionPresent alcIsExtensionPresent.restype = ALCboolean alcIsExtensionPresent.argtypes = [POINTER(ALCdevice), POINTER(ALCchar)] # /usr/include/AL/alc.h:217 alcGetProcAddress = _lib.alcGetProcAddress alcGetProcAddress.restype = POINTER(c_void) alcGetProcAddress.argtypes = [POINTER(ALCdevice), POINTER(ALCchar)] # /usr/include/AL/alc.h:219 alcGetEnumValue = _lib.alcGetEnumValue alcGetEnumValue.restype = ALCenum alcGetEnumValue.argtypes = [POINTER(ALCdevice), POINTER(ALCchar)] # /usr/include/AL/alc.h:225 alcGetString = _lib.alcGetString alcGetString.restype = POINTER(ALCchar) alcGetString.argtypes = [POINTER(ALCdevice), ALCenum] # /usr/include/AL/alc.h:227 alcGetIntegerv = _lib.alcGetIntegerv alcGetIntegerv.restype = None alcGetIntegerv.argtypes = [POINTER(ALCdevice), ALCenum, ALCsizei, POINTER(ALCint)] # /usr/include/AL/alc.h:233 alcCaptureOpenDevice = _lib.alcCaptureOpenDevice alcCaptureOpenDevice.restype = POINTER(ALCdevice) alcCaptureOpenDevice.argtypes = [POINTER(ALCchar), ALCuint, ALCenum, ALCsizei] # /usr/include/AL/alc.h:235 alcCaptureCloseDevice = _lib.alcCaptureCloseDevice alcCaptureCloseDevice.restype = ALCboolean alcCaptureCloseDevice.argtypes = [POINTER(ALCdevice)] # /usr/include/AL/alc.h:237 alcCaptureStart = _lib.alcCaptureStart alcCaptureStart.restype = None alcCaptureStart.argtypes = [POINTER(ALCdevice)] # /usr/include/AL/alc.h:239 alcCaptureStop = _lib.alcCaptureStop alcCaptureStop.restype = None alcCaptureStop.argtypes = [POINTER(ALCdevice)] # /usr/include/AL/alc.h:241 alcCaptureSamples = _lib.alcCaptureSamples alcCaptureSamples.restype = None alcCaptureSamples.argtypes = [POINTER(ALCdevice), POINTER(ALCvoid), ALCsizei] LPALCCREATECONTEXT = CFUNCTYPE(POINTER(ALCcontext), POINTER(ALCdevice), POINTER(ALCint)) # /usr/include/AL/alc.h:246 LPALCMAKECONTEXTCURRENT = CFUNCTYPE(ALCboolean, POINTER(ALCcontext)) # /usr/include/AL/alc.h:247 LPALCPROCESSCONTEXT = CFUNCTYPE(None, POINTER(ALCcontext)) # /usr/include/AL/alc.h:248 LPALCSUSPENDCONTEXT = CFUNCTYPE(None, POINTER(ALCcontext)) # /usr/include/AL/alc.h:249 LPALCDESTROYCONTEXT = CFUNCTYPE(None, POINTER(ALCcontext)) # /usr/include/AL/alc.h:250 LPALCGETCURRENTCONTEXT = CFUNCTYPE(POINTER(ALCcontext)) # /usr/include/AL/alc.h:251 LPALCGETCONTEXTSDEVICE = CFUNCTYPE(POINTER(ALCdevice), POINTER(ALCcontext)) # /usr/include/AL/alc.h:252 LPALCOPENDEVICE = CFUNCTYPE(POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:253 LPALCCLOSEDEVICE = CFUNCTYPE(ALCboolean, POINTER(ALCdevice)) # /usr/include/AL/alc.h:254 LPALCGETERROR = CFUNCTYPE(ALCenum, POINTER(ALCdevice)) # /usr/include/AL/alc.h:255 LPALCISEXTENSIONPRESENT = CFUNCTYPE(ALCboolean, POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:256 LPALCGETPROCADDRESS = CFUNCTYPE(POINTER(c_void), POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:257 LPALCGETENUMVALUE = CFUNCTYPE(ALCenum, POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:258 LPALCGETSTRING = CFUNCTYPE(POINTER(ALCchar), POINTER(ALCdevice), ALCenum) # /usr/include/AL/alc.h:259 LPALCGETINTEGERV = CFUNCTYPE(None, POINTER(ALCdevice), ALCenum, ALCsizei, POINTER(ALCint)) # /usr/include/AL/alc.h:260 LPALCCAPTUREOPENDEVICE = CFUNCTYPE(POINTER(ALCdevice), POINTER(ALCchar), ALCuint, ALCenum, ALCsizei) # /usr/include/AL/alc.h:261 LPALCCAPTURECLOSEDEVICE = CFUNCTYPE(ALCboolean, POINTER(ALCdevice)) # /usr/include/AL/alc.h:262 LPALCCAPTURESTART = CFUNCTYPE(None, POINTER(ALCdevice)) # /usr/include/AL/alc.h:263 LPALCCAPTURESTOP = CFUNCTYPE(None, POINTER(ALCdevice)) # /usr/include/AL/alc.h:264 LPALCCAPTURESAMPLES = CFUNCTYPE(None, POINTER(ALCdevice), POINTER(ALCvoid), ALCsizei) # /usr/include/AL/alc.h:265 __all__ = ['ALC_API', 'ALCAPI', 'ALC_INVALID', 'ALC_VERSION_0_1', 'ALCdevice', 'ALCcontext', 'ALCboolean', 'ALCchar', 'ALCbyte', 'ALCubyte', 'ALCshort', 'ALCushort', 'ALCint', 'ALCuint', 'ALCsizei', 'ALCenum', 'ALCfloat', 'ALCdouble', 'ALCvoid', 'ALC_FALSE', 'ALC_TRUE', 'ALC_FREQUENCY', 'ALC_REFRESH', 'ALC_SYNC', 'ALC_MONO_SOURCES', 'ALC_STEREO_SOURCES', 'ALC_NO_ERROR', 'ALC_INVALID_DEVICE', 'ALC_INVALID_CONTEXT', 'ALC_INVALID_ENUM', 'ALC_INVALID_VALUE', 'ALC_OUT_OF_MEMORY', 'ALC_DEFAULT_DEVICE_SPECIFIER', 'ALC_DEVICE_SPECIFIER', 'ALC_EXTENSIONS', 'ALC_MAJOR_VERSION', 'ALC_MINOR_VERSION', 'ALC_ATTRIBUTES_SIZE', 'ALC_ALL_ATTRIBUTES', 'ALC_CAPTURE_DEVICE_SPECIFIER', 'ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER', 'ALC_CAPTURE_SAMPLES', 'alcCreateContext', 'alcMakeContextCurrent', 'alcProcessContext', 'alcSuspendContext', 'alcDestroyContext', 'alcGetCurrentContext', 'alcGetContextsDevice', 'alcOpenDevice', 'alcCloseDevice', 'alcGetError', 'alcIsExtensionPresent', 'alcGetProcAddress', 'alcGetEnumValue', 'alcGetString', 'alcGetIntegerv', 'alcCaptureOpenDevice', 'alcCaptureCloseDevice', 'alcCaptureStart', 'alcCaptureStop', 'alcCaptureSamples', 'LPALCCREATECONTEXT', 'LPALCMAKECONTEXTCURRENT', 'LPALCPROCESSCONTEXT', 'LPALCSUSPENDCONTEXT', 'LPALCDESTROYCONTEXT', 'LPALCGETCURRENTCONTEXT', 'LPALCGETCONTEXTSDEVICE', 'LPALCOPENDEVICE', 'LPALCCLOSEDEVICE', 'LPALCGETERROR', 'LPALCISEXTENSIONPRESENT', 'LPALCGETPROCADDRESS', 'LPALCGETENUMVALUE', 'LPALCGETSTRING', 'LPALCGETINTEGERV', 'LPALCCAPTUREOPENDEVICE', 'LPALCCAPTURECLOSEDEVICE', 'LPALCCAPTURESTART', 'LPALCCAPTURESTOP', 'LPALCCAPTURESAMPLES']
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id$ import ctypes import heapq import sys import threading import time import Queue import lib_openal as al import lib_alc as alc from pyglet.media import MediaException, MediaEvent, AbstractAudioPlayer, \ AbstractAudioDriver, AbstractListener, MediaThread import pyglet _debug = pyglet.options['debug_media'] class OpenALException(MediaException): pass # TODO move functions into context/driver? def _split_nul_strings(s): # NUL-separated list of strings, double-NUL-terminated. nul = False i = 0 while True: if s[i] == '\0': if nul: break else: nul = True else: nul = False i += 1 s = s[:i - 1] return filter(None, [ss.strip() for ss in s.split('\0')]) format_map = { (1, 8): al.AL_FORMAT_MONO8, (1, 16): al.AL_FORMAT_MONO16, (2, 8): al.AL_FORMAT_STEREO8, (2, 16): al.AL_FORMAT_STEREO16, } class OpenALWorker(MediaThread): # Minimum size to bother refilling (bytes) _min_write_size = 512 # Time to wait if there are players, but they're all full. _nap_time = 0.05 # Time to wait if there are no players. _sleep_time = None def __init__(self): super(OpenALWorker, self).__init__() self.players = set() def run(self): while True: # This is a big lock, but ensures a player is not deleted while # we're processing it -- this saves on extra checks in the # player's methods that would otherwise have to check that it's # still alive. self.condition.acquire() if self.stopped: self.condition.release() break sleep_time = -1 # Refill player with least write_size if self.players: player = None write_size = 0 for p in self.players: s = p.get_write_size() if s > write_size: player = p write_size = s if write_size > self._min_write_size: player.refill(write_size) else: sleep_time = self._nap_time else: sleep_time = self._sleep_time self.condition.release() if sleep_time != -1: self.sleep(sleep_time) def add(self, player): self.condition.acquire() self.players.add(player) self.condition.notify() self.condition.release() def remove(self, player): self.condition.acquire() if player in self.players: self.players.remove(player) self.condition.notify() self.condition.release() class OpenALAudioPlayer(AbstractAudioPlayer): #: Minimum size of an OpenAL buffer worth bothering with, in bytes _min_buffer_size = 512 #: Aggregate (desired) buffer size, in bytes _ideal_buffer_size = 44800 def __init__(self, source_group, player): super(OpenALAudioPlayer, self).__init__(source_group, player) audio_format = source_group.audio_format try: self._al_format = format_map[(audio_format.channels, audio_format.sample_size)] except KeyError: raise OpenALException('Unsupported audio format.') self._al_source = al.ALuint() al.alGenSources(1, self._al_source) # Lock policy: lock all instance vars (except constants). (AL calls # are locked on context). self._lock = threading.RLock() # Cursor positions, like DSound and Pulse drivers, refer to a # hypothetical infinite-length buffer. Cursor units are in bytes. # Cursor position of current (head) AL buffer self._buffer_cursor = 0 # Estimated playback cursor position (last seen) self._play_cursor = 0 # Cursor position of end of queued AL buffer. self._write_cursor = 0 # List of currently queued buffer sizes (in bytes) self._buffer_sizes = [] # List of currently queued buffer timestamps self._buffer_timestamps = [] # Timestamp at end of last written buffer (timestamp to return in case # of underrun) self._underrun_timestamp = None # List of (cursor, MediaEvent) self._events = [] # Desired play state (True even if stopped due to underrun) self._playing = False # Has source group EOS been seen (and hence, event added to queue)? self._eos = False # OpenAL 1.0 timestamp interpolation: system time of current buffer # playback (best guess) if not context.have_1_1: self._buffer_system_time = time.time() self.refill(self._ideal_buffer_size) def __del__(self): try: self.delete() except: pass def delete(self): if _debug: print 'OpenALAudioPlayer.delete()' if not self._al_source: return context.worker.remove(self) self._lock.acquire() context.lock() al.alDeleteSources(1, self._al_source) context.unlock() self._al_source = None self._lock.release() def play(self): if self._playing: return if _debug: print 'OpenALAudioPlayer.play()' self._playing = True self._al_play() if not context.have_1_1: self._buffer_system_time = time.time() context.worker.add(self) def _al_play(self): if _debug: print 'OpenALAudioPlayer._al_play()' context.lock() state = al.ALint() al.alGetSourcei(self._al_source, al.AL_SOURCE_STATE, state) if state.value != al.AL_PLAYING: al.alSourcePlay(self._al_source) context.unlock() def stop(self): if not self._playing: return if _debug: print 'OpenALAudioPlayer.stop()' self._pause_timestamp = self.get_time() context.lock() al.alSourcePause(self._al_source) context.unlock() self._playing = False context.worker.remove(self) def clear(self): if _debug: print 'OpenALAudioPlayer.clear()' self._lock.acquire() context.lock() al.alSourceStop(self._al_source) self._playing = False del self._events[:] self._underrun_timestamp = None self._buffer_timestamps = [None for _ in self._buffer_timestamps] context.unlock() self._lock.release() def _update_play_cursor(self): if not self._al_source: return self._lock.acquire() context.lock() # Release spent buffers processed = al.ALint() al.alGetSourcei(self._al_source, al.AL_BUFFERS_PROCESSED, processed) processed = processed.value if processed: buffers = (al.ALuint * processed)() al.alSourceUnqueueBuffers(self._al_source, len(buffers), buffers) al.alDeleteBuffers(len(buffers), buffers) context.unlock() if processed: if len(self._buffer_timestamps) == processed: # Underrun, take note of timestamp self._underrun_timestamp = \ self._buffer_timestamps[-1] + \ self._buffer_sizes[-1] / \ float(self.source_group.audio_format.bytes_per_second) self._buffer_cursor += sum(self._buffer_sizes[:processed]) del self._buffer_sizes[:processed] del self._buffer_timestamps[:processed] if not context.have_1_1: self._buffer_system_time = time.time() # Update play cursor using buffer cursor + estimate into current # buffer if context.have_1_1: bytes = al.ALint() context.lock() al.alGetSourcei(self._al_source, al.AL_BYTE_OFFSET, bytes) context.unlock() if _debug: print 'got bytes offset', bytes.value self._play_cursor = self._buffer_cursor + bytes.value else: # Interpolate system time past buffer timestamp self._play_cursor = \ self._buffer_cursor + int( (time.time() - self._buffer_system_time) * \ self.source_group.audio_format.bytes_per_second) # Process events while self._events and self._events[0][0] < self._play_cursor: _, event = self._events.pop(0) event._sync_dispatch_to_player(self.player) self._lock.release() def get_write_size(self): self._lock.acquire() self._update_play_cursor() write_size = self._ideal_buffer_size - \ (self._write_cursor - self._play_cursor) if self._eos: write_size = 0 self._lock.release() return write_size def refill(self, write_size): if _debug: print 'refill', write_size self._lock.acquire() while write_size > self._min_buffer_size: audio_data = self.source_group.get_audio_data(write_size) if not audio_data: self._eos = True self._events.append( (self._write_cursor, MediaEvent(0, 'on_eos'))) self._events.append( (self._write_cursor, MediaEvent(0, 'on_source_group_eos'))) break for event in audio_data.events: cursor = self._write_cursor + event.timestamp * \ self.source_group.audio_format.bytes_per_second self._events.append((cursor, event)) buffer = al.ALuint() context.lock() al.alGenBuffers(1, buffer) al.alBufferData(buffer, self._al_format, audio_data.data, audio_data.length, self.source_group.audio_format.sample_rate) al.alSourceQueueBuffers(self._al_source, 1, ctypes.byref(buffer)) context.unlock() self._write_cursor += audio_data.length self._buffer_sizes.append(audio_data.length) self._buffer_timestamps.append(audio_data.timestamp) write_size -= audio_data.length # Check for underrun stopping playback if self._playing: state = al.ALint() context.lock() al.alGetSourcei(self._al_source, al.AL_SOURCE_STATE, state) if state.value != al.AL_PLAYING: if _debug: print 'underrun' al.alSourcePlay(self._al_source) context.unlock() self._lock.release() def get_time(self): try: buffer_timestamp = self._buffer_timestamps[0] except IndexError: return self._underrun_timestamp if buffer_timestamp is None: return None return buffer_timestamp + \ (self._play_cursor - self._buffer_cursor) / \ float(self.source_group.audio_format.bytes_per_second) def set_volume(self, volume): context.lock() al.alSourcef(self._al_source, al.AL_GAIN, max(0, volume)) context.unlock() def set_position(self, position): x, y, z = position context.lock() al.alSource3f(self._al_source, al.AL_POSITION, x, y, z) context.unlock() def set_min_distance(self, min_distance): context.lock() al.alSourcef(self._al_source, al.AL_REFERENCE_DISTANCE, min_distance) context.unlock() def set_max_distance(self, max_distance): context.lock() al.alSourcef(self._al_source, al.AL_MAX_DISTANCE, max_distance) context.unlock() def set_pitch(self, pitch): context.lock() al.alSourcef(self._al_source, al.AL_PITCH, max(0, pitch)) context.unlock() def set_cone_orientation(self, cone_orientation): x, y, z = cone_orientation context.lock() al.alSource3f(self._al_source, al.AL_DIRECTION, x, y, z) context.unlock() def set_cone_inner_angle(self, cone_inner_angle): context.lock() al.alSourcef(self._al_source, al.AL_CONE_INNER_ANGLE, cone_inner_angle) context.unlock() def set_cone_outer_angle(self, cone_outer_angle): context.lock() al.alSourcef(self._al_source, al.AL_CONE_OUTER_ANGLE, cone_outer_angle) context.unlock() def set_cone_outer_gain(self, cone_outer_gain): context.lock() al.alSourcef(self._al_source, al.AL_CONE_OUTER_GAIN, cone_outer_gain) context.unlock() class OpenALDriver(AbstractAudioDriver): _forward_orientation = (0, 0, -1) _up_orientation = (0, 1, 0) def __init__(self, device_name=None): super(OpenALDriver, self).__init__() # TODO devices must be enumerated on Windows, otherwise 1.0 context is # returned. self._device = alc.alcOpenDevice(device_name) if not self._device: raise Exception('No OpenAL device.') alcontext = alc.alcCreateContext(self._device, None) alc.alcMakeContextCurrent(alcontext) self.have_1_1 = self.have_version(1, 1) and False self._lock = threading.Lock() self._listener = OpenALListener(self) # Start worker thread self.worker = OpenALWorker() self.worker.start() def create_audio_player(self, source_group, player): return OpenALAudioPlayer(source_group, player) def delete(self): self.worker.stop() def lock(self): self._lock.acquire() def unlock(self): self._lock.release() def have_version(self, major, minor): return (major, minor) <= self.get_version() def get_version(self): major = alc.ALCint() minor = alc.ALCint() alc.alcGetIntegerv(self._device, alc.ALC_MAJOR_VERSION, ctypes.sizeof(major), major) alc.alcGetIntegerv(self._device, alc.ALC_MINOR_VERSION, ctypes.sizeof(minor), minor) return major.value, minor.value def get_extensions(self): extensions = alc.alcGetString(self._device, alc.ALC_EXTENSIONS) if sys.platform == 'darwin' or sys.platform.startswith('linux'): return ctypes.cast(extensions, ctypes.c_char_p).value.split(' ') else: return _split_nul_strings(extensions) def have_extension(self, extension): return extension in self.get_extensions() def get_listener(self): return self._listener class OpenALListener(AbstractListener): def __init__(self, driver): self._driver = driver def _set_volume(self, volume): self._driver.lock() al.alListenerf(al.AL_GAIN, volume) self._driver.unlock() self._volume = volume def _set_position(self, position): x, y, z = position self._driver.lock() al.alListener3f(al.AL_POSITION, x, y, z) self._driver.unlock() self._position = position def _set_forward_orientation(self, orientation): val = (al.ALfloat * 6)(*(orientation + self._up_orientation)) self._driver.lock() al.alListenerfv(al.AL_ORIENTATION, val) self._driver.unlock() self._forward_orientation = orientation def _set_up_orientation(self, orientation): val = (al.ALfloat * 6)(*(self._forward_orientation + orientation)) self._driver.lock() al.alListenerfv(al.AL_ORIENTATION, val) self._driver.unlock() self._up_orientation = orientation context = None def create_audio_driver(device_name=None): global context context = OpenALDriver(device_name) if _debug: print 'OpenAL', context.get_version() return context
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id$ '''Audio and video playback. pyglet can play WAV files, and if AVbin is installed, many other audio and video formats. Playback is handled by the `Player` class, which reads raw data from `Source` objects and provides methods for pausing, seeking, adjusting the volume, and so on. The `Player` class implements a the best available audio device (currently, only OpenAL is supported):: player = Player() A `Source` is used to decode arbitrary audio and video files. It is associated with a single player by "queuing" it:: source = load('background_music.mp3') player.queue(source) Use the `Player` to control playback. If the source contains video, the `Source.video_format` attribute will be non-None, and the `Player.texture` attribute will contain the current video image synchronised to the audio. Decoding sounds can be processor-intensive and may introduce latency, particularly for short sounds that must be played quickly, such as bullets or explosions. You can force such sounds to be decoded and retained in memory rather than streamed from disk by wrapping the source in a `StaticSource`:: bullet_sound = StaticSource(load('bullet.wav')) The other advantage of a `StaticSource` is that it can be queued on any number of players, and so played many times simultaneously. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import atexit import ctypes import heapq import sys import threading import time import pyglet from pyglet.compat import bytes_type, BytesIO _debug = pyglet.options['debug_media'] class MediaException(Exception): pass class MediaFormatException(MediaException): pass class CannotSeekException(MediaException): pass class MediaThread(object): '''A thread that cleanly exits on interpreter shutdown, and provides a sleep method that can be interrupted and a termination method. :Ivariables: `condition` : threading.Condition Lock condition on all instance variables. `stopped` : bool True if `stop` has been called. ''' _threads = set() _threads_lock = threading.Lock() def __init__(self, target=None): self._thread = threading.Thread(target=self._thread_run) self._thread.setDaemon(True) if target is not None: self.run = target self.condition = threading.Condition() self.stopped = False @classmethod def _atexit(cls): cls._threads_lock.acquire() threads = list(cls._threads) cls._threads_lock.release() for thread in threads: thread.stop() def run(self): pass def _thread_run(self): if pyglet.options['debug_trace']: pyglet._install_trace() self._threads_lock.acquire() self._threads.add(self) self._threads_lock.release() self.run() self._threads_lock.acquire() self._threads.remove(self) self._threads_lock.release() def start(self): self._thread.start() def stop(self): '''Stop the thread and wait for it to terminate. The `stop` instance variable is set to ``True`` and the condition is notified. It is the responsibility of the `run` method to check the value of `stop` after each sleep or wait and to return if set. ''' if _debug: print 'MediaThread.stop()' self.condition.acquire() self.stopped = True self.condition.notify() self.condition.release() self._thread.join() def sleep(self, timeout): '''Wait for some amount of time, or until notified. :Parameters: `timeout` : float Time to wait, in seconds. ''' if _debug: print 'MediaThread.sleep(%r)' % timeout self.condition.acquire() self.condition.wait(timeout) self.condition.release() def notify(self): '''Interrupt the current sleep operation. If the thread is currently sleeping, it will be woken immediately, instead of waiting the full duration of the timeout. ''' if _debug: print 'MediaThread.notify()' self.condition.acquire() self.condition.notify() self.condition.release() atexit.register(MediaThread._atexit) class WorkerThread(MediaThread): def __init__(self, target=None): super(WorkerThread, self).__init__(target) self._jobs = [] def run(self): while True: job = self.get_job() if not job: break job() def get_job(self): self.condition.acquire() while self._empty() and not self.stopped: self.condition.wait() if self.stopped: result = None else: result = self._get() self.condition.release() return result def put_job(self, job): self.condition.acquire() self._put(job) self.condition.notify() self.condition.release() def clear_jobs(self): self.condition.acquire() self._clear() self.condition.notify() self.condition.release() def _empty(self): return not self._jobs def _get(self): return self._jobs.pop(0) def _put(self, job): self._jobs.append(job) def _clear(self): del self._jobs[:] class AudioFormat(object): '''Audio details. An instance of this class is provided by sources with audio tracks. You should not modify the fields, as they are used internally to describe the format of data provided by the source. :Ivariables: `channels` : int The number of channels: 1 for mono or 2 for stereo (pyglet does not yet support surround-sound sources). `sample_size` : int Bits per sample; only 8 or 16 are supported. `sample_rate` : int Samples per second (in Hertz). ''' def __init__(self, channels, sample_size, sample_rate): self.channels = channels self.sample_size = sample_size self.sample_rate = sample_rate # Convenience self.bytes_per_sample = (sample_size >> 3) * channels self.bytes_per_second = self.bytes_per_sample * sample_rate def __eq__(self, other): return (self.channels == other.channels and self.sample_size == other.sample_size and self.sample_rate == other.sample_rate) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return '%s(channels=%d, sample_size=%d, sample_rate=%d)' % ( self.__class__.__name__, self.channels, self.sample_size, self.sample_rate) class VideoFormat(object): '''Video details. An instance of this class is provided by sources with a video track. You should not modify the fields. Note that the sample aspect has no relation to the aspect ratio of the video image. For example, a video image of 640x480 with sample aspect 2.0 should be displayed at 1280x480. It is the responsibility of the application to perform this scaling. :Ivariables: `width` : int Width of video image, in pixels. `height` : int Height of video image, in pixels. `sample_aspect` : float Aspect ratio (width over height) of a single video pixel. `frame_rate` : float Frame rate (frames per second) of the video. AVbin 8 or later is required, otherwise the frame rate will be ``None``. **Since:** pyglet 1.2. ''' def __init__(self, width, height, sample_aspect=1.0): self.width = width self.height = height self.sample_aspect = sample_aspect self.frame_rate = None class AudioData(object): '''A single packet of audio data. This class is used internally by pyglet. :Ivariables: `data` : str or ctypes array or pointer Sample data. `length` : int Size of sample data, in bytes. `timestamp` : float Time of the first sample, in seconds. `duration` : float Total data duration, in seconds. `events` : list of MediaEvent List of events contained within this packet. Events are timestamped relative to this audio packet. ''' def __init__(self, data, length, timestamp, duration, events): self.data = data self.length = length self.timestamp = timestamp self.duration = duration self.events = events def consume(self, bytes, audio_format): '''Remove some data from beginning of packet. All events are cleared.''' self.events = () if bytes == self.length: self.data = None self.length = 0 self.timestamp += self.duration self.duration = 0. return elif bytes == 0: return if not isinstance(self.data, str): # XXX Create a string buffer for the whole packet then # chop it up. Could do some pointer arith here and # save a bit of data pushing, but my guess is this is # faster than fudging aruond with ctypes (and easier). data = ctypes.create_string_buffer(self.length) ctypes.memmove(data, self.data, self.length) self.data = data self.data = self.data[bytes:] self.length -= bytes self.duration -= bytes / float(audio_format.bytes_per_second) self.timestamp += bytes / float(audio_format.bytes_per_second) def get_string_data(self): '''Return data as a string. (Python 3: return as bytes)''' if isinstance(self.data, bytes_type): return self.data buf = ctypes.create_string_buffer(self.length) ctypes.memmove(buf, self.data, self.length) return buf.raw class MediaEvent(object): def __init__(self, timestamp, event, *args): # Meaning of timestamp is dependent on context; and not seen by # application. self.timestamp = timestamp self.event = event self.args = args def _sync_dispatch_to_player(self, player): pyglet.app.platform_event_loop.post_event(player, self.event, *self.args) time.sleep(0) # TODO sync with media.dispatch_events def __repr__(self): return '%s(%r, %r, %r)' % (self.__class__.__name__, self.timestamp, self.event, self.args) def __lt__(self, other): return hash(self) < hash(other) class SourceInfo(object): '''Source metadata information. Fields are the empty string or zero if the information is not available. :Ivariables: `title` : str Title `author` : str Author `copyright` : str Copyright statement `comment` : str Comment `album` : str Album name `year` : int Year `track` : int Track number `genre` : str Genre :since: pyglet 1.2 ''' title = '' author = '' copyright = '' comment = '' album = '' year = 0 track = 0 genre = '' class Source(object): '''An audio and/or video source. :Ivariables: `audio_format` : `AudioFormat` Format of the audio in this source, or None if the source is silent. `video_format` : `VideoFormat` Format of the video in this source, or None if there is no video. `info` : `SourceInfo` Source metadata such as title, artist, etc; or None if the information is not available. **Since:** pyglet 1.2 ''' _duration = None audio_format = None video_format = None info = None def _get_duration(self): return self._duration duration = property(lambda self: self._get_duration(), doc='''The length of the source, in seconds. Not all source durations can be determined; in this case the value is None. Read-only. :type: float ''') def play(self): '''Play the source. This is a convenience method which creates a ManagedSoundPlayer for this source and plays it immediately. :rtype: `ManagedSoundPlayer` ''' player = ManagedSoundPlayer() player.queue(self) player.play() return player def get_animation(self): '''Import all video frames into memory as an `Animation`. An empty animation will be returned if the source has no video. Otherwise, the animation will contain all unplayed video frames (the entire source, if it has not been queued on a player). After creating the animation, the source will be at EOS. This method is unsuitable for videos running longer than a few seconds. :since: pyglet 1.1 :rtype: `pyglet.image.Animation` ''' from pyglet.image import Animation, AnimationFrame if not self.video_format: return Animation([]) else: frames = [] last_ts = 0 next_ts = self.get_next_video_timestamp() while next_ts is not None: image = self.get_next_video_frame() if image is not None: delay = next_ts - last_ts frames.append(AnimationFrame(image, delay)) last_ts = next_ts next_ts = self.get_next_video_timestamp() return Animation(frames) def get_next_video_timestamp(self): '''Get the timestamp of the next video frame. :since: pyglet 1.1 :rtype: float :return: The next timestamp, or ``None`` if there are no more video frames. ''' pass def get_next_video_frame(self): '''Get the next video frame. Video frames may share memory: the previous frame may be invalidated or corrupted when this method is called unless the application has made a copy of it. :since: pyglet 1.1 :rtype: `pyglet.image.AbstractImage` :return: The next video frame image, or ``None`` if the video frame could not be decoded or there are no more video frames. ''' pass # Internal methods that SourceGroup calls on the source: def seek(self, timestamp): '''Seek to given timestamp.''' raise CannotSeekException() def _get_queue_source(self): '''Return the `Source` to be used as the queue source for a player. Default implementation returns self.''' return self def get_audio_data(self, bytes): '''Get next packet of audio data. :Parameters: `bytes` : int Maximum number of bytes of data to return. :rtype: `AudioData` :return: Next packet of audio data, or None if there is no (more) data. ''' return None class StreamingSource(Source): '''A source that is decoded as it is being played, and can only be queued once. ''' _is_queued = False is_queued = property(lambda self: self._is_queued, doc='''Determine if this source has been queued on a `Player` yet. Read-only. :type: bool ''') def _get_queue_source(self): '''Return the `Source` to be used as the queue source for a player. Default implementation returns self.''' if self._is_queued: raise MediaException('This source is already queued on a player.') self._is_queued = True return self class StaticSource(Source): '''A source that has been completely decoded in memory. This source can be queued onto multiple players any number of times. ''' def __init__(self, source): '''Construct a `StaticSource` for the data in `source`. :Parameters: `source` : `Source` The source to read and decode audio and video data from. ''' source = source._get_queue_source() if source.video_format: raise NotImplementedError( 'Static sources not supported for video yet.') self.audio_format = source.audio_format if not self.audio_format: return # Arbitrary: number of bytes to request at a time. buffer_size = 1 << 20 # 1 MB # Naive implementation. Driver-specific implementations may override # to load static audio data into device (or at least driver) memory. data = BytesIO() while True: audio_data = source.get_audio_data(buffer_size) if not audio_data: break data.write(audio_data.get_string_data()) self._data = data.getvalue() self._duration = len(self._data) / \ float(self.audio_format.bytes_per_second) def _get_queue_source(self): return StaticMemorySource(self._data, self.audio_format) def get_audio_data(self, bytes): raise RuntimeError('StaticSource cannot be queued.') class StaticMemorySource(StaticSource): '''Helper class for default implementation of `StaticSource`. Do not use directly.''' def __init__(self, data, audio_format): '''Construct a memory source over the given data buffer. ''' self._file = BytesIO(data) self._max_offset = len(data) self.audio_format = audio_format self._duration = len(data) / float(audio_format.bytes_per_second) def seek(self, timestamp): offset = int(timestamp * self.audio_format.bytes_per_second) # Align to sample if self.audio_format.bytes_per_sample == 2: offset &= 0xfffffffe elif self.audio_format.bytes_per_sample == 4: offset &= 0xfffffffc self._file.seek(offset) def get_audio_data(self, bytes): offset = self._file.tell() timestamp = float(offset) / self.audio_format.bytes_per_second # Align to sample size if self.audio_format.bytes_per_sample == 2: bytes &= 0xfffffffe elif self.audio_format.bytes_per_sample == 4: bytes &= 0xfffffffc data = self._file.read(bytes) if not len(data): return None duration = float(len(data)) / self.audio_format.bytes_per_second return AudioData(data, len(data), timestamp, duration, []) class SourceGroup(object): '''Read data from a queue of sources, with support for looping. All sources must share the same audio format. :Ivariables: `audio_format` : `AudioFormat` Required audio format for queued sources. ''' # TODO can sources list go empty? what behaviour (ignore or error)? _advance_after_eos = False _loop = False def __init__(self, audio_format, video_format): self.audio_format = audio_format self.video_format = video_format self.duration = 0. self._timestamp_offset = 0. self._dequeued_durations = [] self._sources = [] def seek(self, time): if self._sources: self._sources[0].seek(time) def queue(self, source): source = source._get_queue_source() assert(source.audio_format == self.audio_format) self._sources.append(source) self.duration += source.duration def has_next(self): return len(self._sources) > 1 def next(self, immediate=True): if immediate: self._advance() else: self._advance_after_eos = True def get_current_source(self): if self._sources: return self._sources[0] def _advance(self): if self._sources: self._timestamp_offset += self._sources[0].duration self._dequeued_durations.insert(0, self._sources[0].duration) old_source = self._sources.pop(0) self.duration -= old_source.duration def _get_loop(self): return self._loop def _set_loop(self, loop): self._loop = loop loop = property(_get_loop, _set_loop, doc='''Loop the current source indefinitely or until `next` is called. Initially False. :type: bool ''') def get_audio_data(self, bytes): '''Get next audio packet. :Parameters: `bytes` : int Hint for preferred size of audio packet; may be ignored. :rtype: `AudioData` :return: Audio data, or None if there is no more data. ''' data = self._sources[0].get_audio_data(bytes) eos = False while not data: eos = True if self._loop and not self._advance_after_eos: self._timestamp_offset += self._sources[0].duration self._dequeued_durations.insert(0, self._sources[0].duration) self._sources[0].seek(0) else: self._advance_after_eos = False # Advance source if there's something to advance to. # Otherwise leave last source paused at EOS. if len(self._sources) > 1: self._advance() else: return None data = self._sources[0].get_audio_data(bytes) # TODO method rename data.timestamp += self._timestamp_offset if eos: if _debug: print 'adding on_eos event to audio data' data.events.append(MediaEvent(0, 'on_eos')) return data def translate_timestamp(self, timestamp): '''Get source-relative timestamp for the audio player's timestamp.''' # XXX if timestamp is None: return None timestamp = timestamp - self._timestamp_offset if timestamp < 0: for duration in self._dequeued_durations[::-1]: timestamp += duration if timestamp > 0: break assert timestamp >= 0, 'Timestamp beyond dequeued source memory' return timestamp def get_next_video_timestamp(self): '''Get the timestamp of the next video frame. :rtype: float :return: The next timestamp, or ``None`` if there are no more video frames. ''' # TODO track current video source independently from audio source for # better prebuffering. timestamp = self._sources[0].get_next_video_timestamp() if timestamp is not None: timestamp += self._timestamp_offset return timestamp def get_next_video_frame(self): '''Get the next video frame. Video frames may share memory: the previous frame may be invalidated or corrupted when this method is called unless the application has made a copy of it. :rtype: `pyglet.image.AbstractImage` :return: The next video frame image, or ``None`` if the video frame could not be decoded or there are no more video frames. ''' return self._sources[0].get_next_video_frame() class AbstractAudioPlayer(object): '''Base class for driver audio players. ''' def __init__(self, source_group, player): '''Create a new audio player. :Parameters: `source_group` : `SourceGroup` Source group to play from. `player` : `Player` Player to receive EOS and video frame sync events. ''' self.source_group = source_group self.player = player def play(self): '''Begin playback.''' raise NotImplementedError('abstract') def stop(self): '''Stop (pause) playback.''' raise NotImplementedError('abstract') def delete(self): '''Stop playing and clean up all resources used by player.''' raise NotImplementedError('abstract') def _play_group(self, audio_players): '''Begin simultaneous playback on a list of audio players.''' # This should be overridden by subclasses for better synchrony. for player in audio_players: player.play() def _stop_group(self, audio_players): '''Stop simultaneous playback on a list of audio players.''' # This should be overridden by subclasses for better synchrony. for player in audio_players: player.play() def clear(self): '''Clear all buffered data and prepare for replacement data. The player should be stopped before calling this method. ''' raise NotImplementedError('abstract') def get_time(self): '''Return approximation of current playback time within current source. Returns ``None`` if the audio player does not know what the playback time is (for example, before any valid audio data has been read). :rtype: float :return: current play cursor time, in seconds. ''' # TODO determine which source within group raise NotImplementedError('abstract') def set_volume(self, volume): '''See `Player.volume`.''' pass def set_position(self, position): '''See `Player.position`.''' pass def set_min_distance(self, min_distance): '''See `Player.min_distance`.''' pass def set_max_distance(self, max_distance): '''See `Player.max_distance`.''' pass def set_pitch(self, pitch): '''See `Player.pitch`.''' pass def set_cone_orientation(self, cone_orientation): '''See `Player.cone_orientation`.''' pass def set_cone_inner_angle(self, cone_inner_angle): '''See `Player.cone_inner_angle`.''' pass def set_cone_outer_angle(self, cone_outer_angle): '''See `Player.cone_outer_angle`.''' pass def set_cone_outer_gain(self, cone_outer_gain): '''See `Player.cone_outer_gain`.''' pass class Player(pyglet.event.EventDispatcher): '''High-level sound and video player. ''' _last_video_timestamp = None _texture = None # Spacialisation attributes, preserved between audio players _volume = 1.0 _min_distance = 1.0 _max_distance = 100000000. _position = (0, 0, 0) _pitch = 1.0 _cone_orientation = (0, 0, 1) _cone_inner_angle = 360. _cone_outer_angle = 360. _cone_outer_gain = 1. #: The player will pause when it reaches the end of the stream. #: #: :deprecated: Use `SourceGroup.advance_after_eos` EOS_PAUSE = 'pause' #: The player will loop the current stream continuosly. #: #: :deprecated: Use `SourceGroup.loop` EOS_LOOP = 'loop' #: The player will move on to the next queued stream when it reaches the #: end of the current source. If there is no source queued, the player #: will pause. #: #: :deprecated: Use `SourceGroup.advance_after_eos` EOS_NEXT = 'next' #: The player will stop entirely; valid only for ManagedSoundPlayer. #: #: :deprecated: Use `SourceGroup.advance_after_eos` EOS_STOP = 'stop' #: :deprecated: _eos_action = EOS_NEXT def __init__(self): # List of queued source groups self._groups = [] self._audio_player = None # Desired play state (not an indication of actual state). self._playing = False self._paused_time = 0.0 def queue(self, source): if (self._groups and source.audio_format == self._groups[-1].audio_format and source.video_format == self._groups[-1].video_format): self._groups[-1].queue(source) else: group = SourceGroup(source.audio_format, source.video_format) group.queue(source) self._groups.append(group) self._set_eos_action(self._eos_action) self._set_playing(self._playing) def _set_playing(self, playing): #stopping = self._playing and not playing #starting = not self._playing and playing self._playing = playing source = self.source if playing and source: if not self._audio_player: self._create_audio_player() self._audio_player.play() if source.video_format: if not self._texture: self._create_texture() if self.source.video_format.frame_rate: period = 1. / self.source.video_format.frame_rate else: period = 1. / 30. pyglet.clock.schedule_interval(self.update_texture, period) else: if self._audio_player: self._audio_player.stop() pyglet.clock.unschedule(self.update_texture) def play(self): self._set_playing(True) def pause(self): self._set_playing(False) if self._audio_player: time = self._audio_player.get_time() time = self._groups[0].translate_timestamp(time) if time is not None: self._paused_time = time self._audio_player.stop() def next(self): if not self._groups: return group = self._groups[0] if group.has_next(): group.next() return if self.source.video_format: self._texture = None pyglet.clock.unschedule(self.update_texture) if self._audio_player: self._audio_player.delete() self._audio_player = None del self._groups[0] if self._groups: self._set_playing(self._playing) return self._set_playing(False) self.dispatch_event('on_player_eos') def seek(self, time): if _debug: print 'Player.seek(%r)' % time self._paused_time = time self.source.seek(time) if self._audio_player: self._audio_player.clear() if self.source.video_format: self._last_video_timestamp = None self.update_texture(time=time) def _create_audio_player(self): assert not self._audio_player assert self._groups group = self._groups[0] audio_format = group.audio_format if audio_format: audio_driver = get_audio_driver() else: audio_driver = get_silent_audio_driver() self._audio_player = audio_driver.create_audio_player(group, self) _class = self.__class__ def _set(name): private_name = '_' + name value = getattr(self, private_name) if value != getattr(_class, private_name): getattr(self._audio_player, 'set_' + name)(value) _set('volume') _set('min_distance') _set('max_distance') _set('position') _set('pitch') _set('cone_orientation') _set('cone_inner_angle') _set('cone_outer_angle') _set('cone_outer_gain') def _get_source(self): if not self._groups: return None return self._groups[0].get_current_source() source = property(_get_source) playing = property(lambda self: self._playing) def _get_time(self): time = None if self._playing and self._audio_player: time = self._audio_player.get_time() time = self._groups[0].translate_timestamp(time) if time is None: return self._paused_time else: return time time = property(_get_time) def _create_texture(self): video_format = self.source.video_format self._texture = pyglet.image.Texture.create( video_format.width, video_format.height, rectangle=True) self._texture = self._texture.get_transform(flip_y=True) self._texture.anchor_y = 0 def get_texture(self): return self._texture def seek_next_frame(self): '''Step forwards one video frame in the current Source. ''' time = self._groups[0].get_next_video_timestamp() if time is None: return self.seek(time) def update_texture(self, dt=None, time=None): if time is None: time = self._audio_player.get_time() if time is None: return if (self._last_video_timestamp is not None and time <= self._last_video_timestamp): return ts = self._groups[0].get_next_video_timestamp() while ts is not None and ts < time: self._groups[0].get_next_video_frame() # Discard frame ts = self._groups[0].get_next_video_timestamp() if ts is None: self._last_video_timestamp = None return image = self._groups[0].get_next_video_frame() if image is not None: if self._texture is None: self._create_texture() self._texture.blit_into(image, 0, 0, 0) self._last_video_timestamp = ts def _set_eos_action(self, eos_action): ''':deprecated:''' assert eos_action in (self.EOS_NEXT, self.EOS_STOP, self.EOS_PAUSE, self.EOS_LOOP) self._eos_action = eos_action for group in self._groups: group.loop = eos_action == self.EOS_LOOP group.advance_after_eos = eos_action == self.EOS_NEXT eos_action = property(lambda self: self._eos_action, _set_eos_action, doc='''Set the behaviour of the player when it reaches the end of the current source. This must be one of the constants `EOS_NEXT`, `EOS_PAUSE`, `EOS_STOP` or `EOS_LOOP`. :deprecated: Use `SourceGroup.loop` and `SourceGroup.advance_after_eos` :type: str ''') def _player_property(name, doc=None): private_name = '_' + name set_name = 'set_' + name def _player_property_set(self, value): setattr(self, private_name, value) if self._audio_player: getattr(self._audio_player, set_name)(value) def _player_property_get(self): return getattr(self, private_name) return property(_player_property_get, _player_property_set, doc=doc) # TODO docstrings for these... volume = _player_property('volume') min_distance = _player_property('min_distance') max_distance = _player_property('max_distance') position = _player_property('position') pitch = _player_property('pitch') cone_orientation = _player_property('cone_orientation') cone_inner_angle = _player_property('cone_inner_angle') cone_outer_angle = _player_property('cone_outer_angle') cone_outer_gain = _player_property('cone_outer_gain') # Events def on_player_eos(self): '''The player ran out of sources. :event: ''' if _debug: print 'Player.on_player_eos' def on_source_group_eos(self): '''The current source group ran out of data. The default behaviour is to advance to the next source group if possible. :event: ''' self.next() if _debug: print 'Player.on_source_group_eos' def on_eos(self): ''' :event: ''' if _debug: print 'Player.on_eos' Player.register_event_type('on_eos') Player.register_event_type('on_player_eos') Player.register_event_type('on_source_group_eos') class ManagedSoundPlayer(Player): ''':deprecated: Use `Player`''' pass class PlayerGroup(object): '''Group of players that can be played and paused simultaneously. :Ivariables: `players` : list of `Player` Players in this group. ''' def __init__(self, players): '''Create a player group for the given set of players. All players in the group must currently not belong to any other group. :Parameters: `players` : Sequence of `Player` Players to add to this group. ''' self.players = list(players) def play(self): '''Begin playing all players in the group simultaneously. ''' audio_players = [p._audio_player \ for p in self.players if p._audio_player] if audio_players: audio_players[0]._play_group(audio_players) for player in self.players: player.play() def pause(self): '''Pause all players in the group simultaneously. ''' audio_players = [p._audio_player \ for p in self.players if p._audio_player] if audio_players: audio_players[0]._stop_group(audio_players) for player in self.players: player.pause() class AbstractAudioDriver(object): def create_audio_player(self, source_group, player): raise NotImplementedError('abstract') def get_listener(self): raise NotImplementedError('abstract') class AbstractListener(object): '''The listener properties for positional audio. You can obtain the singleton instance of this class by calling `AbstractAudioDriver.get_listener`. ''' _volume = 1.0 _position = (0, 0, 0) _forward_orientation = (0, 0, -1) _up_orientation = (0, 1, 0) def _set_volume(self, volume): raise NotImplementedError('abstract') volume = property(lambda self: self._volume, lambda self, volume: self._set_volume(volume), doc='''The master volume for sound playback. All sound volumes are multiplied by this master volume before being played. A value of 0 will silence playback (but still consume resources). The nominal volume is 1.0. :type: float ''') def _set_position(self, position): raise NotImplementedError('abstract') position = property(lambda self: self._position, lambda self, position: self._set_position(position), doc='''The position of the listener in 3D space. The position is given as a tuple of floats (x, y, z). The unit defaults to meters, but can be modified with the listener properties. :type: 3-tuple of float ''') def _set_forward_orientation(self, orientation): raise NotImplementedError('abstract') forward_orientation = property(lambda self: self._forward_orientation, lambda self, o: self._set_forward_orientation(o), doc='''A vector giving the direction the listener is facing. The orientation is given as a tuple of floats (x, y, z), and has no unit. The forward orientation should be orthagonal to the up orientation. :type: 3-tuple of float ''') def _set_up_orientation(self, orientation): raise NotImplementedError('abstract') up_orientation = property(lambda self: self._up_orientation, lambda self, o: self._set_up_orientation(o), doc='''A vector giving the "up" orientation of the listener. The orientation is given as a tuple of floats (x, y, z), and has no unit. The up orientation should be orthagonal to the forward orientation. :type: 3-tuple of float ''') class _LegacyListener(AbstractListener): def _set_volume(self, volume): get_audio_driver().get_listener().volume = volume self._volume = volume def _set_position(self, position): get_audio_driver().get_listener().position = position self._position = position def _set_forward_orientation(self, forward_orientation): get_audio_driver().get_listener().forward_orientation = \ forward_orientation self._forward_orientation = forward_orientation def _set_up_orientation(self, up_orientation): get_audio_driver().get_listener().up_orientation = up_orientation self._up_orientation = up_orientation #: The singleton `AbstractListener` object. #: #: :deprecated: Use `AbstractAudioDriver.get_listener` #: #: :type: `AbstractListener` listener = _LegacyListener() class AbstractSourceLoader(object): def load(self, filename, file): raise NotImplementedError('abstract') class AVbinSourceLoader(AbstractSourceLoader): def load(self, filename, file): import avbin return avbin.AVbinSource(filename, file) class RIFFSourceLoader(AbstractSourceLoader): def load(self, filename, file): import riff return riff.WaveSource(filename, file) def load(filename, file=None, streaming=True): '''Load a source from a file. Currently the `file` argument is not supported; media files must exist as real paths. :Parameters: `filename` : str Filename of the media file to load. `file` : file-like object Not yet supported. `streaming` : bool If False, a `StaticSource` will be returned; otherwise (default) a `StreamingSource` is created. :rtype: `Source` ''' source = get_source_loader().load(filename, file) if not streaming: source = StaticSource(source) return source def get_audio_driver(): global _audio_driver if _audio_driver: return _audio_driver _audio_driver = None for driver_name in pyglet.options['audio']: try: if driver_name == 'pulse': from drivers import pulse _audio_driver = pulse.create_audio_driver() break elif driver_name == 'openal': from drivers import openal _audio_driver = openal.create_audio_driver() break elif driver_name == 'directsound': from drivers import directsound _audio_driver = directsound.create_audio_driver() break elif driver_name == 'silent': _audio_driver = get_silent_audio_driver() break except: if _debug: print 'Error importing driver %s' % driver_name return _audio_driver def get_silent_audio_driver(): global _silent_audio_driver if not _silent_audio_driver: from drivers import silent _silent_audio_driver = silent.create_audio_driver() return _silent_audio_driver _audio_driver = None _silent_audio_driver = None def get_source_loader(): global _source_loader if _source_loader: return _source_loader try: import avbin _source_loader = AVbinSourceLoader() except ImportError: _source_loader = RIFFSourceLoader() return _source_loader _source_loader = None try: import avbin have_avbin = True except ImportError: have_avbin = False
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Events for `pyglet.window`. See `Window` for a description of the window event types. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import sys from pyglet.window import key from pyglet.window import mouse class WindowExitHandler(object): '''Determine if the window should be closed. This event handler watches for the ESC key or the window close event and sets `self.has_exit` to True when either is pressed. An instance of this class is automatically attached to all new `pyglet.window.Window` objects. :deprecated: This class's functionality is provided directly on `Window` in pyglet 1.1. :Ivariables: `has_exit` : bool True if the user wants to close the window. ''' has_exit = False def on_close(self): self.has_exit = True def on_key_press(self, symbol, modifiers): if symbol == key.ESCAPE: self.has_exit = True class WindowEventLogger(object): '''Print all events to a file. When this event handler is added to a window it prints out all events and their parameters; useful for debugging or discovering which events you need to handle. Example:: win = window.Window() win.push_handlers(WindowEventLogger()) ''' def __init__(self, logfile=None): '''Create a `WindowEventLogger` which writes to `logfile`. :Parameters: `logfile` : file-like object The file to write to. If unspecified, stdout will be used. ''' if logfile is None: logfile = sys.stdout self.file = logfile def on_key_press(self, symbol, modifiers): print >> self.file, 'on_key_press(symbol=%s, modifiers=%s)' % ( key.symbol_string(symbol), key.modifiers_string(modifiers)) def on_key_release(self, symbol, modifiers): print >> self.file, 'on_key_release(symbol=%s, modifiers=%s)' % ( key.symbol_string(symbol), key.modifiers_string(modifiers)) def on_text(self, text): print >> self.file, 'on_text(text=%r)' % text def on_text_motion(self, motion): print >> self.file, 'on_text_motion(motion=%s)' % ( key.motion_string(motion)) def on_text_motion_select(self, motion): print >> self.file, 'on_text_motion_select(motion=%s)' % ( key.motion_string(motion)) def on_mouse_motion(self, x, y, dx, dy): print >> self.file, 'on_mouse_motion(x=%d, y=%d, dx=%d, dy=%d)' % ( x, y, dx, dy) def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): print >> self.file, 'on_mouse_drag(x=%d, y=%d, dx=%d, dy=%d, '\ 'buttons=%s, modifiers=%s)' % ( x, y, dx, dy, mouse.buttons_string(buttons), key.modifiers_string(modifiers)) def on_mouse_press(self, x, y, button, modifiers): print >> self.file, 'on_mouse_press(x=%d, y=%d, button=%r, '\ 'modifiers=%s)' % (x, y, mouse.buttons_string(button), key.modifiers_string(modifiers)) def on_mouse_release(self, x, y, button, modifiers): print >> self.file, 'on_mouse_release(x=%d, y=%d, button=%r, '\ 'modifiers=%s)' % (x, y, mouse.buttons_string(button), key.modifiers_string(modifiers)) def on_mouse_scroll(self, x, y, dx, dy): print >> self.file, 'on_mouse_scroll(x=%f, y=%f, dx=%f, dy=%f)' % ( x, y, dx, dy) def on_close(self): print >> self.file, 'on_close()' def on_mouse_enter(self, x, y): print >> self.file, 'on_mouse_enter(x=%d, y=%d)' % (x, y) def on_mouse_leave(self, x, y): print >> self.file, 'on_mouse_leave(x=%d, y=%d)' % (x, y) def on_expose(self): print >> self.file, 'on_expose()' def on_resize(self, width, height): print >> self.file, 'on_resize(width=%d, height=%d)' % (width, height) def on_move(self, x, y): print >> self.file, 'on_move(x=%d, y=%d)' % (x, y) def on_activate(self): print >> self.file, 'on_activate()' def on_deactivate(self): print >> self.file, 'on_deactivate()' def on_show(self): print >> self.file, 'on_show()' def on_hide(self): print >> self.file, 'on_hide()' def on_context_lost(self): print >> self.file, 'on_context_lost()' def on_context_state_lost(self): print >> self.file, 'on_context_state_lost()' def on_draw(self): print >> self.file, 'on_draw()'
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Key constants and utilities for pyglet.window. Usage:: from pyglet.window import Window from pyglet.window import key window = Window() @window.event def on_key_press(symbol, modifiers): # Symbolic names: if symbol == key.RETURN: # Alphabet keys: elif symbol == key.Z: # Number keys: elif symbol == key._1: # Number keypad keys: elif symbol == key.NUM_1: # Modifiers: if modifiers & key.MOD_CTRL: ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' class KeyStateHandler(dict): '''Simple handler that tracks the state of keys on the keyboard. If a key is pressed then this handler holds a True value for it. For example:: >>> win = window.Window >>> keyboard = key.KeyStateHandler() >>> win.push_handlers(keyboard) # Hold down the "up" arrow... >>> keyboard[key.UP] True >>> keyboard[key.DOWN] False ''' def on_key_press(self, symbol, modifiers): self[symbol] = True def on_key_release(self, symbol, modifiers): self[symbol] = False def __getitem__(self, key): return self.get(key, False) def modifiers_string(modifiers): '''Return a string describing a set of modifiers. Example:: >>> modifiers_string(MOD_SHIFT | MOD_CTRL) 'MOD_SHIFT|MOD_CTRL' :Parameters: `modifiers` : int Bitwise combination of modifier constants. :rtype: str ''' mod_names = [] if modifiers & MOD_SHIFT: mod_names.append('MOD_SHIFT') if modifiers & MOD_CTRL: mod_names.append('MOD_CTRL') if modifiers & MOD_ALT: mod_names.append('MOD_ALT') if modifiers & MOD_CAPSLOCK: mod_names.append('MOD_CAPSLOCK') if modifiers & MOD_NUMLOCK: mod_names.append('MOD_NUMLOCK') if modifiers & MOD_SCROLLLOCK: mod_names.append('MOD_SCROLLLOCK') if modifiers & MOD_COMMAND: mod_names.append('MOD_COMMAND') if modifiers & MOD_OPTION: mod_names.append('MOD_OPTION') if modifiers & MOD_FUNCTION: mod_names.append('MOD_FUNCTION') return '|'.join(mod_names) def symbol_string(symbol): '''Return a string describing a key symbol. Example:: >>> symbol_string(BACKSPACE) 'BACKSPACE' :Parameters: `symbol` : int Symbolic key constant. :rtype: str ''' if symbol < 1 << 32: return _key_names.get(symbol, str(symbol)) else: return 'user_key(%x)' % (symbol >> 32) def motion_string(motion): '''Return a string describing a text motion. Example:: >>> motion_string(MOTION_NEXT_WORD): 'MOTION_NEXT_WORD' :Parameters: `motion` : int Text motion constant. :rtype: str ''' return _motion_names.get(motion, str(motion)) def user_key(scancode): '''Return a key symbol for a key not supported by pyglet. This can be used to map virtual keys or scancodes from unsupported keyboard layouts into a machine-specific symbol. The symbol will be meaningless on any other machine, or under a different keyboard layout. Applications should use user-keys only when user explicitly binds them (for example, mapping keys to actions in a game options screen). ''' assert scancode > 0 return scancode << 32 # Modifier mask constants MOD_SHIFT = 1 << 0 MOD_CTRL = 1 << 1 MOD_ALT = 1 << 2 MOD_CAPSLOCK = 1 << 3 MOD_NUMLOCK = 1 << 4 MOD_WINDOWS = 1 << 5 MOD_COMMAND = 1 << 6 MOD_OPTION = 1 << 7 MOD_SCROLLLOCK = 1 << 8 MOD_FUNCTION = 1 << 9 #: Accelerator modifier. On Windows and Linux, this is ``MOD_CTRL``, on #: Mac OS X it's ``MOD_COMMAND``. MOD_ACCEL = MOD_CTRL import sys as _sys if _sys.platform == 'darwin': MOD_ACCEL = MOD_COMMAND # Key symbol constants # ASCII commands BACKSPACE = 0xff08 TAB = 0xff09 LINEFEED = 0xff0a CLEAR = 0xff0b RETURN = 0xff0d ENTER = 0xff0d # synonym PAUSE = 0xff13 SCROLLLOCK = 0xff14 SYSREQ = 0xff15 ESCAPE = 0xff1b SPACE = 0xff20 # Cursor control and motion HOME = 0xff50 LEFT = 0xff51 UP = 0xff52 RIGHT = 0xff53 DOWN = 0xff54 PAGEUP = 0xff55 PAGEDOWN = 0xff56 END = 0xff57 BEGIN = 0xff58 # Misc functions DELETE = 0xffff SELECT = 0xff60 PRINT = 0xff61 EXECUTE = 0xff62 INSERT = 0xff63 UNDO = 0xff65 REDO = 0xff66 MENU = 0xff67 FIND = 0xff68 CANCEL = 0xff69 HELP = 0xff6a BREAK = 0xff6b MODESWITCH = 0xff7e SCRIPTSWITCH = 0xff7e FUNCTION = 0xffd2 # Text motion constants: these are allowed to clash with key constants MOTION_UP = UP MOTION_RIGHT = RIGHT MOTION_DOWN = DOWN MOTION_LEFT = LEFT MOTION_NEXT_WORD = 1 MOTION_PREVIOUS_WORD = 2 MOTION_BEGINNING_OF_LINE = 3 MOTION_END_OF_LINE = 4 MOTION_NEXT_PAGE = PAGEDOWN MOTION_PREVIOUS_PAGE = PAGEUP MOTION_BEGINNING_OF_FILE = 5 MOTION_END_OF_FILE = 6 MOTION_BACKSPACE = BACKSPACE MOTION_DELETE = DELETE # Number pad NUMLOCK = 0xff7f NUM_SPACE = 0xff80 NUM_TAB = 0xff89 NUM_ENTER = 0xff8d NUM_F1 = 0xff91 NUM_F2 = 0xff92 NUM_F3 = 0xff93 NUM_F4 = 0xff94 NUM_HOME = 0xff95 NUM_LEFT = 0xff96 NUM_UP = 0xff97 NUM_RIGHT = 0xff98 NUM_DOWN = 0xff99 NUM_PRIOR = 0xff9a NUM_PAGE_UP = 0xff9a NUM_NEXT = 0xff9b NUM_PAGE_DOWN = 0xff9b NUM_END = 0xff9c NUM_BEGIN = 0xff9d NUM_INSERT = 0xff9e NUM_DELETE = 0xff9f NUM_EQUAL = 0xffbd NUM_MULTIPLY = 0xffaa NUM_ADD = 0xffab NUM_SEPARATOR = 0xffac NUM_SUBTRACT = 0xffad NUM_DECIMAL = 0xffae NUM_DIVIDE = 0xffaf NUM_0 = 0xffb0 NUM_1 = 0xffb1 NUM_2 = 0xffb2 NUM_3 = 0xffb3 NUM_4 = 0xffb4 NUM_5 = 0xffb5 NUM_6 = 0xffb6 NUM_7 = 0xffb7 NUM_8 = 0xffb8 NUM_9 = 0xffb9 # Function keys F1 = 0xffbe F2 = 0xffbf F3 = 0xffc0 F4 = 0xffc1 F5 = 0xffc2 F6 = 0xffc3 F7 = 0xffc4 F8 = 0xffc5 F9 = 0xffc6 F10 = 0xffc7 F11 = 0xffc8 F12 = 0xffc9 F13 = 0xffca F14 = 0xffcb F15 = 0xffcc F16 = 0xffcd F17 = 0xffce F18 = 0xffcf F19 = 0xffd0 F20 = 0xffd1 # Modifiers LSHIFT = 0xffe1 RSHIFT = 0xffe2 LCTRL = 0xffe3 RCTRL = 0xffe4 CAPSLOCK = 0xffe5 LMETA = 0xffe7 RMETA = 0xffe8 LALT = 0xffe9 RALT = 0xffea LWINDOWS = 0xffeb RWINDOWS = 0xffec LCOMMAND = 0xffed RCOMMAND = 0xffee LOPTION = 0xffef ROPTION = 0xfff0 # Latin-1 SPACE = 0x020 EXCLAMATION = 0x021 DOUBLEQUOTE = 0x022 HASH = 0x023 POUND = 0x023 # synonym DOLLAR = 0x024 PERCENT = 0x025 AMPERSAND = 0x026 APOSTROPHE = 0x027 PARENLEFT = 0x028 PARENRIGHT = 0x029 ASTERISK = 0x02a PLUS = 0x02b COMMA = 0x02c MINUS = 0x02d PERIOD = 0x02e SLASH = 0x02f _0 = 0x030 _1 = 0x031 _2 = 0x032 _3 = 0x033 _4 = 0x034 _5 = 0x035 _6 = 0x036 _7 = 0x037 _8 = 0x038 _9 = 0x039 COLON = 0x03a SEMICOLON = 0x03b LESS = 0x03c EQUAL = 0x03d GREATER = 0x03e QUESTION = 0x03f AT = 0x040 BRACKETLEFT = 0x05b BACKSLASH = 0x05c BRACKETRIGHT = 0x05d ASCIICIRCUM = 0x05e UNDERSCORE = 0x05f GRAVE = 0x060 QUOTELEFT = 0x060 A = 0x061 B = 0x062 C = 0x063 D = 0x064 E = 0x065 F = 0x066 G = 0x067 H = 0x068 I = 0x069 J = 0x06a K = 0x06b L = 0x06c M = 0x06d N = 0x06e O = 0x06f P = 0x070 Q = 0x071 R = 0x072 S = 0x073 T = 0x074 U = 0x075 V = 0x076 W = 0x077 X = 0x078 Y = 0x079 Z = 0x07a BRACELEFT = 0x07b BAR = 0x07c BRACERIGHT = 0x07d ASCIITILDE = 0x07e _key_names = {} _motion_names = {} for _name, _value in locals().items(): if _name[:2] != '__' and _name.upper() == _name and \ not _name.startswith('MOD_'): if _name.startswith('MOTION_'): _motion_names[_value] = _name else: _key_names[_value] = _name
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * import os.path import unicodedata import warnings import pyglet from pyglet.window import WindowException, \ BaseWindow, MouseCursor, DefaultMouseCursor, _PlatformEventHandler from pyglet.window import key from pyglet.window import mouse from pyglet.window import event from pyglet.canvas.carbon import CarbonCanvas from pyglet.libs.darwin import * from pyglet.libs.darwin import _oscheck from pyglet.libs.darwin.quartzkey import keymap, charmap from pyglet.event import EventDispatcher # Map symbol,modifiers -> motion # Determined by experiment with TextEdit.app _motion_map = { (key.UP, False): key.MOTION_UP, (key.RIGHT, False): key.MOTION_RIGHT, (key.DOWN, False): key.MOTION_DOWN, (key.LEFT, False): key.MOTION_LEFT, (key.LEFT, key.MOD_OPTION): key.MOTION_PREVIOUS_WORD, (key.RIGHT, key.MOD_OPTION): key.MOTION_NEXT_WORD, (key.LEFT, key.MOD_COMMAND): key.MOTION_BEGINNING_OF_LINE, (key.RIGHT, key.MOD_COMMAND): key.MOTION_END_OF_LINE, (key.PAGEUP, False): key.MOTION_PREVIOUS_PAGE, (key.PAGEDOWN, False): key.MOTION_NEXT_PAGE, (key.HOME, False): key.MOTION_BEGINNING_OF_FILE, (key.END, False): key.MOTION_END_OF_FILE, (key.UP, key.MOD_COMMAND): key.MOTION_BEGINNING_OF_FILE, (key.DOWN, key.MOD_COMMAND): key.MOTION_END_OF_FILE, (key.BACKSPACE, False): key.MOTION_BACKSPACE, (key.DELETE, False): key.MOTION_DELETE, } class CarbonMouseCursor(MouseCursor): drawable = False def __init__(self, theme): self.theme = theme def CarbonEventHandler(event_class, event_kind): return _PlatformEventHandler((event_class, event_kind)) class CarbonWindow(BaseWindow): _window = None # Carbon WindowRef # Window properties _minimum_size = None _maximum_size = None _event_dispatcher = None _current_modifiers = 0 _mapped_modifers = 0 _carbon_event_handlers = [] _carbon_event_handler_refs = [] _track_ref = 0 _track_region = None _mouse_exclusive = False _mouse_platform_visible = True _mouse_ignore_motion = False _mouse_button_state = 0 def _recreate(self, changes): # We can't destroy the window while event handlers are active, # otherwise the (OS X) event dispatcher gets lost and segfaults. # # Defer actual recreation until dispatch_events next finishes. from pyglet import app app.platform_event_loop.post_event(self, 'on_recreate_immediate', changes) def on_recreate_immediate(self, changes): # The actual _recreate function. if ('context' in changes): self.context.detach() self._create() def _create(self): if self._window: # The window is about to be recreated; destroy everything # associated with the old window, then the window itself. self._remove_track_region() self._remove_event_handlers() self.context.detach() self.canvas = None carbon.DisposeWindow(self._window) self._window = None self._window = WindowRef() if self._fullscreen: rect = Rect() rect.left = 0 rect.top = 0 rect.right = self.screen.width rect.bottom = self.screen.height r = carbon.CreateNewWindow(kSimpleWindowClass, kWindowNoAttributes, byref(rect), byref(self._window)) _oscheck(r) # Set window level to shield level level = carbon.CGShieldingWindowLevel() WindowGroupRef = c_void_p group = WindowGroupRef() _oscheck(carbon.CreateWindowGroup(0, byref(group))) _oscheck(carbon.SetWindowGroup(self._window, group)) _oscheck(carbon.SetWindowGroupLevel(group, level)) # Set black background color = RGBColor(0, 0, 0) _oscheck(carbon.SetWindowContentColor(self._window, byref(color))) self._mouse_in_window = True self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_show') self.dispatch_event('on_expose') self._view_x = (self.screen.width - self._width) // 2 self._view_y = (self.screen.height - self._height) // 2 self.canvas = CarbonCanvas(self.display, self.screen, carbon.GetWindowPort(self._window)) self.canvas.bounds = (self._view_x, self._view_y, self._width, self._height) else: # Create floating window rect = Rect() location = None # TODO if location is not None: rect.left = location[0] rect.top = location[1] else: rect.top = rect.left = 0 rect.right = rect.left + self._width rect.bottom = rect.top + self._height styles = { self.WINDOW_STYLE_DEFAULT: (kDocumentWindowClass, kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute), self.WINDOW_STYLE_DIALOG: (kDocumentWindowClass, kWindowCloseBoxAttribute), self.WINDOW_STYLE_TOOL: (kUtilityWindowClass, kWindowCloseBoxAttribute), self.WINDOW_STYLE_BORDERLESS: (kSimpleWindowClass, kWindowNoAttributes) } window_class, window_attributes = \ styles.get(self._style, kDocumentWindowClass) if self._resizable: window_attributes |= (kWindowFullZoomAttribute | kWindowLiveResizeAttribute | kWindowResizableAttribute) r = carbon.CreateNewWindow(window_class, window_attributes, byref(rect), byref(self._window)) _oscheck(r) if location is None: carbon.RepositionWindow(self._window, c_void_p(), kWindowCascadeOnMainScreen) self.canvas = CarbonCanvas(self.display, self.screen, carbon.GetWindowPort(self._window)) self._view_x = self._view_y = 0 self.context.attach(self.canvas) self.set_caption(self._caption) # Get initial state self._event_dispatcher = carbon.GetEventDispatcherTarget() self._current_modifiers = carbon.GetCurrentKeyModifiers().value self._mapped_modifiers = self._map_modifiers(self._current_modifiers) # (re)install Carbon event handlers self._install_event_handlers() self._create_track_region() self.switch_to() # XXX self.set_vsync(self._vsync) if self._visible: self.set_visible(True) def _create_track_region(self): self._remove_track_region() # Create a tracking region for the content part of the window # to receive enter/leave events. track_id = MouseTrackingRegionID() track_id.signature = DEFAULT_CREATOR_CODE track_id.id = 1 self._track_ref = MouseTrackingRef() self._track_region = carbon.NewRgn() if self._fullscreen: carbon.SetRectRgn(self._track_region, self._view_x, self._view_y, self._view_x + self._width, self._view_y + self._height) options = kMouseTrackingOptionsGlobalClip else: carbon.GetWindowRegion(self._window, kWindowContentRgn, self._track_region) options = kMouseTrackingOptionsGlobalClip carbon.CreateMouseTrackingRegion(self._window, self._track_region, None, options, track_id, None, None, byref(self._track_ref)) def _remove_track_region(self): if self._track_region: carbon.ReleaseMouseTrackingRegion(self._track_region) self._track_region = None def close(self): super(CarbonWindow, self).close() self._remove_event_handlers() self._remove_track_region() # Restore cursor visibility self.set_mouse_platform_visible(True) self.set_exclusive_mouse(False) if self._window: carbon.DisposeWindow(self._window) self._window = None def switch_to(self): self.context.set_current() ''' agl.aglSetCurrentContext(self._agl_context) self._context.set_current() _aglcheck() # XXX TODO transpose gl[u]_info to gl.Context.attach gl_info.set_active_context() glu_info.set_active_context() ''' def flip(self): self.draw_mouse_cursor() if self.context: self.context.flip() def _get_vsync(self): if self.context: return self.context.get_vsync() return self._vsync vsync = property(_get_vsync) # overrides BaseWindow property def set_vsync(self, vsync): if pyglet.options['vsync'] is not None: vsync = pyglet.options['vsync'] self._vsync = vsync # _recreate depends on this if self.context: self.context.set_vsync(vsync) def dispatch_events(self): from pyglet import app app.platform_event_loop.dispatch_posted_events() self._allow_dispatch_event = True while self._event_queue: EventDispatcher.dispatch_event(self, *self._event_queue.pop(0)) e = EventRef() result = carbon.ReceiveNextEvent(0, c_void_p(), 0, True, byref(e)) while result == noErr: carbon.SendEventToEventTarget(e, self._event_dispatcher) carbon.ReleaseEvent(e) result = carbon.ReceiveNextEvent(0, c_void_p(), 0, True, byref(e)) self._allow_dispatch_event = False # Return value from ReceiveNextEvent can be ignored if not # noErr; we check here only to look for new bugs. # eventLoopQuitErr: the inner event loop was quit, see # http://lists.apple.com/archives/Carbon-dev/2006/Jun/msg00850.html # Can occur when mixing with other toolkits, e.g. Tk. # Fixes issue 180. if result not in (eventLoopTimedOutErr, eventLoopQuitErr): raise 'Error %d' % result def dispatch_pending_events(self): while self._event_queue: EventDispatcher.dispatch_event(self, *self._event_queue.pop(0)) def set_caption(self, caption): self._caption = caption s = create_cfstring(caption) carbon.SetWindowTitleWithCFString(self._window, s) carbon.CFRelease(s) def set_location(self, x, y): rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) rect.right += x - rect.left rect.bottom += y - rect.top rect.left = x rect.top = y carbon.SetWindowBounds(self._window, kWindowContentRgn, byref(rect)) def get_location(self): rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) return rect.left, rect.top def set_size(self, width, height): if self._fullscreen: raise WindowException('Cannot set size of fullscreen window.') rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) rect.right = rect.left + width rect.bottom = rect.top + height carbon.SetWindowBounds(self._window, kWindowContentRgn, byref(rect)) self._width = width self._height = height self.dispatch_event('on_resize', width, height) self.dispatch_event('on_expose') def get_size(self): if self._fullscreen: return self._width, self._height rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) return rect.right - rect.left, rect.bottom - rect.top def set_minimum_size(self, width, height): self._minimum_size = (width, height) minimum = HISize() minimum.width = width minimum.height = height if self._maximum_size: maximum = HISize() maximum.width, maximum.height = self._maximum_size maximum = byref(maximum) else: maximum = None carbon.SetWindowResizeLimits(self._window, byref(minimum), maximum) def set_maximum_size(self, width, height): self._maximum_size = (width, height) maximum = HISize() maximum.width = width maximum.height = height if self._minimum_size: minimum = HISize() minimum.width, minimum.height = self._minimum_size minimum = byref(minimum) else: minimum = None carbon.SetWindowResizeLimits(self._window, minimum, byref(maximum)) def activate(self): carbon.ActivateWindow(self._window, 1) # Also make the application the "front" application. TODO # maybe don't bring forward all of the application's windows? psn = ProcessSerialNumber() psn.highLongOfPSN = 0 psn.lowLongOfPSN = kCurrentProcess carbon.SetFrontProcess(byref(psn)) def set_visible(self, visible=True): self._visible = visible if visible: self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_show') self.dispatch_event('on_expose') carbon.ShowWindow(self._window) else: carbon.HideWindow(self._window) def minimize(self): self._mouse_in_window = False self.set_mouse_platform_visible() carbon.CollapseWindow(self._window, True) def maximize(self): # Maximum "safe" value, gets trimmed to screen size automatically. p = Point() p.v, p.h = 16000,16000 if not carbon.IsWindowInStandardState(self._window, byref(p), None): carbon.ZoomWindowIdeal(self._window, inZoomOut, byref(p)) def set_mouse_platform_visible(self, platform_visible=None): if platform_visible is None: platform_visible = self._mouse_visible and \ not self._mouse_exclusive and \ not self._mouse_cursor.drawable if not self._mouse_in_window: platform_visible = True if self._mouse_in_window and \ isinstance(self._mouse_cursor, CarbonMouseCursor): carbon.SetThemeCursor(self._mouse_cursor.theme) else: carbon.SetThemeCursor(kThemeArrowCursor) if self._mouse_platform_visible == platform_visible: return if platform_visible: carbon.ShowCursor() else: carbon.HideCursor() self._mouse_platform_visible = platform_visible def set_exclusive_mouse(self, exclusive=True): self._mouse_exclusive = exclusive if exclusive: # Move mouse to center of window rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) x = (rect.right + rect.left) / 2 y = (rect.bottom + rect.top) / 2 # Skip the next motion event, which would return a large delta. self._mouse_ignore_motion = True self.set_mouse_position(x, y, absolute=True) carbon.CGAssociateMouseAndMouseCursorPosition(False) else: carbon.CGAssociateMouseAndMouseCursorPosition(True) self.set_mouse_platform_visible() def set_mouse_position(self, x, y, absolute=False): point = CGPoint() if absolute: point.x = x point.y = y else: rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) point.x = x + rect.left point.y = rect.top + (rect.bottom - rect.top) - y carbon.CGWarpMouseCursorPosition(point) def set_exclusive_keyboard(self, exclusive=True): if exclusive: # Note: power switch can also be disabled, with # kUIOptionDisableSessionTerminate. That seems # a little extreme though. carbon.SetSystemUIMode(kUIModeAllHidden, (kUIOptionDisableAppleMenu | kUIOptionDisableProcessSwitch | kUIOptionDisableForceQuit | kUIOptionDisableHide)) else: carbon.SetSystemUIMode(kUIModeNormal, 0) def get_system_mouse_cursor(self, name): if name == self.CURSOR_DEFAULT: return DefaultMouseCursor() themes = { self.CURSOR_CROSSHAIR: kThemeCrossCursor, self.CURSOR_HAND: kThemePointingHandCursor, self.CURSOR_HELP: kThemeArrowCursor, self.CURSOR_NO: kThemeNotAllowedCursor, self.CURSOR_SIZE: kThemeArrowCursor, self.CURSOR_SIZE_UP: kThemeResizeUpCursor, self.CURSOR_SIZE_UP_RIGHT: kThemeArrowCursor, self.CURSOR_SIZE_RIGHT: kThemeResizeRightCursor, self.CURSOR_SIZE_DOWN_RIGHT: kThemeArrowCursor, self.CURSOR_SIZE_DOWN: kThemeResizeDownCursor, self.CURSOR_SIZE_DOWN_LEFT: kThemeArrowCursor, self.CURSOR_SIZE_LEFT: kThemeResizeLeftCursor, self.CURSOR_SIZE_UP_LEFT: kThemeArrowCursor, self.CURSOR_SIZE_UP_DOWN: kThemeResizeUpDownCursor, self.CURSOR_SIZE_LEFT_RIGHT: kThemeResizeLeftRightCursor, self.CURSOR_TEXT: kThemeIBeamCursor, self.CURSOR_WAIT: kThemeWatchCursor, self.CURSOR_WAIT_ARROW: kThemeWatchCursor, } if name not in themes: raise RuntimeError('Unknown cursor name "%s"' % name) return CarbonMouseCursor(themes[name]) def set_icon(self, *images): # Only use the biggest image image = images[0] size = image.width * image.height for img in images: if img.width * img.height > size: size = img.width * img.height image = img image = image.get_image_data() format = 'ARGB' pitch = -len(format) * image.width data = image.get_data(format, pitch) provider = carbon.CGDataProviderCreateWithData( None, data, len(data), None) colorspace = carbon.CGColorSpaceCreateDeviceRGB() cgi = carbon.CGImageCreate( image.width, image.height, 8, 32, -pitch, colorspace, kCGImageAlphaFirst, provider, None, True, kCGRenderingIntentDefault) carbon.SetApplicationDockTileImage(cgi) carbon.CGDataProviderRelease(provider) carbon.CGColorSpaceRelease(colorspace) # Non-public utilities def _update_drawable(self): if self.context: self.context.update_geometry() # Need a redraw self.dispatch_event('on_expose') def _update_track_region(self): if not self._fullscreen: carbon.GetWindowRegion(self._window, kWindowContentRgn, self._track_region) carbon.ChangeMouseTrackingRegion(self._track_ref, self._track_region, None) def _install_event_handlers(self): self._remove_event_handlers() if self._fullscreen: target = carbon.GetApplicationEventTarget() else: target = carbon.GetWindowEventTarget(self._window) carbon.InstallStandardEventHandler(target) self._carbon_event_handlers = [] self._carbon_event_handler_refs = [] for func_name in self._platform_event_names: if not hasattr(self, func_name): continue func = getattr(self, func_name) self._install_event_handler(func) def _install_event_handler(self, func): if self._fullscreen: target = carbon.GetApplicationEventTarget() else: target = carbon.GetWindowEventTarget(self._window) for event_class, event_kind in func._platform_event_data: # TODO: could just build up array of class/kind proc = EventHandlerProcPtr(func) self._carbon_event_handlers.append(proc) upp = carbon.NewEventHandlerUPP(proc) types = EventTypeSpec() types.eventClass = event_class types.eventKind = event_kind handler_ref = EventHandlerRef() carbon.InstallEventHandler( target, upp, 1, byref(types), c_void_p(), byref(handler_ref)) self._carbon_event_handler_refs.append(handler_ref) def _remove_event_handlers(self): for ref in self._carbon_event_handler_refs: carbon.RemoveEventHandler(ref) self._carbon_event_handler_refs = [] self._carbon_event_handlers = [] # Carbon event handlers @CarbonEventHandler(kEventClassTextInput, kEventTextInputUnicodeForKeyEvent) def _on_text_input(self, next_handler, ev, data): size = c_uint32() carbon.GetEventParameter(ev, kEventParamTextInputSendText, typeUTF8Text, c_void_p(), 0, byref(size), c_void_p()) text = create_string_buffer(size.value) carbon.GetEventParameter(ev, kEventParamTextInputSendText, typeUTF8Text, c_void_p(), size.value, c_void_p(), byref(text)) text = text.value.decode('utf8') raw_event = EventRef() carbon.GetEventParameter(ev, kEventParamTextInputSendKeyboardEvent, typeEventRef, c_void_p(), sizeof(raw_event), c_void_p(), byref(raw_event)) symbol, modifiers = self._get_symbol_and_modifiers(raw_event) motion_modifiers = modifiers & \ (key.MOD_COMMAND | key.MOD_CTRL | key.MOD_OPTION) if (symbol, motion_modifiers) in _motion_map: motion = _motion_map[symbol, motion_modifiers] if modifiers & key.MOD_SHIFT: self.dispatch_event('on_text_motion_select', motion) else: self.dispatch_event('on_text_motion', motion) elif ((unicodedata.category(text[0]) != 'Cc' or text == u'\r') and not (modifiers & key.MOD_COMMAND)): self.dispatch_event('on_text', text) return noErr @CarbonEventHandler(kEventClassKeyboard, kEventRawKeyUp) def _on_key_up(self, next_handler, ev, data): symbol, modifiers = self._get_symbol_and_modifiers(ev) if symbol: self.dispatch_event('on_key_release', symbol, modifiers) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassKeyboard, kEventRawKeyDown) def _on_key_down(self, next_handler, ev, data): symbol, modifiers = self._get_symbol_and_modifiers(ev) if symbol: self.dispatch_event('on_key_press', symbol, modifiers) carbon.CallNextEventHandler(next_handler, ev) return noErr @staticmethod def _get_symbol_and_modifiers(ev): # The unicode char help processing virtual keycodes (see issue 405) wchar = c_wchar() carbon.GetEventParameter(ev, kEventParamKeyUnicodes, typeUnicodeText, c_void_p(), sizeof(wchar), c_void_p(), byref(wchar)) try: wchar = str((wchar.value)).upper() except UnicodeEncodeError: # (this fix for issue 405 caused a bug itself (see comments 6-7); # this try/except fixes it) wchar = None # If the unicode char is within charmap keys (ascii value), then we use # the corresponding symbol. if wchar in charmap.keys(): symbol = charmap[wchar] else: sym = c_uint32() carbon.GetEventParameter(ev, kEventParamKeyCode, typeUInt32, c_void_p(), sizeof(sym), c_void_p(), byref(sym)) symbol = keymap.get(sym.value, None) if symbol is None: symbol = key.user_key(sym.value) modifiers = c_uint32() carbon.GetEventParameter(ev, kEventParamKeyModifiers, typeUInt32, c_void_p(), sizeof(modifiers), c_void_p(), byref(modifiers)) return (symbol, CarbonWindow._map_modifiers(modifiers.value)) @staticmethod def _map_modifiers(modifiers): mapped_modifiers = 0 if modifiers & (shiftKey | rightShiftKey): mapped_modifiers |= key.MOD_SHIFT if modifiers & (controlKey | rightControlKey): mapped_modifiers |= key.MOD_CTRL if modifiers & (optionKey | rightOptionKey): mapped_modifiers |= key.MOD_OPTION if modifiers & alphaLock: mapped_modifiers |= key.MOD_CAPSLOCK if modifiers & cmdKey: mapped_modifiers |= key.MOD_COMMAND return mapped_modifiers @CarbonEventHandler(kEventClassKeyboard, kEventRawKeyModifiersChanged) def _on_modifiers_changed(self, next_handler, ev, data): modifiers = c_uint32() carbon.GetEventParameter(ev, kEventParamKeyModifiers, typeUInt32, c_void_p(), sizeof(modifiers), c_void_p(), byref(modifiers)) modifiers = modifiers.value deltas = modifiers ^ self._current_modifiers for mask, k in [ (controlKey, key.LCTRL), (shiftKey, key.LSHIFT), (cmdKey, key.LCOMMAND), (optionKey, key.LOPTION), (rightShiftKey, key.RSHIFT), (rightOptionKey, key.ROPTION), (rightControlKey, key.RCTRL), (alphaLock, key.CAPSLOCK), (numLock, key.NUMLOCK)]: if deltas & mask: if modifiers & mask: self.dispatch_event('on_key_press', k, self._mapped_modifiers) else: self.dispatch_event('on_key_release', k, self._mapped_modifiers) carbon.CallNextEventHandler(next_handler, ev) self._mapped_modifiers = self._map_modifiers(modifiers) self._current_modifiers = modifiers return noErr def _get_mouse_position(self, ev): position = HIPoint() carbon.GetEventParameter(ev, kEventParamMouseLocation, typeHIPoint, c_void_p(), sizeof(position), c_void_p(), byref(position)) bounds = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(bounds)) return (int(position.x - bounds.left - self._view_x), int(position.y - bounds.top - self._view_y)) def _get_mouse_buttons_changed(self): button_state = self._get_mouse_buttons() change = self._mouse_button_state ^ button_state self._mouse_button_state = button_state return change @staticmethod def _get_mouse_buttons(): buttons = carbon.GetCurrentEventButtonState() button_state = 0 if buttons & 0x1: button_state |= mouse.LEFT if buttons & 0x2: button_state |= mouse.RIGHT if buttons & 0x4: button_state |= mouse.MIDDLE return button_state @staticmethod def _get_modifiers(ev): modifiers = c_uint32() carbon.GetEventParameter(ev, kEventParamKeyModifiers, typeUInt32, c_void_p(), sizeof(modifiers), c_void_p(), byref(modifiers)) return CarbonWindow._map_modifiers(modifiers.value) def _get_mouse_in_content(self, ev, x, y): if self._fullscreen: return 0 <= x < self._width and 0 <= y < self._height else: position = Point() carbon.GetEventParameter(ev, kEventParamMouseLocation, typeQDPoint, c_void_p(), sizeof(position), c_void_p(), byref(position)) return carbon.FindWindow(position, None) == inContent @CarbonEventHandler(kEventClassMouse, kEventMouseDown) def _on_mouse_down(self, next_handler, ev, data): x, y = self._get_mouse_position(ev) if self._get_mouse_in_content(ev, x, y): button = self._get_mouse_buttons_changed() modifiers = self._get_modifiers(ev) if button is not None: y = self.height - y self.dispatch_event('on_mouse_press', x, y, button, modifiers) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseUp) def _on_mouse_up(self, next_handler, ev, data): # Always report mouse up, even out of content area, because it's # probably after a drag gesture. button = self._get_mouse_buttons_changed() modifiers = self._get_modifiers(ev) if button is not None: x, y = self._get_mouse_position(ev) y = self.height - y self.dispatch_event('on_mouse_release', x, y, button, modifiers) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseMoved) def _on_mouse_moved(self, next_handler, ev, data): x, y = self._get_mouse_position(ev) if (self._get_mouse_in_content(ev, x, y) and not self._mouse_ignore_motion): y = self.height - y self._mouse_x = x self._mouse_y = y delta = HIPoint() carbon.GetEventParameter(ev, kEventParamMouseDelta, typeHIPoint, c_void_p(), sizeof(delta), c_void_p(), byref(delta)) # Motion event self.dispatch_event('on_mouse_motion', x, y, delta.x, -delta.y) elif self._mouse_ignore_motion: self._mouse_ignore_motion = False carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseDragged) def _on_mouse_dragged(self, next_handler, ev, data): button = self._get_mouse_buttons() modifiers = self._get_modifiers(ev) if button is not None: x, y = self._get_mouse_position(ev) y = self.height - y self._mouse_x = x self._mouse_y = y delta = HIPoint() carbon.GetEventParameter(ev, kEventParamMouseDelta, typeHIPoint, c_void_p(), sizeof(delta), c_void_p(), byref(delta)) # Drag event self.dispatch_event('on_mouse_drag', x, y, delta.x, -delta.y, button, modifiers) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseEntered) def _on_mouse_entered(self, next_handler, ev, data): x, y = self._get_mouse_position(ev) y = self.height - y self._mouse_x = x self._mouse_y = y self._mouse_in_window = True self.set_mouse_platform_visible() self.dispatch_event('on_mouse_enter', x, y) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseExited) def _on_mouse_exited(self, next_handler, ev, data): x, y = self._get_mouse_position(ev) y = self.height - y self._mouse_in_window = False self.set_mouse_platform_visible() self.dispatch_event('on_mouse_leave', x, y) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseWheelMoved) def _on_mouse_wheel_moved(self, next_handler, ev, data): x, y = self._get_mouse_position(ev) y = self.height - y axis = EventMouseWheelAxis() carbon.GetEventParameter(ev, kEventParamMouseWheelAxis, typeMouseWheelAxis, c_void_p(), sizeof(axis), c_void_p(), byref(axis)) delta = c_long() carbon.GetEventParameter(ev, kEventParamMouseWheelDelta, typeSInt32, c_void_p(), sizeof(delta), c_void_p(), byref(delta)) if axis.value == kEventMouseWheelAxisX: self.dispatch_event('on_mouse_scroll', x, y, delta.value, 0) else: self.dispatch_event('on_mouse_scroll', x, y, 0, delta.value) # _Don't_ call the next handler, which is application, as this then # calls our window handler again. #carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowClose) def _on_window_close(self, next_handler, ev, data): self.dispatch_event('on_close') # Presumably the next event handler is the one that closes # the window; don't do that here. #carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowResizeStarted) def _on_window_resize_started(self, next_handler, ev, data): from pyglet import app if app.event_loop is not None: app.event_loop.enter_blocking() carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowResizeCompleted) def _on_window_resize_completed(self, next_handler, ev, data): from pyglet import app if app.event_loop is not None: app.event_loop.exit_blocking() rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) width = rect.right - rect.left height = rect.bottom - rect.top self.switch_to() self.dispatch_event('on_resize', width, height) self.dispatch_event('on_expose') carbon.CallNextEventHandler(next_handler, ev) return noErr _dragging = False @CarbonEventHandler(kEventClassWindow, kEventWindowDragStarted) def _on_window_drag_started(self, next_handler, ev, data): self._dragging = True from pyglet import app if app.event_loop is not None: app.event_loop.enter_blocking() carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowDragCompleted) def _on_window_drag_completed(self, next_handler, ev, data): self._dragging = False from pyglet import app if app.event_loop is not None: app.event_loop.exit_blocking() rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) self.dispatch_event('on_move', rect.left, rect.top) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowBoundsChanging) def _on_window_bounds_changing(self, next_handler, ev, data): carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowBoundsChanged) def _on_window_bounds_change(self, next_handler, ev, data): self._update_track_region() rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) width = rect.right - rect.left height = rect.bottom - rect.top if width != self._width or height != self._height: self._update_drawable() self.switch_to() self.dispatch_event('on_resize', width, height) from pyglet import app if app.event_loop is not None: app.event_loop.enter_blocking() self._width = width self._height = height else: self.dispatch_event('on_move', rect.left, rect.top) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowZoomed) def _on_window_zoomed(self, next_handler, ev, data): rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) width = rect.right - rect.left height = rect.bottom - rect.top self.dispatch_event('on_move', rect.left, rect.top) self.dispatch_event('on_resize', width, height) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowActivated) def _on_window_activated(self, next_handler, ev, data): self.dispatch_event('on_activate') carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowDeactivated) def _on_window_deactivated(self, next_handler, ev, data): self.dispatch_event('on_deactivate') carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowShown) @CarbonEventHandler(kEventClassWindow, kEventWindowExpanded) def _on_window_shown(self, next_handler, ev, data): self._update_drawable() # XXX not needed here according to apple docs self.dispatch_event('on_show') carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowHidden) @CarbonEventHandler(kEventClassWindow, kEventWindowCollapsed) def _on_window_hidden(self, next_handler, ev, data): self.dispatch_event('on_hide') carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowDrawContent) def _on_window_draw_content(self, next_handler, ev, data): self.dispatch_event('on_expose') carbon.CallNextEventHandler(next_handler, ev) return noErr CarbonWindow.register_event_type('on_recreate_immediate')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- __docformat__ = 'restructuredtext' __version__ = '$Id$' from ctypes import * import unicodedata import warnings import pyglet from pyglet.window import WindowException, NoSuchDisplayException, \ MouseCursorException, MouseCursor, \ DefaultMouseCursor, ImageMouseCursor, BaseWindow, _PlatformEventHandler, \ _ViewEventHandler from pyglet.window import key from pyglet.window import mouse from pyglet.event import EventDispatcher from pyglet.canvas.xlib import XlibCanvas from pyglet.libs.x11 import xlib from pyglet.libs.x11 import cursorfont from pyglet.compat import asbytes try: from pyglet.libs.x11 import xsync _have_xsync = True except: _have_xsync = False class mwmhints_t(Structure): _fields_ = [ ('flags', c_uint32), ('functions', c_uint32), ('decorations', c_uint32), ('input_mode', c_int32), ('status', c_uint32) ] XA_CARDINAL = 6 # Xatom.h:14 # Do we have the November 2000 UTF8 extension? _have_utf8 = hasattr(xlib._lib, 'Xutf8TextListToTextProperty') # symbol,ctrl -> motion mapping _motion_map = { (key.UP, False): key.MOTION_UP, (key.RIGHT, False): key.MOTION_RIGHT, (key.DOWN, False): key.MOTION_DOWN, (key.LEFT, False): key.MOTION_LEFT, (key.RIGHT, True): key.MOTION_NEXT_WORD, (key.LEFT, True): key.MOTION_PREVIOUS_WORD, (key.HOME, False): key.MOTION_BEGINNING_OF_LINE, (key.END, False): key.MOTION_END_OF_LINE, (key.PAGEUP, False): key.MOTION_PREVIOUS_PAGE, (key.PAGEDOWN, False): key.MOTION_NEXT_PAGE, (key.HOME, True): key.MOTION_BEGINNING_OF_FILE, (key.END, True): key.MOTION_END_OF_FILE, (key.BACKSPACE, False): key.MOTION_BACKSPACE, (key.DELETE, False): key.MOTION_DELETE, } class XlibException(WindowException): '''An X11-specific exception. This exception is probably a programming error in pyglet.''' pass class XlibMouseCursor(MouseCursor): drawable = False def __init__(self, cursor): self.cursor = cursor # Platform event data is single item, so use platform event handler directly. XlibEventHandler = _PlatformEventHandler ViewEventHandler = _ViewEventHandler class XlibWindow(BaseWindow): _x_display = None # X display connection _x_screen_id = None # X screen index _x_ic = None # X input context _window = None # Xlib window handle _minimum_size = None _maximum_size = None _override_redirect = False _x = 0 _y = 0 # Last known window position _width = 0 _height = 0 # Last known window size _mouse_exclusive_client = None # x,y of "real" mouse during exclusive _mouse_buttons = [False] * 6 # State of each xlib button _keyboard_exclusive = False _active = True _applied_mouse_exclusive = False _applied_keyboard_exclusive = False _mapped = False _lost_context = False _lost_context_state = False _enable_xsync = False _current_sync_value = None _current_sync_valid = False _needs_resize = False # True when resize event has been received but not # dispatched _default_event_mask = (0x1ffffff & ~xlib.PointerMotionHintMask & ~xlib.ResizeRedirectMask & ~xlib.SubstructureNotifyMask) def __init__(self, *args, **kwargs): # Bind event handlers self._event_handlers = {} self._view_event_handlers = {} for name in self._platform_event_names: if not hasattr(self, name): continue func = getattr(self, name) for message in func._platform_event_data: if hasattr(func, '_view'): self._view_event_handlers[message] = func else: self._event_handlers[message] = func super(XlibWindow, self).__init__(*args, **kwargs) def _recreate(self, changes): # If flipping to/from fullscreen, need to recreate the window. (This # is the case with both override_redirect method and # _NET_WM_STATE_FULLSCREEN). # # A possible improvement could be to just hide the top window, # destroy the GLX window, and reshow it again when leaving fullscreen. # This would prevent the floating window from being moved by the # WM. if ('fullscreen' in changes or 'resizable' in changes): # clear out the GLX context self.context.detach() xlib.XDestroyWindow(self._x_display, self._window) del self.display._window_map[self._window] del self.display._window_map[self._view] self._window = None self._mapped = False # TODO: detect state loss only by examining context share. if 'context' in changes: self._lost_context = True self._lost_context_state = True self._create() def _create(self): # Unmap existing window if necessary while we fiddle with it. if self._window and self._mapped: self._unmap() self._x_display = self.display._display self._x_screen_id = self.display.x_screen # Create X window if not already existing. if not self._window: root = xlib.XRootWindow(self._x_display, self._x_screen_id) visual_info = self.config.get_visual_info() visual = visual_info.visual visual_id = xlib.XVisualIDFromVisual(visual) default_visual = xlib.XDefaultVisual( self._x_display, self._x_screen_id) default_visual_id = xlib.XVisualIDFromVisual(default_visual) window_attributes = xlib.XSetWindowAttributes() if visual_id != default_visual_id: window_attributes.colormap = xlib.XCreateColormap( self._x_display, root, visual, xlib.AllocNone) else: window_attributes.colormap = xlib.XDefaultColormap( self._x_display, self._x_screen_id) window_attributes.bit_gravity = xlib.StaticGravity # Issue 287: Compiz on Intel/Mesa doesn't draw window decoration # unless CWBackPixel is given in mask. Should have # no effect on other systems, so it's set # unconditionally. mask = xlib.CWColormap | xlib.CWBitGravity | xlib.CWBackPixel if self._fullscreen: width, height = self.screen.width, self.screen.height self._view_x = (width - self._width) // 2 self._view_y = (height - self._height) // 2 else: width, height = self._width, self._height self._view_x = self._view_y = 0 self._window = xlib.XCreateWindow(self._x_display, root, 0, 0, width, height, 0, visual_info.depth, xlib.InputOutput, visual, mask, byref(window_attributes)) self._view = xlib.XCreateWindow(self._x_display, self._window, self._view_x, self._view_y, self._width, self._height, 0, visual_info.depth, xlib.InputOutput, visual, mask, byref(window_attributes)); xlib.XMapWindow(self._x_display, self._view) xlib.XSelectInput( self._x_display, self._view, self._default_event_mask) self.display._window_map[self._window] = \ self.dispatch_platform_event self.display._window_map[self._view] = \ self.dispatch_platform_event_view self.canvas = XlibCanvas(self.display, self._view) self.context.attach(self.canvas) self.context.set_vsync(self._vsync) # XXX ? # Setting null background pixmap disables drawing the background, # preventing flicker while resizing (in theory). # # Issue 287: Compiz on Intel/Mesa doesn't draw window decoration if # this is called. As it doesn't seem to have any # effect anyway, it's just commented out. #xlib.XSetWindowBackgroundPixmap(self._x_display, self._window, 0) self._enable_xsync = (pyglet.options['xsync'] and self.display._enable_xsync and self.config.double_buffer) # Set supported protocols protocols = [] protocols.append(xlib.XInternAtom(self._x_display, asbytes('WM_DELETE_WINDOW'), False)) if self._enable_xsync: protocols.append(xlib.XInternAtom(self._x_display, asbytes('_NET_WM_SYNC_REQUEST'), False)) protocols = (c_ulong * len(protocols))(*protocols) xlib.XSetWMProtocols(self._x_display, self._window, protocols, len(protocols)) # Create window resize sync counter if self._enable_xsync: value = xsync.XSyncValue() self._sync_counter = xlib.XID( xsync.XSyncCreateCounter(self._x_display, value)) atom = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_SYNC_REQUEST_COUNTER'), False) ptr = pointer(self._sync_counter) xlib.XChangeProperty(self._x_display, self._window, atom, XA_CARDINAL, 32, xlib.PropModeReplace, cast(ptr, POINTER(c_ubyte)), 1) # Set window attributes attributes = xlib.XSetWindowAttributes() attributes_mask = 0 self._override_redirect = False if self._fullscreen: if pyglet.options['xlib_fullscreen_override_redirect']: # Try not to use this any more, it causes problems; disabled # by default in favour of _NET_WM_STATE_FULLSCREEN. attributes.override_redirect = self._fullscreen attributes_mask |= xlib.CWOverrideRedirect self._override_redirect = True else: self._set_wm_state('_NET_WM_STATE_FULLSCREEN') if self._fullscreen: xlib.XMoveResizeWindow(self._x_display, self._window, self.screen.x, self.screen.y, self.screen.width, self.screen.height) else: xlib.XResizeWindow(self._x_display, self._window, self._width, self._height) xlib.XChangeWindowAttributes(self._x_display, self._window, attributes_mask, byref(attributes)) # Set style styles = { self.WINDOW_STYLE_DEFAULT: '_NET_WM_WINDOW_TYPE_NORMAL', self.WINDOW_STYLE_DIALOG: '_NET_WM_WINDOW_TYPE_DIALOG', self.WINDOW_STYLE_TOOL: '_NET_WM_WINDOW_TYPE_UTILITY', } if self._style in styles: self._set_atoms_property('_NET_WM_WINDOW_TYPE', (styles[self._style],)) elif self._style == self.WINDOW_STYLE_BORDERLESS: MWM_HINTS_DECORATIONS = 1 << 1 PROP_MWM_HINTS_ELEMENTS = 5 mwmhints = mwmhints_t() mwmhints.flags = MWM_HINTS_DECORATIONS mwmhints.decorations = 0 name = xlib.XInternAtom(self._x_display, asbytes('_MOTIF_WM_HINTS'), False) xlib.XChangeProperty(self._x_display, self._window, name, name, 32, xlib.PropModeReplace, cast(pointer(mwmhints), POINTER(c_ubyte)), PROP_MWM_HINTS_ELEMENTS) # Set resizeable if not self._resizable and not self._fullscreen: self.set_minimum_size(self._width, self._height) self.set_maximum_size(self._width, self._height) # Set caption self.set_caption(self._caption) # Create input context. A good but very outdated reference for this # is http://www.sbin.org/doc/Xlib/chapt_11.html if _have_utf8 and not self._x_ic: if not self.display._x_im: xlib.XSetLocaleModifiers(asbytes('@im=none')) self.display._x_im = \ xlib.XOpenIM(self._x_display, None, None, None) xlib.XFlush(self._x_display); # Need to set argtypes on this function because it's vararg, # and ctypes guesses wrong. xlib.XCreateIC.argtypes = [xlib.XIM, c_char_p, c_int, c_char_p, xlib.Window, c_char_p, xlib.Window, c_void_p] self._x_ic = xlib.XCreateIC(self.display._x_im, asbytes('inputStyle'), xlib.XIMPreeditNothing|xlib.XIMStatusNothing, asbytes('clientWindow'), self._window, asbytes('focusWindow'), self._window, None) filter_events = c_ulong() xlib.XGetICValues(self._x_ic, 'filterEvents', byref(filter_events), None) self._default_event_mask |= filter_events.value xlib.XSetICFocus(self._x_ic) self.switch_to() if self._visible: self.set_visible(True) self.set_mouse_platform_visible() self._applied_mouse_exclusive = None self._update_exclusivity() def _map(self): if self._mapped: return # Map the window, wait for map event before continuing. xlib.XSelectInput( self._x_display, self._window, xlib.StructureNotifyMask) xlib.XMapRaised(self._x_display, self._window) e = xlib.XEvent() while True: xlib.XNextEvent(self._x_display, e) if e.type == xlib.ConfigureNotify: self._width = e.xconfigure.width self._height = e.xconfigure.height elif e.type == xlib.MapNotify: break xlib.XSelectInput( self._x_display, self._window, self._default_event_mask) self._mapped = True if self._override_redirect: # Possibly an override_redirect issue. self.activate() self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_show') self.dispatch_event('on_expose') def _unmap(self): if not self._mapped: return xlib.XSelectInput( self._x_display, self._window, xlib.StructureNotifyMask) xlib.XUnmapWindow(self._x_display, self._window) e = xlib.XEvent() while True: xlib.XNextEvent(self._x_display, e) if e.type == xlib.UnmapNotify: break xlib.XSelectInput( self._x_display, self._window, self._default_event_mask) self._mapped = False def _get_root(self): attributes = xlib.XWindowAttributes() xlib.XGetWindowAttributes(self._x_display, self._window, byref(attributes)) return attributes.root def close(self): if not self._window: return self.context.destroy() self._unmap() if self._window: xlib.XDestroyWindow(self._x_display, self._window) del self.display._window_map[self._window] self._window = None if _have_utf8: xlib.XDestroyIC(self._x_ic) self._x_ic = None super(XlibWindow, self).close() def switch_to(self): if self.context: self.context.set_current() def flip(self): self.draw_mouse_cursor() # TODO canvas.flip? if self.context: self.context.flip() self._sync_resize() def set_vsync(self, vsync): if pyglet.options['vsync'] is not None: vsync = pyglet.options['vsync'] self._vsync = vsync self.context.set_vsync(vsync) def set_caption(self, caption): if caption is None: caption = '' self._caption = caption self._set_text_property('WM_NAME', caption, allow_utf8=False) self._set_text_property('WM_ICON_NAME', caption, allow_utf8=False) self._set_text_property('_NET_WM_NAME', caption) self._set_text_property('_NET_WM_ICON_NAME', caption) def get_caption(self): return self._caption def set_size(self, width, height): if self._fullscreen: raise WindowException('Cannot set size of fullscreen window.') self._width = width self._height = height if not self._resizable: self.set_minimum_size(width, height) self.set_maximum_size(width, height) xlib.XResizeWindow(self._x_display, self._window, width, height) self._update_view_size() self.dispatch_event('on_resize', width, height) def _update_view_size(self): xlib.XResizeWindow(self._x_display, self._view, self._width, self._height) def get_size(self): # XGetGeometry and XWindowAttributes seem to always return the # original size of the window, which is wrong after the user # has resized it. # XXX this is probably fixed now, with fix of resize. return self._width, self._height def set_location(self, x, y): # Assume the window manager has reparented our top-level window # only once, in which case attributes.x/y give the offset from # the frame to the content window. Better solution would be # to use _NET_FRAME_EXTENTS, where supported. attributes = xlib.XWindowAttributes() xlib.XGetWindowAttributes(self._x_display, self._window, byref(attributes)) # XXX at least under KDE's WM these attrs are both 0 x -= attributes.x y -= attributes.y xlib.XMoveWindow(self._x_display, self._window, x, y) def get_location(self): child = xlib.Window() x = c_int() y = c_int() xlib.XTranslateCoordinates(self._x_display, self._window, self._get_root(), 0, 0, byref(x), byref(y), byref(child)) return x.value, y.value def activate(self): xlib.XSetInputFocus(self._x_display, self._window, xlib.RevertToParent, xlib.CurrentTime) def set_visible(self, visible=True): if visible: self._map() else: self._unmap() self._visible = visible def set_minimum_size(self, width, height): self._minimum_size = width, height self._set_wm_normal_hints() def set_maximum_size(self, width, height): self._maximum_size = width, height self._set_wm_normal_hints() def minimize(self): xlib.XIconifyWindow(self._x_display, self._window, self._x_screen_id) def maximize(self): self._set_wm_state('_NET_WM_STATE_MAXIMIZED_HORZ', '_NET_WM_STATE_MAXIMIZED_VERT') def set_mouse_platform_visible(self, platform_visible=None): if platform_visible is None: platform_visible = self._mouse_visible and \ not self._mouse_cursor.drawable if not platform_visible: # Hide pointer by creating an empty cursor black = xlib.XBlackPixel(self._x_display, self._x_screen_id) black = xlib.XColor() bmp = xlib.XCreateBitmapFromData(self._x_display, self._window, c_buffer(8), 8, 8) cursor = xlib.XCreatePixmapCursor(self._x_display, bmp, bmp, black, black, 0, 0) xlib.XDefineCursor(self._x_display, self._window, cursor) xlib.XFreeCursor(self._x_display, cursor) xlib.XFreePixmap(self._x_display, bmp) else: # Restore cursor if isinstance(self._mouse_cursor, XlibMouseCursor): xlib.XDefineCursor(self._x_display, self._window, self._mouse_cursor.cursor) else: xlib.XUndefineCursor(self._x_display, self._window) def set_mouse_position(self, x, y): xlib.XWarpPointer(self._x_display, 0, # src window self._window, # dst window 0, 0, # src x, y 0, 0, # src w, h x, self._height - y, ) def _update_exclusivity(self): mouse_exclusive = self._active and self._mouse_exclusive keyboard_exclusive = self._active and self._keyboard_exclusive if mouse_exclusive != self._applied_mouse_exclusive: if mouse_exclusive: self.set_mouse_platform_visible(False) # Restrict to client area xlib.XGrabPointer(self._x_display, self._window, True, 0, xlib.GrabModeAsync, xlib.GrabModeAsync, self._window, 0, xlib.CurrentTime) # Move pointer to center of window x = self._width // 2 y = self._height // 2 self._mouse_exclusive_client = x, y self.set_mouse_position(x, y) elif self._fullscreen and not self.screen._xinerama: # Restrict to fullscreen area (prevent viewport scrolling) self.set_mouse_position(0, 0) r = xlib.XGrabPointer(self._x_display, self._view, True, 0, xlib.GrabModeAsync, xlib.GrabModeAsync, self._view, 0, xlib.CurrentTime) if r: # Failed to grab, try again later self._applied_mouse_exclusive = None return self.set_mouse_platform_visible() else: # Unclip xlib.XUngrabPointer(self._x_display, xlib.CurrentTime) self.set_mouse_platform_visible() self._applied_mouse_exclusive = mouse_exclusive if keyboard_exclusive != self._applied_keyboard_exclusive: if keyboard_exclusive: xlib.XGrabKeyboard(self._x_display, self._window, False, xlib.GrabModeAsync, xlib.GrabModeAsync, xlib.CurrentTime) else: xlib.XUngrabKeyboard(self._x_display, xlib.CurrentTime) self._applied_keyboard_exclusive = keyboard_exclusive def set_exclusive_mouse(self, exclusive=True): if exclusive == self._mouse_exclusive: return self._mouse_exclusive = exclusive self._update_exclusivity() def set_exclusive_keyboard(self, exclusive=True): if exclusive == self._keyboard_exclusive: return self._keyboard_exclusive = exclusive self._update_exclusivity() def get_system_mouse_cursor(self, name): if name == self.CURSOR_DEFAULT: return DefaultMouseCursor() # NQR means default shape is not pretty... surely there is another # cursor font? cursor_shapes = { self.CURSOR_CROSSHAIR: cursorfont.XC_crosshair, self.CURSOR_HAND: cursorfont.XC_hand2, self.CURSOR_HELP: cursorfont.XC_question_arrow, # NQR self.CURSOR_NO: cursorfont.XC_pirate, # NQR self.CURSOR_SIZE: cursorfont.XC_fleur, self.CURSOR_SIZE_UP: cursorfont.XC_top_side, self.CURSOR_SIZE_UP_RIGHT: cursorfont.XC_top_right_corner, self.CURSOR_SIZE_RIGHT: cursorfont.XC_right_side, self.CURSOR_SIZE_DOWN_RIGHT: cursorfont.XC_bottom_right_corner, self.CURSOR_SIZE_DOWN: cursorfont.XC_bottom_side, self.CURSOR_SIZE_DOWN_LEFT: cursorfont.XC_bottom_left_corner, self.CURSOR_SIZE_LEFT: cursorfont.XC_left_side, self.CURSOR_SIZE_UP_LEFT: cursorfont.XC_top_left_corner, self.CURSOR_SIZE_UP_DOWN: cursorfont.XC_sb_v_double_arrow, self.CURSOR_SIZE_LEFT_RIGHT: cursorfont.XC_sb_h_double_arrow, self.CURSOR_TEXT: cursorfont.XC_xterm, self.CURSOR_WAIT: cursorfont.XC_watch, self.CURSOR_WAIT_ARROW: cursorfont.XC_watch, # NQR } if name not in cursor_shapes: raise MouseCursorException('Unknown cursor name "%s"' % name) cursor = xlib.XCreateFontCursor(self._x_display, cursor_shapes[name]) return XlibMouseCursor(cursor) def set_icon(self, *images): # Careful! XChangeProperty takes an array of long when data type # is 32-bit (but long can be 64 bit!), so pad high bytes of format if # necessary. import sys format = { ('little', 4): 'BGRA', ('little', 8): 'BGRAAAAA', ('big', 4): 'ARGB', ('big', 8): 'AAAAARGB' }[(sys.byteorder, sizeof(c_ulong))] data = asbytes('') for image in images: image = image.get_image_data() pitch = -(image.width * len(format)) s = c_buffer(sizeof(c_ulong) * 2) memmove(s, cast((c_ulong * 2)(image.width, image.height), POINTER(c_ubyte)), len(s)) data += s.raw + image.get_data(format, pitch) buffer = (c_ubyte * len(data))() memmove(buffer, data, len(data)) atom = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_ICON'), False) xlib.XChangeProperty(self._x_display, self._window, atom, XA_CARDINAL, 32, xlib.PropModeReplace, buffer, len(data)//sizeof(c_ulong)) # Private utility def _set_wm_normal_hints(self): hints = xlib.XAllocSizeHints().contents if self._minimum_size: hints.flags |= xlib.PMinSize hints.min_width, hints.min_height = self._minimum_size if self._maximum_size: hints.flags |= xlib.PMaxSize hints.max_width, hints.max_height = self._maximum_size xlib.XSetWMNormalHints(self._x_display, self._window, byref(hints)) def _set_text_property(self, name, value, allow_utf8=True): atom = xlib.XInternAtom(self._x_display, asbytes(name), False) if not atom: raise XlibException('Undefined atom "%s"' % name) assert type(value) in (str, unicode) property = xlib.XTextProperty() if _have_utf8 and allow_utf8: buf = create_string_buffer(value.encode('utf8')) result = xlib.Xutf8TextListToTextProperty(self._x_display, cast(pointer(buf), c_char_p), 1, xlib.XUTF8StringStyle, byref(property)) if result < 0: raise XlibException('Could not create UTF8 text property') else: buf = create_string_buffer(value.encode('ascii', 'ignore')) result = xlib.XStringListToTextProperty( cast(pointer(buf), c_char_p), 1, byref(property)) if result < 0: raise XlibException('Could not create text property') xlib.XSetTextProperty(self._x_display, self._window, byref(property), atom) # XXX <rj> Xlib doesn't like us freeing this #xlib.XFree(property.value) def _set_atoms_property(self, name, values, mode=xlib.PropModeReplace): name_atom = xlib.XInternAtom(self._x_display, asbytes(name), False) atoms = [] for value in values: atoms.append(xlib.XInternAtom(self._x_display, asbytes(value), False)) atom_type = xlib.XInternAtom(self._x_display, asbytes('ATOM'), False) if len(atoms): atoms_ar = (xlib.Atom * len(atoms))(*atoms) xlib.XChangeProperty(self._x_display, self._window, name_atom, atom_type, 32, mode, cast(pointer(atoms_ar), POINTER(c_ubyte)), len(atoms)) else: xlib.XDeleteProperty(self._x_display, self._window, net_wm_state) def _set_wm_state(self, *states): # Set property net_wm_state = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_STATE'), False) atoms = [] for state in states: atoms.append(xlib.XInternAtom(self._x_display, asbytes(state), False)) atom_type = xlib.XInternAtom(self._x_display, asbytes('ATOM'), False) if len(atoms): atoms_ar = (xlib.Atom * len(atoms))(*atoms) xlib.XChangeProperty(self._x_display, self._window, net_wm_state, atom_type, 32, xlib.PropModePrepend, cast(pointer(atoms_ar), POINTER(c_ubyte)), len(atoms)) else: xlib.XDeleteProperty(self._x_display, self._window, net_wm_state) # Nudge the WM e = xlib.XEvent() e.xclient.type = xlib.ClientMessage e.xclient.message_type = net_wm_state e.xclient.display = cast(self._x_display, POINTER(xlib.Display)) e.xclient.window = self._window e.xclient.format = 32 e.xclient.data.l[0] = xlib.PropModePrepend for i, atom in enumerate(atoms): e.xclient.data.l[i + 1] = atom xlib.XSendEvent(self._x_display, self._get_root(), False, xlib.SubstructureRedirectMask, byref(e)) # Event handling def dispatch_events(self): self.dispatch_pending_events() self._allow_dispatch_event = True e = xlib.XEvent() # Cache these in case window is closed from an event handler _x_display = self._x_display _window = self._window _view = self._view # Check for the events specific to this window while xlib.XCheckWindowEvent(_x_display, _window, 0x1ffffff, byref(e)): # Key events are filtered by the xlib window event # handler so they get a shot at the prefiltered event. if e.xany.type not in (xlib.KeyPress, xlib.KeyRelease): if xlib.XFilterEvent(e, 0): continue self.dispatch_platform_event(e) # Check for the events specific to this view while xlib.XCheckWindowEvent(_x_display, _view, 0x1ffffff, byref(e)): # Key events are filtered by the xlib window event # handler so they get a shot at the prefiltered event. if e.xany.type not in (xlib.KeyPress, xlib.KeyRelease): if xlib.XFilterEvent(e, 0): continue self.dispatch_platform_event_view(e) # Generic events for this window (the window close event). while xlib.XCheckTypedWindowEvent(_x_display, _window, xlib.ClientMessage, byref(e)): self.dispatch_platform_event(e) if self._needs_resize: self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_expose') self._needs_resize = False self._allow_dispatch_event = False def dispatch_pending_events(self): while self._event_queue: EventDispatcher.dispatch_event(self, *self._event_queue.pop(0)) # Dispatch any context-related events if self._lost_context: self._lost_context = False EventDispatcher.dispatch_event(self, 'on_context_lost') if self._lost_context_state: self._lost_context_state = False EventDispatcher.dispatch_event(self, 'on_context_state_lost') def dispatch_platform_event(self, e): if self._applied_mouse_exclusive is None: self._update_exclusivity() event_handler = self._event_handlers.get(e.type) if event_handler: event_handler(e) def dispatch_platform_event_view(self, e): event_handler = self._view_event_handlers.get(e.type) if event_handler: event_handler(e) @staticmethod def _translate_modifiers(state): modifiers = 0 if state & xlib.ShiftMask: modifiers |= key.MOD_SHIFT if state & xlib.ControlMask: modifiers |= key.MOD_CTRL if state & xlib.LockMask: modifiers |= key.MOD_CAPSLOCK if state & xlib.Mod1Mask: modifiers |= key.MOD_ALT if state & xlib.Mod2Mask: modifiers |= key.MOD_NUMLOCK if state & xlib.Mod4Mask: modifiers |= key.MOD_WINDOWS if state & xlib.Mod5Mask: modifiers |= key.MOD_SCROLLLOCK return modifiers # Event handlers ''' def _event_symbol(self, event): # pyglet.self.key keysymbols are identical to X11 keysymbols, no # need to map the keysymbol. symbol = xlib.XKeycodeToKeysym(self._x_display, event.xkey.keycode, 0) if symbol == 0: # XIM event return None elif symbol not in key._key_names.keys(): symbol = key.user_key(event.xkey.keycode) return symbol ''' def _event_text_symbol(self, ev): text = None symbol = xlib.KeySym() buffer = create_string_buffer(128) # Look up raw keysym before XIM filters it (default for keypress and # keyrelease) count = xlib.XLookupString(ev.xkey, buffer, len(buffer) - 1, byref(symbol), None) # Give XIM a shot filtered = xlib.XFilterEvent(ev, ev.xany.window) if ev.type == xlib.KeyPress and not filtered: status = c_int() if _have_utf8: encoding = 'utf8' count = xlib.Xutf8LookupString(self._x_ic, ev.xkey, buffer, len(buffer) - 1, byref(symbol), byref(status)) if status.value == xlib.XBufferOverflow: raise NotImplementedError('TODO: XIM buffer resize') else: encoding = 'ascii' count = xlib.XLookupString(ev.xkey, buffer, len(buffer) - 1, byref(symbol), None) if count: status.value = xlib.XLookupBoth if status.value & (xlib.XLookupChars | xlib.XLookupBoth): text = buffer.value[:count].decode(encoding) # Don't treat Unicode command codepoints as text, except Return. if text and unicodedata.category(text) == 'Cc' and text != '\r': text = None symbol = symbol.value # If the event is a XIM filtered event, the keysym will be virtual # (e.g., aacute instead of A after a dead key). Drop it, we don't # want these kind of key events. if ev.xkey.keycode == 0 and not filtered: symbol = None # pyglet.self.key keysymbols are identical to X11 keysymbols, no # need to map the keysymbol. For keysyms outside the pyglet set, map # raw key code to a user key. if symbol and symbol not in key._key_names and ev.xkey.keycode: # Issue 353: Symbol is uppercase when shift key held down. try: symbol = ord(unichr(symbol).lower()) except ValueError: # Not a valid unichr, use the keycode symbol = key.user_key(ev.xkey.keycode) else: # If still not recognised, use the keycode if symbol not in key._key_names: symbol = key.user_key(ev.xkey.keycode) if filtered: # The event was filtered, text must be ignored, but the symbol is # still good. return None, symbol return text, symbol def _event_text_motion(self, symbol, modifiers): if modifiers & key.MOD_ALT: return None ctrl = modifiers & key.MOD_CTRL != 0 return _motion_map.get((symbol, ctrl), None) @ViewEventHandler @XlibEventHandler(xlib.KeyPress) @XlibEventHandler(xlib.KeyRelease) def _event_key_view(self, ev): if ev.type == xlib.KeyRelease: # Look in the queue for a matching KeyPress with same timestamp, # indicating an auto-repeat rather than actual key event. saved = [] while True: auto_event = xlib.XEvent() result = xlib.XCheckWindowEvent(self._x_display, self._window, xlib.KeyPress|xlib.KeyRelease, byref(auto_event)) if not result: break saved.append(auto_event) if auto_event.type == xlib.KeyRelease: # just save this off for restoration back to the queue continue if ev.xkey.keycode == auto_event.xkey.keycode: # Found a key repeat: dispatch EVENT_TEXT* event text, symbol = self._event_text_symbol(auto_event) modifiers = self._translate_modifiers(ev.xkey.state) modifiers_ctrl = modifiers & (key.MOD_CTRL | key.MOD_ALT) motion = self._event_text_motion(symbol, modifiers) if motion: if modifiers & key.MOD_SHIFT: self.dispatch_event( 'on_text_motion_select', motion) else: self.dispatch_event('on_text_motion', motion) elif text and not modifiers_ctrl: self.dispatch_event('on_text', text) ditched = saved.pop() for auto_event in reversed(saved): xlib.XPutBackEvent(self._x_display, byref(auto_event)) return else: # Key code of press did not match, therefore no repeating # is going on, stop searching. break # Whoops, put the events back, it's for real. for auto_event in reversed(saved): xlib.XPutBackEvent(self._x_display, byref(auto_event)) text, symbol = self._event_text_symbol(ev) modifiers = self._translate_modifiers(ev.xkey.state) modifiers_ctrl = modifiers & (key.MOD_CTRL | key.MOD_ALT) motion = self._event_text_motion(symbol, modifiers) if ev.type == xlib.KeyPress: if symbol: self.dispatch_event('on_key_press', symbol, modifiers) if motion: if modifiers & key.MOD_SHIFT: self.dispatch_event('on_text_motion_select', motion) else: self.dispatch_event('on_text_motion', motion) elif text and not modifiers_ctrl: self.dispatch_event('on_text', text) elif ev.type == xlib.KeyRelease: if symbol: self.dispatch_event('on_key_release', symbol, modifiers) @XlibEventHandler(xlib.KeyPress) @XlibEventHandler(xlib.KeyRelease) def _event_key(self, ev): return self._event_key_view(ev) @ViewEventHandler @XlibEventHandler(xlib.MotionNotify) def _event_motionnotify_view(self, ev): x = ev.xmotion.x y = self.height - ev.xmotion.y if self._mouse_in_window: dx = x - self._mouse_x dy = y - self._mouse_y else: dx = dy = 0 if self._applied_mouse_exclusive and \ (ev.xmotion.x, ev.xmotion.y) == self._mouse_exclusive_client: # Ignore events caused by XWarpPointer self._mouse_x = x self._mouse_y = y return if self._applied_mouse_exclusive: # Reset pointer position ex, ey = self._mouse_exclusive_client xlib.XWarpPointer(self._x_display, 0, self._window, 0, 0, 0, 0, ex, ey) self._mouse_x = x self._mouse_y = y self._mouse_in_window = True buttons = 0 if ev.xmotion.state & xlib.Button1MotionMask: buttons |= mouse.LEFT if ev.xmotion.state & xlib.Button2MotionMask: buttons |= mouse.MIDDLE if ev.xmotion.state & xlib.Button3MotionMask: buttons |= mouse.RIGHT if buttons: # Drag event modifiers = self._translate_modifiers(ev.xmotion.state) self.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) else: # Motion event self.dispatch_event('on_mouse_motion', x, y, dx, dy) @XlibEventHandler(xlib.MotionNotify) def _event_motionnotify(self, ev): # Window motion looks for drags that are outside the view but within # the window. buttons = 0 if ev.xmotion.state & xlib.Button1MotionMask: buttons |= mouse.LEFT if ev.xmotion.state & xlib.Button2MotionMask: buttons |= mouse.MIDDLE if ev.xmotion.state & xlib.Button3MotionMask: buttons |= mouse.RIGHT if buttons: # Drag event x = ev.xmotion.x - self._view_x y = self._height - (ev.xmotion.y - self._view_y) if self._mouse_in_window: dx = x - self._mouse_x dy = y - self._mouse_y else: dx = dy = 0 self._mouse_x = x self._mouse_y = y modifiers = self._translate_modifiers(ev.xmotion.state) self.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) @XlibEventHandler(xlib.ClientMessage) def _event_clientmessage(self, ev): atom = ev.xclient.data.l[0] if atom == xlib.XInternAtom(ev.xclient.display, asbytes('WM_DELETE_WINDOW'), False): self.dispatch_event('on_close') elif (self._enable_xsync and atom == xlib.XInternAtom(ev.xclient.display, asbytes('_NET_WM_SYNC_REQUEST'), False)): lo = ev.xclient.data.l[2] hi = ev.xclient.data.l[3] self._current_sync_value = xsync.XSyncValue(hi, lo) def _sync_resize(self): if self._enable_xsync and self._current_sync_valid: if xsync.XSyncValueIsZero(self._current_sync_value): self._current_sync_valid = False return xsync.XSyncSetCounter(self._x_display, self._sync_counter, self._current_sync_value) self._current_sync_value = None self._current_sync_valid = False @ViewEventHandler @XlibEventHandler(xlib.ButtonPress) @XlibEventHandler(xlib.ButtonRelease) def _event_button(self, ev): x = ev.xbutton.x y = self.height - ev.xbutton.y button = 1 << (ev.xbutton.button - 1) # 1, 2, 3 -> 1, 2, 4 modifiers = self._translate_modifiers(ev.xbutton.state) if ev.type == xlib.ButtonPress: # override_redirect issue: manually activate this window if # fullscreen. if self._override_redirect and not self._active: self.activate() if ev.xbutton.button == 4: self.dispatch_event('on_mouse_scroll', x, y, 0, 1) elif ev.xbutton.button == 5: self.dispatch_event('on_mouse_scroll', x, y, 0, -1) elif ev.xbutton.button < len(self._mouse_buttons): self._mouse_buttons[ev.xbutton.button] = True self.dispatch_event('on_mouse_press', x, y, button, modifiers) else: if ev.xbutton.button < 4: self._mouse_buttons[ev.xbutton.button] = False self.dispatch_event('on_mouse_release', x, y, button, modifiers) @ViewEventHandler @XlibEventHandler(xlib.Expose) def _event_expose(self, ev): # Ignore all expose events except the last one. We could be told # about exposure rects - but I don't see the point since we're # working with OpenGL and we'll just redraw the whole scene. if ev.xexpose.count > 0: return self.dispatch_event('on_expose') @ViewEventHandler @XlibEventHandler(xlib.EnterNotify) def _event_enternotify(self, ev): # figure active mouse buttons # XXX ignore modifier state? state = ev.xcrossing.state self._mouse_buttons[1] = state & xlib.Button1Mask self._mouse_buttons[2] = state & xlib.Button2Mask self._mouse_buttons[3] = state & xlib.Button3Mask self._mouse_buttons[4] = state & xlib.Button4Mask self._mouse_buttons[5] = state & xlib.Button5Mask # mouse position x = self._mouse_x = ev.xcrossing.x y = self._mouse_y = self.height - ev.xcrossing.y self._mouse_in_window = True # XXX there may be more we could do here self.dispatch_event('on_mouse_enter', x, y) @ViewEventHandler @XlibEventHandler(xlib.LeaveNotify) def _event_leavenotify(self, ev): x = self._mouse_x = ev.xcrossing.x y = self._mouse_y = self.height - ev.xcrossing.y self._mouse_in_window = False self.dispatch_event('on_mouse_leave', x, y) @XlibEventHandler(xlib.ConfigureNotify) def _event_configurenotify(self, ev): if self._enable_xsync and self._current_sync_value: self._current_sync_valid = True if self._fullscreen: return self.switch_to() w, h = ev.xconfigure.width, ev.xconfigure.height x, y = ev.xconfigure.x, ev.xconfigure.y if self._width != w or self._height != h: self._update_view_size() self._width = w self._height = h self._needs_resize = True if self._x != x or self._y != y: self.dispatch_event('on_move', x, y) self._x = x self._y = y @XlibEventHandler(xlib.FocusIn) def _event_focusin(self, ev): self._active = True self._update_exclusivity() self.dispatch_event('on_activate') xlib.XSetICFocus(self._x_ic) @XlibEventHandler(xlib.FocusOut) def _event_focusout(self, ev): self._active = False self._update_exclusivity() self.dispatch_event('on_deactivate') xlib.XUnsetICFocus(self._x_ic) @XlibEventHandler(xlib.MapNotify) def _event_mapnotify(self, ev): self._mapped = True self.dispatch_event('on_show') self._update_exclusivity() @XlibEventHandler(xlib.UnmapNotify) def _event_unmapnotify(self, ev): self._mapped = False self.dispatch_event('on_hide')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Mouse constants and utilities for pyglet.window. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' def buttons_string(buttons): '''Return a string describing a set of active mouse buttons. Example:: >>> buttons_string(LEFT | RIGHT) 'LEFT|RIGHT' :Parameters: `buttons` : int Bitwise combination of mouse button constants. :rtype: str ''' button_names = [] if buttons & LEFT: button_names.append('LEFT') if buttons & MIDDLE: button_names.append('MIDDLE') if buttons & RIGHT: button_names.append('RIGHT') return '|'.join(button_names) # Symbolic names for the mouse buttons LEFT = 1 << 0 MIDDLE = 1 << 1 RIGHT = 1 << 2
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Windowing and user-interface events. This module allows applications to create and display windows with an OpenGL context. Windows can be created with a variety of border styles or set fullscreen. You can register event handlers for keyboard, mouse and window events. For games and kiosks you can also restrict the input to your windows, for example disabling users from switching away from the application with certain key combinations or capturing and hiding the mouse. Getting started --------------- Call the Window constructor to create a new window:: from pyglet.window import Window win = Window(width=640, height=480) Attach your own event handlers:: @win.event def on_key_press(symbol, modifiers): # ... handle this event ... Place drawing code for the window within the `Window.on_draw` event handler:: @win.event def on_draw(): # ... drawing code ... Call `pyglet.app.run` to enter the main event loop (by default, this returns when all open windows are closed):: from pyglet import app app.run() Creating a game window ---------------------- Use `Window.set_exclusive_mouse` to hide the mouse cursor and receive relative mouse movement events. Specify ``fullscreen=True`` as a keyword argument to the `Window` constructor to render to the entire screen rather than opening a window:: win = Window(fullscreen=True) win.set_exclusive_mouse() Working with multiple screens ----------------------------- By default, fullscreen windows are opened on the primary display (typically set by the user in their operating system settings). You can retrieve a list of attached screens and select one manually if you prefer. This is useful for opening a fullscreen window on each screen:: display = window.get_platform().get_default_display() screens = display.get_screens() windows = [] for screen in screens: windows.append(window.Window(fullscreen=True, screen=screen)) Specifying a screen has no effect if the window is not fullscreen. Specifying the OpenGL context properties ---------------------------------------- Each window has its own context which is created when the window is created. You can specify the properties of the context before it is created by creating a "template" configuration:: from pyglet import gl # Create template config config = gl.Config() config.stencil_size = 8 config.aux_buffers = 4 # Create a window using this config win = window.Window(config=config) To determine if a given configuration is supported, query the screen (see above, "Working with multiple screens"):: configs = screen.get_matching_configs(config) if not configs: # ... config is not supported else: win = window.Window(config=configs[0]) ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import pprint import sys import pyglet from pyglet import gl from pyglet.gl import gl_info from pyglet.event import EventDispatcher import pyglet.window.key import pyglet.window.event _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc class WindowException(Exception): '''The root exception for all window-related errors.''' pass #XXX class NoSuchDisplayException(WindowException): '''An exception indicating the requested display is not available.''' pass class NoSuchConfigException(WindowException): '''An exception indicating the requested configuration is not available.''' pass class NoSuchScreenModeException(WindowException): '''An exception indicating the requested screen resolution could not be met.''' pass class MouseCursorException(WindowException): '''The root exception for all mouse cursor-related errors.''' pass class MouseCursor(object): '''An abstract mouse cursor.''' #: Indicates if the cursor is drawn using OpenGL. This is True #: for all mouse cursors except system cursors. drawable = True def draw(self, x, y): '''Abstract render method. The cursor should be drawn with the "hot" spot at the given coordinates. The projection is set to the pyglet default (i.e., orthographic in window-space), however no other aspects of the state can be assumed. :Parameters: `x` : int X coordinate of the mouse pointer's hot spot. `y` : int Y coordinate of the mouse pointer's hot spot. ''' raise NotImplementedError('abstract') class DefaultMouseCursor(MouseCursor): '''The default mouse cursor used by the operating system.''' drawable = False class ImageMouseCursor(MouseCursor): '''A user-defined mouse cursor created from an image. Use this class to create your own mouse cursors and assign them to windows. There are no constraints on the image size or format. ''' drawable = True def __init__(self, image, hot_x=0, hot_y=0): '''Create a mouse cursor from an image. :Parameters: `image` : `pyglet.image.AbstractImage` Image to use for the mouse cursor. It must have a valid ``texture`` attribute. `hot_x` : int X coordinate of the "hot" spot in the image relative to the image's anchor. `hot_y` : int Y coordinate of the "hot" spot in the image, relative to the image's anchor. ''' self.texture = image.get_texture() self.hot_x = hot_x self.hot_y = hot_y def draw(self, x, y): gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_CURRENT_BIT) gl.glColor4f(1, 1, 1, 1) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) self.texture.blit(x - self.hot_x, y - self.hot_y, 0) gl.glPopAttrib() def _PlatformEventHandler(data): '''Decorator for platform event handlers. Apply giving the platform-specific data needed by the window to associate the method with an event. See platform-specific subclasses of this decorator for examples. The following attributes are set on the function, which is returned otherwise unchanged: _platform_event True _platform_event_data List of data applied to the function (permitting multiple decorators on the same method). ''' def _event_wrapper(f): f._platform_event = True if not hasattr(f, '_platform_event_data'): f._platform_event_data = [] f._platform_event_data.append(data) return f return _event_wrapper def _ViewEventHandler(f): f._view = True return f class _WindowMetaclass(type): '''Sets the _platform_event_names class variable on the window subclass. ''' def __init__(cls, name, bases, dict): cls._platform_event_names = set() for base in bases: if hasattr(base, '_platform_event_names'): cls._platform_event_names.update(base._platform_event_names) for name, func in dict.items(): if hasattr(func, '_platform_event'): cls._platform_event_names.add(name) super(_WindowMetaclass, cls).__init__(name, bases, dict) class BaseWindow(EventDispatcher): '''Platform-independent application window. A window is a "heavyweight" object occupying operating system resources. The "client" or "content" area of a window is filled entirely with an OpenGL viewport. Applications have no access to operating system widgets or controls; all rendering must be done via OpenGL. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). When floating, windows may appear borderless or decorated with a platform-specific frame (including, for example, the title bar, minimize and close buttons, resize handles, and so on). While it is possible to set the location of a window, it is recommended that applications allow the platform to place it according to local conventions. This will ensure it is not obscured by other windows, and appears on an appropriate screen for the user. To render into a window, you must first call `switch_to`, to make it the current OpenGL context. If you use only one window in the application, there is no need to do this. :Ivariables: `has_exit` : bool True if the user has attempted to close the window. :deprecated: Windows are closed immediately by the default `on_close` handler when `pyglet.app.event_loop` is being used. ''' __metaclass__ = _WindowMetaclass # Filled in by metaclass with the names of all methods on this (sub)class # that are platform event handlers. _platform_event_names = set() #: The default window style. WINDOW_STYLE_DEFAULT = None #: The window style for pop-up dialogs. WINDOW_STYLE_DIALOG = 'dialog' #: The window style for tool windows. WINDOW_STYLE_TOOL = 'tool' #: A window style without any decoration. WINDOW_STYLE_BORDERLESS = 'borderless' #: The default mouse cursor. CURSOR_DEFAULT = None #: A crosshair mouse cursor. CURSOR_CROSSHAIR = 'crosshair' #: A pointing hand mouse cursor. CURSOR_HAND = 'hand' #: A "help" mouse cursor; typically a question mark and an arrow. CURSOR_HELP = 'help' #: A mouse cursor indicating that the selected operation is not permitted. CURSOR_NO = 'no' #: A mouse cursor indicating the element can be resized. CURSOR_SIZE = 'size' #: A mouse cursor indicating the element can be resized from the top #: border. CURSOR_SIZE_UP = 'size_up' #: A mouse cursor indicating the element can be resized from the #: upper-right corner. CURSOR_SIZE_UP_RIGHT = 'size_up_right' #: A mouse cursor indicating the element can be resized from the right #: border. CURSOR_SIZE_RIGHT = 'size_right' #: A mouse cursor indicating the element can be resized from the lower-right #: corner. CURSOR_SIZE_DOWN_RIGHT = 'size_down_right' #: A mouse cursor indicating the element can be resized from the bottom #: border. CURSOR_SIZE_DOWN = 'size_down' #: A mouse cursor indicating the element can be resized from the lower-left #: corner. CURSOR_SIZE_DOWN_LEFT = 'size_down_left' #: A mouse cursor indicating the element can be resized from the left #: border. CURSOR_SIZE_LEFT = 'size_left' #: A mouse cursor indicating the element can be resized from the upper-left #: corner. CURSOR_SIZE_UP_LEFT = 'size_up_left' #: A mouse cursor indicating the element can be resized vertically. CURSOR_SIZE_UP_DOWN = 'size_up_down' #: A mouse cursor indicating the element can be resized horizontally. CURSOR_SIZE_LEFT_RIGHT = 'size_left_right' #: A text input mouse cursor (I-beam). CURSOR_TEXT = 'text' #: A "wait" mouse cursor; typically an hourglass or watch. CURSOR_WAIT = 'wait' #: The "wait" mouse cursor combined with an arrow. CURSOR_WAIT_ARROW = 'wait_arrow' has_exit = False #: Window display contents validity. The `pyglet.app` event loop #: examines every window each iteration and only dispatches the `on_draw` #: event to windows that have `invalid` set. By default, windows always #: have `invalid` set to ``True``. #: #: You can prevent redundant redraws by setting this variable to ``False`` #: in the window's `on_draw` handler, and setting it to True again in #: response to any events that actually do require a window contents #: update. #: #: :type: bool #: :since: pyglet 1.1 invalid = True #: Legacy invalidation flag introduced in pyglet 1.2: set by all event #: dispatches that go to non-empty handlers. The default 1.2 event loop #: will therefore redraw after any handled event or scheduled function. _legacy_invalid = True # Instance variables accessible only via properties _width = None _height = None _caption = None _resizable = False _style = WINDOW_STYLE_DEFAULT _fullscreen = False _visible = False _vsync = False _screen = None _config = None _context = None # Used to restore window size and position after fullscreen _windowed_size = None _windowed_location = None # Subclasses should update these after relevant events _mouse_cursor = DefaultMouseCursor() _mouse_x = 0 _mouse_y = 0 _mouse_visible = True _mouse_exclusive = False _mouse_in_window = False _event_queue = None _enable_event_queue = True # overridden by EventLoop. _allow_dispatch_event = False # controlled by dispatch_events stack frame # Class attributes _default_width = 640 _default_height = 480 def __init__(self, width=None, height=None, caption=None, resizable=False, style=WINDOW_STYLE_DEFAULT, fullscreen=False, visible=True, vsync=True, display=None, screen=None, config=None, context=None, mode=None): '''Create a window. All parameters are optional, and reasonable defaults are assumed where they are not specified. The `display`, `screen`, `config` and `context` parameters form a hierarchy of control: there is no need to specify more than one of these. For example, if you specify `screen` the `display` will be inferred, and a default `config` and `context` will be created. `config` is a special case; it can be a template created by the user specifying the attributes desired, or it can be a complete `config` as returned from `Screen.get_matching_configs` or similar. The context will be active as soon as the window is created, as if `switch_to` was just called. :Parameters: `width` : int Width of the window, in pixels. Defaults to 640, or the screen width if `fullscreen` is True. `height` : int Height of the window, in pixels. Defaults to 480, or the screen height if `fullscreen` is True. `caption` : str or unicode Initial caption (title) of the window. Defaults to ``sys.argv[0]``. `resizable` : bool If True, the window will be resizable. Defaults to False. `style` : int One of the ``WINDOW_STYLE_*`` constants specifying the border style of the window. `fullscreen` : bool If True, the window will cover the entire screen rather than floating. Defaults to False. `visible` : bool Determines if the window is visible immediately after creation. Defaults to True. Set this to False if you would like to change attributes of the window before having it appear to the user. `vsync` : bool If True, buffer flips are synchronised to the primary screen's vertical retrace, eliminating flicker. `display` : `Display` The display device to use. Useful only under X11. `screen` : `Screen` The screen to use, if in fullscreen. `config` : `pyglet.gl.Config` Either a template from which to create a complete config, or a complete config. `context` : `pyglet.gl.Context` The context to attach to this window. The context must not already be attached to another window. `mode` : `ScreenMode` The screen will be switched to this mode if `fullscreen` is True. If None, an appropriate mode is selected to accomodate `width` and `height.` ''' EventDispatcher.__init__(self) self._event_queue = [] if not display: display = get_platform().get_default_display() if not screen: screen = display.get_default_screen() if not config: for template_config in [ gl.Config(double_buffer=True, depth_size=24), gl.Config(double_buffer=True, depth_size=16), None]: try: config = screen.get_best_config(template_config) break except NoSuchConfigException: pass if not config: raise NoSuchConfigException('No standard config is available.') if not config.is_complete(): config = screen.get_best_config(config) if not context: context = config.create_context(gl.current_context) # Set these in reverse order to above, to ensure we get user # preference self._context = context self._config = self._context.config # XXX deprecate config's being screen-specific if hasattr(self._config, 'screen'): self._screen = self._config.screen else: display = self._config.canvas.display self._screen = display.get_default_screen() self._display = self._screen.display if fullscreen: if width is None and height is None: self._windowed_size = self._default_width, self._default_height width, height = self._set_fullscreen_mode(mode, width, height) if not self._windowed_size: self._windowed_size = width, height else: if width is None: width = self._default_width if height is None: height = self._default_height self._width = width self._height = height self._resizable = resizable self._fullscreen = fullscreen self._style = style if pyglet.options['vsync'] is not None: self._vsync = pyglet.options['vsync'] else: self._vsync = vsync if caption is None: caption = sys.argv[0] self._caption = caption from pyglet import app app.windows.add(self) self._create() self.switch_to() if visible: self.set_visible(True) self.activate() def _create(self): raise NotImplementedError('abstract') def _recreate(self, changes): '''Recreate the window with current attributes. :Parameters: `changes` : list of str List of attribute names that were changed since the last `_create` or `_recreate`. For example, ``['fullscreen']`` is given if the window is to be toggled to or from fullscreen. ''' raise NotImplementedError('abstract') def flip(self): '''Swap the OpenGL front and back buffers. Call this method on a double-buffered window to update the visible display with the back buffer. The contents of the back buffer is undefined after this operation. Windows are double-buffered by default. This method is called automatically by `EventLoop` after the `on_draw` event. ''' raise NotImplementedError('abstract') def switch_to(self): '''Make this window the current OpenGL rendering context. Only one OpenGL context can be active at a time. This method sets the current window's context to be current. You should use this method in preference to `pyglet.gl.Context.set_current`, as it may perform additional initialisation functions. ''' raise NotImplementedError('abstract') def set_fullscreen(self, fullscreen=True, screen=None, mode=None, width=None, height=None): '''Toggle to or from fullscreen. After toggling fullscreen, the GL context should have retained its state and objects, however the buffers will need to be cleared and redrawn. If `width` and `height` are specified and `fullscreen` is True, the screen may be switched to a different resolution that most closely matches the given size. If the resolution doesn't match exactly, a higher resolution is selected and the window will be centered within a black border covering the rest of the screen. :Parameters: `fullscreen` : bool True if the window should be made fullscreen, False if it should be windowed. `screen` : Screen If not None and fullscreen is True, the window is moved to the given screen. The screen must belong to the same display as the window. `mode` : `ScreenMode` The screen will be switched to the given mode. The mode must have been obtained by enumerating `Screen.get_modes`. If None, an appropriate mode will be selected from the given `width` and `height`. `width` : int Optional width of the window. If unspecified, defaults to the previous window size when windowed, or the screen size if fullscreen. **Since:** pyglet 1.2 `height` : int Optional height of the window. If unspecified, defaults to the previous window size when windowed, or the screen size if fullscreen. **Since:** pyglet 1.2 ''' if (fullscreen == self._fullscreen and (screen is None or screen is self._screen) and (width is None or width == self._width) and (height is None or height == self._height)): return if not self._fullscreen: # Save windowed size self._windowed_size = self.get_size() self._windowed_location = self.get_location() if fullscreen and screen is not None: assert screen.display is self.display self._screen = screen self._fullscreen = fullscreen if self._fullscreen: self._width, self._height = self._set_fullscreen_mode( mode, width, height) else: self.screen.restore_mode() self._width, self._height = self._windowed_size if width is not None: self._width = width if height is not None: self._height = height self._recreate(['fullscreen']) if not self._fullscreen and self._windowed_location: # Restore windowed location. # TODO: Move into platform _create? # Not harmless on Carbon because upsets _width and _height # via _on_window_bounds_changed. if sys.platform != 'darwin' or pyglet.options['darwin_cocoa']: self.set_location(*self._windowed_location) def _set_fullscreen_mode(self, mode, width, height): if mode is not None: self.screen.set_mode(mode) if width is None: width = self.screen.width if height is None: height = self.screen.height elif width is not None or height is not None: if width is None: width = 0 if height is None: height = 0 mode = self.screen.get_closest_mode(width, height) if mode is not None: self.screen.set_mode(mode) elif self.screen.get_modes(): # Only raise exception if mode switching is at all possible. raise NoSuchScreenModeException( 'No mode matching %dx%d' % (width, height)) else: width = self.screen.width height = self.screen.height return width, height def on_resize(self, width, height): '''A default resize event handler. This default handler updates the GL viewport to cover the entire window and sets the ``GL_PROJECTION`` matrix to be orthogonal in window space. The bottom-left corner is (0, 0) and the top-right corner is the width and height of the window in pixels. Override this event handler with your own to create another projection, for example in perspective. ''' gl.glViewport(0, 0, width, height) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(0, width, 0, height, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW) def on_close(self): '''Default on_close handler.''' self.has_exit = True from pyglet import app if app.event_loop.is_running: self.close() def on_key_press(self, symbol, modifiers): '''Default on_key_press handler.''' if symbol == key.ESCAPE and not (modifiers & ~(key.MOD_NUMLOCK | key.MOD_CAPSLOCK | key.MOD_SCROLLLOCK)): self.dispatch_event('on_close') def close(self): '''Close the window. After closing the window, the GL context will be invalid. The window instance cannot be reused once closed (see also `set_visible`). The `pyglet.app.EventLoop.on_window_close` event is dispatched on `pyglet.app.event_loop` when this method is called. ''' from pyglet import app if not self._context: return app.windows.remove(self) self._context.destroy() self._config = None self._context = None if app.event_loop: app.event_loop.dispatch_event('on_window_close', self) def draw_mouse_cursor(self): '''Draw the custom mouse cursor. If the current mouse cursor has ``drawable`` set, this method is called before the buffers are flipped to render it. This method always leaves the ``GL_MODELVIEW`` matrix as current, regardless of what it was set to previously. No other GL state is affected. There is little need to override this method; instead, subclass ``MouseCursor`` and provide your own ``draw`` method. ''' # Draw mouse cursor if set and visible. # XXX leaves state in modelview regardless of starting state if (self._mouse_cursor.drawable and self._mouse_visible and self._mouse_in_window): gl.glMatrixMode(gl.GL_PROJECTION) gl.glPushMatrix() gl.glLoadIdentity() gl.glOrtho(0, self.width, 0, self.height, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glLoadIdentity() self._mouse_cursor.draw(self._mouse_x, self._mouse_y) gl.glMatrixMode(gl.GL_PROJECTION) gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPopMatrix() # Properties provide read-only access to instance variables. Use # set_* methods to change them if applicable. caption = property(lambda self: self._caption, doc='''The window caption (title). Read-only. :type: str ''') resizable = property(lambda self: self._resizable, doc='''True if the window is resizable. Read-only. :type: bool ''') style = property(lambda self: self._style, doc='''The window style; one of the ``WINDOW_STYLE_*`` constants. Read-only. :type: int ''') fullscreen = property(lambda self: self._fullscreen, doc='''True if the window is currently fullscreen. Read-only. :type: bool ''') visible = property(lambda self: self._visible, doc='''True if the window is currently visible. Read-only. :type: bool ''') vsync = property(lambda self: self._vsync, doc='''True if buffer flips are synchronised to the screen's vertical retrace. Read-only. :type: bool ''') display = property(lambda self: self._display, doc='''The display this window belongs to. Read-only. :type: `Display` ''') screen = property(lambda self: self._screen, doc='''The screen this window is fullscreen in. Read-only. :type: `Screen` ''') config = property(lambda self: self._config, doc='''A GL config describing the context of this window. Read-only. :type: `pyglet.gl.Config` ''') context = property(lambda self: self._context, doc='''The OpenGL context attached to this window. Read-only. :type: `pyglet.gl.Context` ''') # These are the only properties that can be set width = property(lambda self: self.get_size()[0], lambda self, width: self.set_size(width, self.height), doc='''The width of the window, in pixels. Read-write. :type: int ''') height = property(lambda self: self.get_size()[1], lambda self, height: self.set_size(self.width, height), doc='''The height of the window, in pixels. Read-write. :type: int ''') def set_caption(self, caption): '''Set the window's caption. The caption appears in the titlebar of the window, if it has one, and in the taskbar on Windows and many X11 window managers. :Parameters: `caption` : str or unicode The caption to set. ''' raise NotImplementedError('abstract') def set_minimum_size(self, width, height): '''Set the minimum size of the window. Once set, the user will not be able to resize the window smaller than the given dimensions. There is no way to remove the minimum size constraint on a window (but you could set it to 0,0). The behaviour is undefined if the minimum size is set larger than the current size of the window. The window size does not include the border or title bar. :Parameters: `width` : int Minimum width of the window, in pixels. `height` : int Minimum height of the window, in pixels. ''' raise NotImplementedError('abstract') def set_maximum_size(self, width, height): '''Set the maximum size of the window. Once set, the user will not be able to resize the window larger than the given dimensions. There is no way to remove the maximum size constraint on a window (but you could set it to a large value). The behaviour is undefined if the maximum size is set smaller than the current size of the window. The window size does not include the border or title bar. :Parameters: `width` : int Maximum width of the window, in pixels. `height` : int Maximum height of the window, in pixels. ''' raise NotImplementedError('abstract') def set_size(self, width, height): '''Resize the window. The behaviour is undefined if the window is not resizable, or if it is currently fullscreen. The window size does not include the border or title bar. :Parameters: `width` : int New width of the window, in pixels. `height` : int New height of the window, in pixels. ''' raise NotImplementedError('abstract') def get_size(self): '''Return the current size of the window. The window size does not include the border or title bar. :rtype: (int, int) :return: The width and height of the window, in pixels. ''' raise NotImplementedError('abstract') def set_location(self, x, y): '''Set the position of the window. :Parameters: `x` : int Distance of the left edge of the window from the left edge of the virtual desktop, in pixels. `y` : int Distance of the top edge of the window from the top edge of the virtual desktop, in pixels. ''' raise NotImplementedError('abstract') def get_location(self): '''Return the current position of the window. :rtype: (int, int) :return: The distances of the left and top edges from their respective edges on the virtual desktop, in pixels. ''' raise NotImplementedError('abstract') def activate(self): '''Attempt to restore keyboard focus to the window. Depending on the window manager or operating system, this may not be successful. For example, on Windows XP an application is not allowed to "steal" focus from another application. Instead, the window's taskbar icon will flash, indicating it requires attention. ''' raise NotImplementedError('abstract') def set_visible(self, visible=True): '''Show or hide the window. :Parameters: `visible` : bool If True, the window will be shown; otherwise it will be hidden. ''' raise NotImplementedError('abstract') def minimize(self): '''Minimize the window. ''' raise NotImplementedError('abstract') def maximize(self): '''Maximize the window. The behaviour of this method is somewhat dependent on the user's display setup. On a multi-monitor system, the window may maximize to either a single screen or the entire virtual desktop. ''' raise NotImplementedError('abstract') def set_vsync(self, vsync): '''Enable or disable vertical sync control. When enabled, this option ensures flips from the back to the front buffer are performed only during the vertical retrace period of the primary display. This can prevent "tearing" or flickering when the buffer is updated in the middle of a video scan. Note that LCD monitors have an analogous time in which they are not reading from the video buffer; while it does not correspond to a vertical retrace it has the same effect. With multi-monitor systems the secondary monitor cannot be synchronised to, so tearing and flicker cannot be avoided when the window is positioned outside of the primary display. In this case it may be advisable to forcibly reduce the framerate (for example, using `pyglet.clock.set_fps_limit`). :Parameters: `vsync` : bool If True, vsync is enabled, otherwise it is disabled. ''' raise NotImplementedError('abstract') def set_mouse_visible(self, visible=True): '''Show or hide the mouse cursor. The mouse cursor will only be hidden while it is positioned within this window. Mouse events will still be processed as usual. :Parameters: `visible` : bool If True, the mouse cursor will be visible, otherwise it will be hidden. ''' self._mouse_visible = visible self.set_mouse_platform_visible() def set_mouse_platform_visible(self, platform_visible=None): '''Set the platform-drawn mouse cursor visibility. This is called automatically after changing the mouse cursor or exclusive mode. Applications should not normally need to call this method, see `set_mouse_visible` instead. :Parameters: `platform_visible` : bool or None If None, sets platform visibility to the required visibility for the current exclusive mode and cursor type. Otherwise, a bool value will override and force a visibility. ''' raise NotImplementedError() def set_mouse_cursor(self, cursor=None): '''Change the appearance of the mouse cursor. The appearance of the mouse cursor is only changed while it is within this window. :Parameters: `cursor` : `MouseCursor` The cursor to set, or None to restore the default cursor. ''' if cursor is None: cursor = DefaultMouseCursor() self._mouse_cursor = cursor self.set_mouse_platform_visible() def set_exclusive_mouse(self, exclusive=True): '''Hide the mouse cursor and direct all mouse events to this window. When enabled, this feature prevents the mouse leaving the window. It is useful for certain styles of games that require complete control of the mouse. The position of the mouse as reported in subsequent events is meaningless when exclusive mouse is enabled; you should only use the relative motion parameters ``dx`` and ``dy``. :Parameters: `exclusive` : bool If True, exclusive mouse is enabled, otherwise it is disabled. ''' raise NotImplementedError('abstract') def set_exclusive_keyboard(self, exclusive=True): '''Prevent the user from switching away from this window using keyboard accelerators. When enabled, this feature disables certain operating-system specific key combinations such as Alt+Tab (Command+Tab on OS X). This can be useful in certain kiosk applications, it should be avoided in general applications or games. :Parameters: `exclusive` : bool If True, exclusive keyboard is enabled, otherwise it is disabled. ''' raise NotImplementedError('abstract') def get_system_mouse_cursor(self, name): '''Obtain a system mouse cursor. Use `set_mouse_cursor` to make the cursor returned by this method active. The names accepted by this method are the ``CURSOR_*`` constants defined on this class. :Parameters: `name` : str Name describing the mouse cursor to return. For example, ``CURSOR_WAIT``, ``CURSOR_HELP``, etc. :rtype: `MouseCursor` :return: A mouse cursor which can be used with `set_mouse_cursor`. ''' raise NotImplementedError() def set_icon(self, *images): '''Set the window icon. If multiple images are provided, one with an appropriate size will be selected (if the correct size is not provided, the image will be scaled). Useful sizes to provide are 16x16, 32x32, 64x64 (Mac only) and 128x128 (Mac only). :Parameters: `images` : sequence of `pyglet.image.AbstractImage` List of images to use for the window icon. ''' pass def clear(self): '''Clear the window. This is a convenience method for clearing the color and depth buffer. The window must be the active context (see `switch_to`). ''' gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) def dispatch_event(self, *args): if not self._enable_event_queue or self._allow_dispatch_event: if EventDispatcher.dispatch_event(self, *args) != False: self._legacy_invalid = True else: self._event_queue.append(args) def dispatch_events(self): '''Poll the operating system event queue for new events and call attached event handlers. This method is provided for legacy applications targeting pyglet 1.0, and advanced applications that must integrate their event loop into another framework. Typical applications should use `pyglet.app.run`. ''' raise NotImplementedError('abstract') # If documenting, show the event methods. Otherwise, leave them out # as they are not really methods. if _is_epydoc: def on_key_press(symbol, modifiers): '''A key on the keyboard was pressed (and held down). In pyglet 1.0 the default handler sets `has_exit` to ``True`` if the ``ESC`` key is pressed. In pyglet 1.1 the default handler dispatches the `on_close` event if the ``ESC`` key is pressed. :Parameters: `symbol` : int The key symbol pressed. `modifiers` : int Bitwise combination of the key modifiers active. :event: ''' def on_key_release(symbol, modifiers): '''A key on the keyboard was released. :Parameters: `symbol` : int The key symbol pressed. `modifiers` : int Bitwise combination of the key modifiers active. :event: ''' def on_text(text): '''The user input some text. Typically this is called after `on_key_press` and before `on_key_release`, but may also be called multiple times if the key is held down (key repeating); or called without key presses if another input method was used (e.g., a pen input). You should always use this method for interpreting text, as the key symbols often have complex mappings to their unicode representation which this event takes care of. :Parameters: `text` : unicode The text entered by the user. :event: ''' def on_text_motion(motion): '''The user moved the text input cursor. Typically this is called after `on_key_press` and before `on_key_release`, but may also be called multiple times if the key is help down (key repeating). You should always use this method for moving the text input cursor (caret), as different platforms have different default keyboard mappings, and key repeats are handled correctly. The values that `motion` can take are defined in `pyglet.window.key`: * MOTION_UP * MOTION_RIGHT * MOTION_DOWN * MOTION_LEFT * MOTION_NEXT_WORD * MOTION_PREVIOUS_WORD * MOTION_BEGINNING_OF_LINE * MOTION_END_OF_LINE * MOTION_NEXT_PAGE * MOTION_PREVIOUS_PAGE * MOTION_BEGINNING_OF_FILE * MOTION_END_OF_FILE * MOTION_BACKSPACE * MOTION_DELETE :Parameters: `motion` : int The direction of motion; see remarks. :event: ''' def on_text_motion_select(motion): '''The user moved the text input cursor while extending the selection. Typically this is called after `on_key_press` and before `on_key_release`, but may also be called multiple times if the key is help down (key repeating). You should always use this method for responding to text selection events rather than the raw `on_key_press`, as different platforms have different default keyboard mappings, and key repeats are handled correctly. The values that `motion` can take are defined in `pyglet.window.key`: * MOTION_UP * MOTION_RIGHT * MOTION_DOWN * MOTION_LEFT * MOTION_NEXT_WORD * MOTION_PREVIOUS_WORD * MOTION_BEGINNING_OF_LINE * MOTION_END_OF_LINE * MOTION_NEXT_PAGE * MOTION_PREVIOUS_PAGE * MOTION_BEGINNING_OF_FILE * MOTION_END_OF_FILE :Parameters: `motion` : int The direction of selection motion; see remarks. :event: ''' def on_mouse_motion(x, y, dx, dy): '''The mouse was moved with no buttons held down. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `dx` : int Relative X position from the previous mouse position. `dy` : int Relative Y position from the previous mouse position. :event: ''' def on_mouse_drag(x, y, dx, dy, buttons, modifiers): '''The mouse was moved with one or more mouse buttons pressed. This event will continue to be fired even if the mouse leaves the window, so long as the drag buttons are continuously held down. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `dx` : int Relative X position from the previous mouse position. `dy` : int Relative Y position from the previous mouse position. `buttons` : int Bitwise combination of the mouse buttons currently pressed. `modifiers` : int Bitwise combination of any keyboard modifiers currently active. :event: ''' def on_mouse_press(x, y, button, modifiers): '''A mouse button was pressed (and held down). :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `button` : int The mouse button that was pressed. `modifiers` : int Bitwise combination of any keyboard modifiers currently active. :event: ''' def on_mouse_release(x, y, button, modifiers): '''A mouse button was released. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `button` : int The mouse button that was released. `modifiers` : int Bitwise combination of any keyboard modifiers currently active. :event: ''' def on_mouse_scroll(x, y, scroll_x, scroll_y): '''The mouse wheel was scrolled. Note that most mice have only a vertical scroll wheel, so `scroll_x` is usually 0. An exception to this is the Apple Mighty Mouse, which has a mouse ball in place of the wheel which allows both `scroll_x` and `scroll_y` movement. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `scroll_x` : int Number of "clicks" towards the right (left if negative). `scroll_y` : int Number of "clicks" upwards (downwards if negative). :event: ''' def on_close(): '''The user attempted to close the window. This event can be triggered by clicking on the "X" control box in the window title bar, or by some other platform-dependent manner. The default handler sets `has_exit` to ``True``. In pyglet 1.1, if `pyglet.app.event_loop` is being used, `close` is also called, closing the window immediately. :event: ''' def on_mouse_enter(x, y): '''The mouse was moved into the window. This event will not be trigged if the mouse is currently being dragged. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. :event: ''' def on_mouse_leave(x, y): '''The mouse was moved outside of the window. This event will not be trigged if the mouse is currently being dragged. Note that the coordinates of the mouse pointer will be outside of the window rectangle. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. :event: ''' def on_expose(): '''A portion of the window needs to be redrawn. This event is triggered when the window first appears, and any time the contents of the window is invalidated due to another window obscuring it. There is no way to determine which portion of the window needs redrawing. Note that the use of this method is becoming increasingly uncommon, as newer window managers composite windows automatically and keep a backing store of the window contents. :event: ''' def on_resize(width, height): '''The window was resized. The window will have the GL context when this event is dispatched; there is no need to call `switch_to` in this handler. :Parameters: `width` : int The new width of the window, in pixels. `height` : int The new height of the window, in pixels. :event: ''' def on_move(x, y): '''The window was moved. :Parameters: `x` : int Distance from the left edge of the screen to the left edge of the window. `y` : int Distance from the top edge of the screen to the top edge of the window. Note that this is one of few methods in pyglet which use a Y-down coordinate system. :event: ''' def on_activate(): '''The window was activated. This event can be triggered by clicking on the title bar, bringing it to the foreground; or by some platform-specific method. When a window is "active" it has the keyboard focus. :event: ''' def on_deactivate(): '''The window was deactivated. This event can be triggered by clicking on another application window. When a window is deactivated it no longer has the keyboard focus. :event: ''' def on_show(): '''The window was shown. This event is triggered when a window is restored after being minimised, or after being displayed for the first time. :event: ''' def on_hide(): '''The window was hidden. This event is triggered when a window is minimised or (on Mac OS X) hidden by the user. :event: ''' def on_context_lost(): '''The window's GL context was lost. When the context is lost no more GL methods can be called until it is recreated. This is a rare event, triggered perhaps by the user switching to an incompatible video mode. When it occurs, an application will need to reload all objects (display lists, texture objects, shaders) as well as restore the GL state. :event: ''' def on_context_state_lost(): '''The state of the window's GL context was lost. pyglet may sometimes need to recreate the window's GL context if the window is moved to another video device, or between fullscreen or windowed mode. In this case it will try to share the objects (display lists, texture objects, shaders) between the old and new contexts. If this is possible, only the current state of the GL context is lost, and the application should simply restore state. :event: ''' def on_draw(): '''The window contents must be redrawn. The `EventLoop` will dispatch this event when the window should be redrawn. This will happen during idle time after any window events and after any scheduled functions were called. The window will already have the GL context, so there is no need to call `switch_to`. The window's `flip` method will be called after this event, so your event handler should not. You should make no assumptions about the window contents when this event is triggered; a resize or expose event may have invalidated the framebuffer since the last time it was drawn. :since: pyglet 1.1 :event: ''' BaseWindow.register_event_type('on_key_press') BaseWindow.register_event_type('on_key_release') BaseWindow.register_event_type('on_text') BaseWindow.register_event_type('on_text_motion') BaseWindow.register_event_type('on_text_motion_select') BaseWindow.register_event_type('on_mouse_motion') BaseWindow.register_event_type('on_mouse_drag') BaseWindow.register_event_type('on_mouse_press') BaseWindow.register_event_type('on_mouse_release') BaseWindow.register_event_type('on_mouse_scroll') BaseWindow.register_event_type('on_mouse_enter') BaseWindow.register_event_type('on_mouse_leave') BaseWindow.register_event_type('on_close') BaseWindow.register_event_type('on_expose') BaseWindow.register_event_type('on_resize') BaseWindow.register_event_type('on_move') BaseWindow.register_event_type('on_activate') BaseWindow.register_event_type('on_deactivate') BaseWindow.register_event_type('on_show') BaseWindow.register_event_type('on_hide') BaseWindow.register_event_type('on_context_lost') BaseWindow.register_event_type('on_context_state_lost') BaseWindow.register_event_type('on_draw') class FPSDisplay(object): '''Display of a window's framerate. This is a convenience class to aid in profiling and debugging. Typical usage is to create an `FPSDisplay` for each window, and draw the display at the end of the windows' `on_draw` event handler:: window = pyglet.window.Window() fps_display = FPSDisplay(window) @window.event def on_draw(): # ... perform ordinary window drawing operations ... fps_display.draw() The style and position of the display can be modified via the `label` attribute. Different text can be substituted by overriding the `set_fps` method. The display can be set to update more or less often by setting the `update_period` attribute. :Ivariables: `label` : Label The text label displaying the framerate. ''' #: Time in seconds between updates. #: #: :type: float update_period = 0.25 def __init__(self, window): from time import time from pyglet.text import Label self.label = Label('', x=10, y=10, font_size=24, bold=True, color=(127, 127, 127, 127)) self.window = window self._window_flip = window.flip window.flip = self._hook_flip self.time = 0.0 self.last_time = time() self.count = 0 def update(self): '''Records a new data point at the current time. This method is called automatically when the window buffer is flipped. ''' from time import time t = time() self.count += 1 self.time += t - self.last_time self.last_time = t if self.time >= self.update_period: self.set_fps(self.count / self.update_period) self.time %= self.update_period self.count = 0 def set_fps(self, fps): '''Set the label text for the given FPS estimation. Called by `update` every `update_period` seconds. :Parameters: `fps` : float Estimated framerate of the window. ''' self.label.text = '%.2f' % fps def draw(self): '''Draw the label. The OpenGL state is assumed to be at default values, except that the MODELVIEW and PROJECTION matrices are ignored. At the return of this method the matrix mode will be MODELVIEW. ''' gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glLoadIdentity() gl.glMatrixMode(gl.GL_PROJECTION) gl.glPushMatrix() gl.glLoadIdentity() gl.glOrtho(0, self.window.width, 0, self.window.height, -1, 1) self.label.draw() gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPopMatrix() def _hook_flip(self): self.update() self._window_flip() if _is_epydoc: # We are building documentation Window = BaseWindow Window.__name__ = 'Window' del BaseWindow else: # Try to determine which platform to use. if sys.platform == 'darwin': if pyglet.options['darwin_cocoa']: from pyglet.window.cocoa import CocoaWindow as Window else: from pyglet.window.carbon import CarbonWindow as Window elif sys.platform in ('win32', 'cygwin'): from pyglet.window.win32 import Win32Window as Window else: # XXX HACK around circ problem, should be fixed after removal of # shadow nonsense #pyglet.window = sys.modules[__name__] #import key, mouse from pyglet.window.xlib import XlibWindow as Window # Deprecated API def get_platform(): '''Get an instance of the Platform most appropriate for this system. :deprecated: Use `pyglet.canvas.Display`. :rtype: `Platform` :return: The platform instance. ''' return Platform() class Platform(object): '''Operating-system-level functionality. The platform instance can only be obtained with `get_platform`. Use the platform to obtain a `Display` instance. :deprecated: Use `pyglet.canvas.Display` ''' def get_display(self, name): '''Get a display device by name. This is meaningful only under X11, where the `name` is a string including the host name and display number; for example ``"localhost:1"``. On platforms other than X11, `name` is ignored and the default display is returned. pyglet does not support multiple multiple video devices on Windows or OS X. If more than one device is attached, they will appear as a single virtual device comprising all the attached screens. :deprecated: Use `pyglet.canvas.get_display`. :Parameters: `name` : str The name of the display to connect to. :rtype: `Display` ''' for display in pyglet.app.displays: if display.name == name: return display return pyglet.canvas.Display(name) def get_default_display(self): '''Get the default display device. :deprecated: Use `pyglet.app.get_display`. :rtype: `Display` ''' return pyglet.canvas.get_display() if _is_epydoc: class Display(object): '''A display device supporting one or more screens. Use `Platform.get_display` or `Platform.get_default_display` to obtain an instance of this class. Use a display to obtain `Screen` instances. :deprecated: Use `pyglet.canvas.Display`. ''' def __init__(self): raise NotImplementedError('deprecated') def get_screens(self): '''Get the available screens. A typical multi-monitor workstation comprises one `Display` with multiple `Screen` s. This method returns a list of screens which can be enumerated to select one for full-screen display. For the purposes of creating an OpenGL config, the default screen will suffice. :rtype: list of `Screen` ''' raise NotImplementedError('deprecated') def get_default_screen(self): '''Get the default screen as specified by the user's operating system preferences. :rtype: `Screen` ''' raise NotImplementedError('deprecated') def get_windows(self): '''Get the windows currently attached to this display. :rtype: sequence of `Window` ''' raise NotImplementedError('deprecated') else: Display = pyglet.canvas.Display Screen = pyglet.canvas.Screen # XXX remove # Create shadow window. (trickery is for circular import) if not _is_epydoc: pyglet.window = sys.modules[__name__] gl._create_shadow_window()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * import unicodedata import warnings import sys if sys.platform not in ('cygwin', 'win32'): raise ImportError('Not a win32 platform.') import pyglet from pyglet.window import BaseWindow, \ WindowException, MouseCursor, DefaultMouseCursor, _PlatformEventHandler, \ _ViewEventHandler from pyglet.event import EventDispatcher from pyglet.window import key from pyglet.window import mouse from pyglet.canvas.win32 import Win32Canvas from pyglet.libs.win32 import _user32, _kernel32, _gdi32 from pyglet.libs.win32.constants import * from pyglet.libs.win32.winkey import * from pyglet.libs.win32.types import * # symbol,ctrl -> motion mapping _motion_map = { (key.UP, False): key.MOTION_UP, (key.RIGHT, False): key.MOTION_RIGHT, (key.DOWN, False): key.MOTION_DOWN, (key.LEFT, False): key.MOTION_LEFT, (key.RIGHT, True): key.MOTION_NEXT_WORD, (key.LEFT, True): key.MOTION_PREVIOUS_WORD, (key.HOME, False): key.MOTION_BEGINNING_OF_LINE, (key.END, False): key.MOTION_END_OF_LINE, (key.PAGEUP, False): key.MOTION_PREVIOUS_PAGE, (key.PAGEDOWN, False): key.MOTION_NEXT_PAGE, (key.HOME, True): key.MOTION_BEGINNING_OF_FILE, (key.END, True): key.MOTION_END_OF_FILE, (key.BACKSPACE, False): key.MOTION_BACKSPACE, (key.DELETE, False): key.MOTION_DELETE, } class Win32MouseCursor(MouseCursor): drawable = False def __init__(self, cursor): self.cursor = cursor # This is global state, we have to be careful not to set the same state twice, # which will throw off the ShowCursor counter. _win32_cursor_visible = True Win32EventHandler = _PlatformEventHandler ViewEventHandler = _ViewEventHandler class Win32Window(BaseWindow): _window_class = None _hwnd = None _dc = None _wgl_context = None _tracking = False _hidden = False _has_focus = False _exclusive_keyboard = False _exclusive_keyboard_focus = True _exclusive_mouse = False _exclusive_mouse_focus = True _exclusive_mouse_screen = None _exclusive_mouse_client = None _mouse_platform_visible = True _ws_style = 0 _ex_ws_style = 0 _minimum_size = None _maximum_size = None def __init__(self, *args, **kwargs): # Bind event handlers self._event_handlers = {} self._view_event_handlers = {} for func_name in self._platform_event_names: if not hasattr(self, func_name): continue func = getattr(self, func_name) for message in func._platform_event_data: if hasattr(func, '_view'): self._view_event_handlers[message] = func else: self._event_handlers[message] = func super(Win32Window, self).__init__(*args, **kwargs) def _recreate(self, changes): if 'context' in changes: self._wgl_context = None self._create() def _create(self): # Ensure style is set before determining width/height. if self._fullscreen: self._ws_style = WS_POPUP self._ex_ws_style = 0 # WS_EX_TOPMOST else: styles = { self.WINDOW_STYLE_DEFAULT: (WS_OVERLAPPEDWINDOW, 0), self.WINDOW_STYLE_DIALOG: (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU, WS_EX_DLGMODALFRAME), self.WINDOW_STYLE_TOOL: (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU, WS_EX_TOOLWINDOW), self.WINDOW_STYLE_BORDERLESS: (WS_POPUP, 0), } self._ws_style, self._ex_ws_style = styles[self._style] if self._resizable and not self._fullscreen: self._ws_style |= WS_THICKFRAME else: self._ws_style &= ~(WS_THICKFRAME|WS_MAXIMIZEBOX) if self._fullscreen: width = self.screen.width height = self.screen.height else: width, height = \ self._client_to_window_size(self._width, self._height) if not self._window_class: module = _kernel32.GetModuleHandleW(None) white = _gdi32.GetStockObject(WHITE_BRUSH) black = _gdi32.GetStockObject(BLACK_BRUSH) self._window_class = WNDCLASS() self._window_class.lpszClassName = u'GenericAppClass%d' % id(self) self._window_class.lpfnWndProc = WNDPROC(self._wnd_proc) self._window_class.style = CS_VREDRAW | CS_HREDRAW self._window_class.hInstance = 0 self._window_class.hIcon = _user32.LoadIconW(module, MAKEINTRESOURCE(1)) self._window_class.hbrBackground = black self._window_class.lpszMenuName = None self._window_class.cbClsExtra = 0 self._window_class.cbWndExtra = 0 _user32.RegisterClassW(byref(self._window_class)) self._view_window_class = WNDCLASS() self._view_window_class.lpszClassName = \ u'GenericViewClass%d' % id(self) self._view_window_class.lpfnWndProc = WNDPROC(self._wnd_proc_view) self._view_window_class.style = 0 self._view_window_class.hInstance = 0 self._view_window_class.hIcon = 0 self._view_window_class.hbrBackground = white self._view_window_class.lpszMenuName = None self._view_window_class.cbClsExtra = 0 self._view_window_class.cbWndExtra = 0 _user32.RegisterClassW(byref(self._view_window_class)) if not self._hwnd: self._hwnd = _user32.CreateWindowExW( self._ex_ws_style, self._window_class.lpszClassName, u'', self._ws_style, CW_USEDEFAULT, CW_USEDEFAULT, width, height, 0, 0, self._window_class.hInstance, 0) self._view_hwnd = _user32.CreateWindowExW( 0, self._view_window_class.lpszClassName, u'', WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, self._hwnd, 0, self._view_window_class.hInstance, 0) self._dc = _user32.GetDC(self._view_hwnd) else: # Window already exists, update it with new style # We need to hide window here, otherwise Windows forgets # to redraw the whole screen after leaving fullscreen. _user32.ShowWindow(self._hwnd, SW_HIDE) _user32.SetWindowLongW(self._hwnd, GWL_STYLE, self._ws_style) _user32.SetWindowLongW(self._hwnd, GWL_EXSTYLE, self._ex_ws_style) if self._fullscreen: hwnd_after = HWND_TOPMOST else: hwnd_after = HWND_NOTOPMOST # Position and size window if self._fullscreen: _user32.SetWindowPos(self._hwnd, hwnd_after, self._screen.x, self._screen.y, width, height, SWP_FRAMECHANGED) elif False: # TODO location not in pyglet API x, y = self._client_to_window_pos(*factory.get_location()) _user32.SetWindowPos(self._hwnd, hwnd_after, x, y, width, height, SWP_FRAMECHANGED) else: _user32.SetWindowPos(self._hwnd, hwnd_after, 0, 0, width, height, SWP_NOMOVE | SWP_FRAMECHANGED) self._update_view_location(self._width, self._height) # Context must be created after window is created. if not self._wgl_context: self.canvas = Win32Canvas(self.display, self._view_hwnd, self._dc) self.context.attach(self.canvas) self._wgl_context = self.context._context self.set_caption(self._caption) self.switch_to() self.set_vsync(self._vsync) if self._visible: self.set_visible() self.dispatch_event('on_expose') # Might need resize event if going from fullscreen to fullscreen self.dispatch_event('on_resize', self._width, self._height) def _update_view_location(self, width, height): if self._fullscreen: x = (self.screen.width - width) // 2 y = (self.screen.height - height) // 2 else: x = y = 0 _user32.SetWindowPos(self._view_hwnd, 0, x, y, width, height, SWP_NOZORDER | SWP_NOOWNERZORDER) def close(self): super(Win32Window, self).close() if not self._hwnd: return _user32.DestroyWindow(self._hwnd) _user32.UnregisterClassW(self._window_class.lpszClassName, 0) self.set_mouse_platform_visible(True) self._hwnd = None self._dc = None self._wgl_context = None def _get_vsync(self): return self.context.get_vsync() vsync = property(_get_vsync) # overrides BaseWindow property def set_vsync(self, vsync): if pyglet.options['vsync'] is not None: vsync = pyglet.options['vsync'] self.context.set_vsync(vsync) def switch_to(self): self.context.set_current() def flip(self): self.draw_mouse_cursor() self.context.flip() def set_location(self, x, y): x, y = self._client_to_window_pos(x, y) _user32.SetWindowPos(self._hwnd, 0, x, y, 0, 0, (SWP_NOZORDER | SWP_NOSIZE | SWP_NOOWNERZORDER)) def get_location(self): rect = RECT() _user32.GetClientRect(self._hwnd, byref(rect)) point = POINT() point.x = rect.left point.y = rect.top _user32.ClientToScreen(self._hwnd, byref(point)) return point.x, point.y def set_size(self, width, height): if self._fullscreen: raise WindowException('Cannot set size of fullscreen window.') width, height = self._client_to_window_size(width, height) _user32.SetWindowPos(self._hwnd, 0, 0, 0, width, height, (SWP_NOZORDER | SWP_NOMOVE | SWP_NOOWNERZORDER)) def get_size(self): #rect = RECT() #_user32.GetClientRect(self._hwnd, byref(rect)) #return rect.right - rect.left, rect.bottom - rect.top return self._width, self._height def set_minimum_size(self, width, height): self._minimum_size = width, height def set_maximum_size(self, width, height): self._maximum_size = width, height def activate(self): _user32.SetForegroundWindow(self._hwnd) def set_visible(self, visible=True): if visible: if self._fullscreen: _user32.SetWindowPos(self._hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW) else: _user32.ShowWindow(self._hwnd, SW_SHOW) self.dispatch_event('on_show') self.activate() else: _user32.ShowWindow(self._hwnd, SW_HIDE) self.dispatch_event('on_hide') self._visible = visible self.set_mouse_platform_visible() def minimize(self): _user32.ShowWindow(self._hwnd, SW_MINIMIZE) def maximize(self): _user32.ShowWindow(self._hwnd, SW_MAXIMIZE) def set_caption(self, caption): self._caption = caption _user32.SetWindowTextW(self._hwnd, c_wchar_p(caption)) def set_mouse_platform_visible(self, platform_visible=None): if platform_visible is None: platform_visible = (self._mouse_visible and not self._exclusive_mouse and not self._mouse_cursor.drawable) or \ (not self._mouse_in_window or not self._has_focus) if platform_visible and not self._mouse_cursor.drawable: if isinstance(self._mouse_cursor, Win32MouseCursor): cursor = self._mouse_cursor.cursor else: cursor = _user32.LoadCursorW(None, MAKEINTRESOURCE(IDC_ARROW)) _user32.SetClassLongPtrW(self._view_hwnd, GCL_HCURSOR, cursor) _user32.SetCursor(cursor) if platform_visible == self._mouse_platform_visible: return # Avoid calling ShowCursor with the current visibility (which would # push the counter too far away from zero). global _win32_cursor_visible if _win32_cursor_visible != platform_visible: _user32.ShowCursor(platform_visible) _win32_cursor_visible = platform_visible self._mouse_platform_visible = platform_visible def _reset_exclusive_mouse_screen(self): '''Recalculate screen coords of mouse warp point for exclusive mouse.''' p = POINT() rect = RECT() _user32.GetClientRect(self._view_hwnd, byref(rect)) _user32.MapWindowPoints(self._view_hwnd, HWND_DESKTOP, byref(rect), 2) p.x = (rect.left + rect.right) // 2 p.y = (rect.top + rect.bottom) // 2 # This is the point the mouse will be kept at while in exclusive # mode. self._exclusive_mouse_screen = p.x, p.y self._exclusive_mouse_client = p.x - rect.left, p.y - rect.top def set_exclusive_mouse(self, exclusive=True): if self._exclusive_mouse == exclusive and \ self._exclusive_mouse_focus == self._has_focus: return if exclusive and self._has_focus: # Move mouse to the center of the window. self._reset_exclusive_mouse_screen() x, y = self._exclusive_mouse_screen self.set_mouse_position(x, y, absolute=True) # Clip to client area, to prevent large mouse movements taking # it outside the client area. rect = RECT() _user32.GetClientRect(self._view_hwnd, byref(rect)) _user32.MapWindowPoints(self._view_hwnd, HWND_DESKTOP, byref(rect), 2) _user32.ClipCursor(byref(rect)) else: # Release clip _user32.ClipCursor(None) self._exclusive_mouse = exclusive self._exclusive_mouse_focus = self._has_focus self.set_mouse_platform_visible() def set_mouse_position(self, x, y, absolute=False): if not absolute: rect = RECT() _user32.GetClientRect(self._view_hwnd, byref(rect)) _user32.MapWindowPoints(self._view_hwnd, HWND_DESKTOP, byref(rect), 2) x = x + rect.left y = rect.top + (rect.bottom - rect.top) - y _user32.SetCursorPos(x, y) def set_exclusive_keyboard(self, exclusive=True): if self._exclusive_keyboard == exclusive and \ self._exclusive_keyboard_focus == self._has_focus: return if exclusive and self._has_focus: _user32.RegisterHotKey(self._hwnd, 0, WIN32_MOD_ALT, VK_TAB) else: _user32.UnregisterHotKey(self._hwnd, 0) self._exclusive_keyboard = exclusive self._exclusive_keyboard_focus = self._has_focus def get_system_mouse_cursor(self, name): if name == self.CURSOR_DEFAULT: return DefaultMouseCursor() names = { self.CURSOR_CROSSHAIR: IDC_CROSS, self.CURSOR_HAND: IDC_HAND, self.CURSOR_HELP: IDC_HELP, self.CURSOR_NO: IDC_NO, self.CURSOR_SIZE: IDC_SIZEALL, self.CURSOR_SIZE_UP: IDC_SIZENS, self.CURSOR_SIZE_UP_RIGHT: IDC_SIZENESW, self.CURSOR_SIZE_RIGHT: IDC_SIZEWE, self.CURSOR_SIZE_DOWN_RIGHT: IDC_SIZENWSE, self.CURSOR_SIZE_DOWN: IDC_SIZENS, self.CURSOR_SIZE_DOWN_LEFT: IDC_SIZENESW, self.CURSOR_SIZE_LEFT: IDC_SIZEWE, self.CURSOR_SIZE_UP_LEFT: IDC_SIZENWSE, self.CURSOR_SIZE_UP_DOWN: IDC_SIZENS, self.CURSOR_SIZE_LEFT_RIGHT: IDC_SIZEWE, self.CURSOR_TEXT: IDC_IBEAM, self.CURSOR_WAIT: IDC_WAIT, self.CURSOR_WAIT_ARROW: IDC_APPSTARTING, } if name not in names: raise RuntimeError('Unknown cursor name "%s"' % name) cursor = _user32.LoadCursorW(None, unicode(names[name])) return Win32MouseCursor(cursor) def set_icon(self, *images): # XXX Undocumented AFAICT, but XP seems happy to resize an image # of any size, so no scaling necessary. def best_image(width, height): # A heuristic for finding closest sized image to required size. image = images[0] for img in images: if img.width == width and img.height == height: # Exact match always used return img elif img.width >= width and \ img.width * img.height > image.width * image.height: # At least wide enough, and largest area image = img return image def get_icon(image): # Alpha-blended icon: see http://support.microsoft.com/kb/318876 format = 'BGRA' pitch = len(format) * image.width header = BITMAPV5HEADER() header.bV5Size = sizeof(header) header.bV5Width = image.width header.bV5Height = image.height header.bV5Planes = 1 header.bV5BitCount = 32 header.bV5Compression = BI_BITFIELDS header.bV5RedMask = 0x00ff0000 header.bV5GreenMask = 0x0000ff00 header.bV5BlueMask = 0x000000ff header.bV5AlphaMask = 0xff000000 hdc = _user32.GetDC(None) dataptr = c_void_p() bitmap = _gdi32.CreateDIBSection(hdc, byref(header), DIB_RGB_COLORS, byref(dataptr), None, 0) _user32.ReleaseDC(None, hdc) data = image.get_data(format, pitch) memmove(dataptr, data, len(data)) mask = _gdi32.CreateBitmap(image.width, image.height, 1, 1, None) iconinfo = ICONINFO() iconinfo.fIcon = True iconinfo.hbmMask = mask iconinfo.hbmColor = bitmap icon = _user32.CreateIconIndirect(byref(iconinfo)) _gdi32.DeleteObject(mask) _gdi32.DeleteObject(bitmap) return icon # Set large icon image = best_image(_user32.GetSystemMetrics(SM_CXICON), _user32.GetSystemMetrics(SM_CYICON)) icon = get_icon(image) _user32.SetClassLongW(self._hwnd, GCL_HICON, icon) # Set small icon image = best_image(_user32.GetSystemMetrics(SM_CXSMICON), _user32.GetSystemMetrics(SM_CYSMICON)) icon = get_icon(image) _user32.SetClassLongW(self._hwnd, GCL_HICONSM, icon) # Private util def _client_to_window_size(self, width, height): rect = RECT() rect.left = 0 rect.top = 0 rect.right = width rect.bottom = height _user32.AdjustWindowRectEx(byref(rect), self._ws_style, False, self._ex_ws_style) return rect.right - rect.left, rect.bottom - rect.top def _client_to_window_pos(self, x, y): rect = RECT() rect.left = x rect.top = y _user32.AdjustWindowRectEx(byref(rect), self._ws_style, False, self._ex_ws_style) return rect.left, rect.top # Event dispatching def dispatch_events(self): from pyglet import app app.platform_event_loop.start() self._allow_dispatch_event = True self.dispatch_pending_events() msg = MSG() while _user32.PeekMessageW(byref(msg), 0, 0, 0, PM_REMOVE): _user32.TranslateMessage(byref(msg)) _user32.DispatchMessageW(byref(msg)) self._allow_dispatch_event = False def dispatch_pending_events(self): while self._event_queue: event = self._event_queue.pop(0) if type(event[0]) is str: # pyglet event EventDispatcher.dispatch_event(self, *event) else: # win32 event event[0](*event[1:]) def _wnd_proc(self, hwnd, msg, wParam, lParam): event_handler = self._event_handlers.get(msg, None) result = 0 if event_handler: if self._allow_dispatch_event or not self._enable_event_queue: result = event_handler(msg, wParam, lParam) else: self._event_queue.append((event_handler, msg, wParam, lParam)) result = 0 if not result and msg != WM_CLOSE: result = _user32.DefWindowProcW(hwnd, msg, wParam, lParam) return result def _wnd_proc_view(self, hwnd, msg, wParam, lParam): event_handler = self._view_event_handlers.get(msg, None) result = 0 if event_handler: if self._allow_dispatch_event or not self._enable_event_queue: result = event_handler(msg, wParam, lParam) else: self._event_queue.append((event_handler, msg, wParam, lParam)) result = 0 if not result and msg != WM_CLOSE: result = _user32.DefWindowProcW(hwnd, msg, wParam, lParam) return result # Event handlers def _get_modifiers(self, key_lParam=0): modifiers = 0 if _user32.GetKeyState(VK_SHIFT) & 0xff00: modifiers |= key.MOD_SHIFT if _user32.GetKeyState(VK_CONTROL) & 0xff00: modifiers |= key.MOD_CTRL if _user32.GetKeyState(VK_LWIN) & 0xff00: modifiers |= key.MOD_WINDOWS if _user32.GetKeyState(VK_CAPITAL) & 0x00ff: # toggle modifiers |= key.MOD_CAPSLOCK if _user32.GetKeyState(VK_NUMLOCK) & 0x00ff: # toggle modifiers |= key.MOD_NUMLOCK if _user32.GetKeyState(VK_SCROLL) & 0x00ff: # toggle modifiers |= key.MOD_SCROLLLOCK if key_lParam: if key_lParam & (1 << 29): modifiers |= key.MOD_ALT elif _user32.GetKeyState(VK_MENU) < 0: modifiers |= key.MOD_ALT return modifiers @staticmethod def _get_location(lParam): x = c_int16(lParam & 0xffff).value y = c_int16(lParam >> 16).value return x, y @Win32EventHandler(WM_KEYDOWN) @Win32EventHandler(WM_KEYUP) @Win32EventHandler(WM_SYSKEYDOWN) @Win32EventHandler(WM_SYSKEYUP) def _event_key(self, msg, wParam, lParam): repeat = False if lParam & (1 << 30): if msg not in (WM_KEYUP, WM_SYSKEYUP): repeat = True ev = 'on_key_release' else: ev = 'on_key_press' symbol = keymap.get(wParam, None) if symbol is None: ch = _user32.MapVirtualKeyW(wParam, MAPVK_VK_TO_CHAR) symbol = chmap.get(ch) if symbol is None: symbol = key.user_key(wParam) elif symbol == key.LCTRL and lParam & (1 << 24): symbol = key.RCTRL elif symbol == key.LALT and lParam & (1 << 24): symbol = key.RALT elif symbol == key.LSHIFT: pass # TODO: some magic with getstate to find out if it's the # right or left shift key. modifiers = self._get_modifiers(lParam) if not repeat: self.dispatch_event(ev, symbol, modifiers) ctrl = modifiers & key.MOD_CTRL != 0 if (symbol, ctrl) in _motion_map and msg not in (WM_KEYUP, WM_SYSKEYUP): motion = _motion_map[symbol, ctrl] if modifiers & key.MOD_SHIFT: self.dispatch_event('on_text_motion_select', motion) else: self.dispatch_event('on_text_motion', motion) # Send on to DefWindowProc if not exclusive. if self._exclusive_keyboard: return 0 else: return None @Win32EventHandler(WM_CHAR) def _event_char(self, msg, wParam, lParam): text = unichr(wParam) if unicodedata.category(text) != 'Cc' or text == '\r': self.dispatch_event('on_text', text) return 0 @ViewEventHandler @Win32EventHandler(WM_MOUSEMOVE) def _event_mousemove(self, msg, wParam, lParam): x, y = self._get_location(lParam) if (x, y) == self._exclusive_mouse_client: # Ignore the event caused by SetCursorPos self._mouse_x = x self._mouse_y = y return 0 y = self._height - y if self._exclusive_mouse and self._has_focus: # Reset mouse position (so we don't hit the edge of the screen). _x, _y = self._exclusive_mouse_screen self.set_mouse_position(_x, _y, absolute=True) dx = x - self._mouse_x dy = y - self._mouse_y if not self._tracking: # There is no WM_MOUSEENTER message (!), so fake it from the # first WM_MOUSEMOVE event after leaving. Use self._tracking # to determine when to recreate the tracking structure after # re-entering (to track the next WM_MOUSELEAVE). self._mouse_in_window = True self.set_mouse_platform_visible() self.dispatch_event('on_mouse_enter', x, y) self._tracking = True track = TRACKMOUSEEVENT() track.cbSize = sizeof(track) track.dwFlags = TME_LEAVE track.hwndTrack = self._view_hwnd _user32.TrackMouseEvent(byref(track)) # Don't generate motion/drag events when mouse hasn't moved. (Issue # 305) if self._mouse_x == x and self._mouse_y == y: return 0 self._mouse_x = x self._mouse_y = y buttons = 0 if wParam & MK_LBUTTON: buttons |= mouse.LEFT if wParam & MK_MBUTTON: buttons |= mouse.MIDDLE if wParam & MK_RBUTTON: buttons |= mouse.RIGHT if buttons: # Drag event modifiers = self._get_modifiers() self.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) else: # Motion event self.dispatch_event('on_mouse_motion', x, y, dx, dy) return 0 @ViewEventHandler @Win32EventHandler(WM_MOUSELEAVE) def _event_mouseleave(self, msg, wParam, lParam): point = POINT() _user32.GetCursorPos(byref(point)) _user32.ScreenToClient(self._view_hwnd, byref(point)) x = point.x y = self._height - point.y self._tracking = False self._mouse_in_window = False self.set_mouse_platform_visible() self.dispatch_event('on_mouse_leave', x, y) return 0 def _event_mousebutton(self, ev, button, lParam): if ev == 'on_mouse_press': _user32.SetCapture(self._view_hwnd) else: _user32.ReleaseCapture() x, y = self._get_location(lParam) y = self._height - y self.dispatch_event(ev, x, y, button, self._get_modifiers()) return 0 @ViewEventHandler @Win32EventHandler(WM_LBUTTONDOWN) def _event_lbuttondown(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_press', mouse.LEFT, lParam) @ViewEventHandler @Win32EventHandler(WM_LBUTTONUP) def _event_lbuttonup(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_release', mouse.LEFT, lParam) @ViewEventHandler @Win32EventHandler(WM_MBUTTONDOWN) def _event_mbuttondown(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_press', mouse.MIDDLE, lParam) @ViewEventHandler @Win32EventHandler(WM_MBUTTONUP) def _event_mbuttonup(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_release', mouse.MIDDLE, lParam) @ViewEventHandler @Win32EventHandler(WM_RBUTTONDOWN) def _event_rbuttondown(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_press', mouse.RIGHT, lParam) @ViewEventHandler @Win32EventHandler(WM_RBUTTONUP) def _event_rbuttonup(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_release', mouse.RIGHT, lParam) @Win32EventHandler(WM_MOUSEWHEEL) def _event_mousewheel(self, msg, wParam, lParam): delta = c_short(wParam >> 16).value self.dispatch_event('on_mouse_scroll', self._mouse_x, self._mouse_y, 0, delta / float(WHEEL_DELTA)) return 0 @Win32EventHandler(WM_CLOSE) def _event_close(self, msg, wParam, lParam): self.dispatch_event('on_close') return 0 @ViewEventHandler @Win32EventHandler(WM_PAINT) def _event_paint(self, msg, wParam, lParam): self.dispatch_event('on_expose') # Validating the window using ValidateRect or ValidateRgn # doesn't clear the paint message when more than one window # is open [why?]; defer to DefWindowProc instead. return None @Win32EventHandler(WM_SIZING) def _event_sizing(self, msg, wParam, lParam): #rect = cast(lParam, POINTER(RECT)).contents #width, height = self.get_size() from pyglet import app if app.event_loop is not None: app.event_loop.enter_blocking() return 1 @Win32EventHandler(WM_SIZE) def _event_size(self, msg, wParam, lParam): if not self._dc: # Ignore window creation size event (appears for fullscreen # only) -- we haven't got DC or HWND yet. return None if wParam == SIZE_MINIMIZED: # Minimized, not resized. self._hidden = True self.dispatch_event('on_hide') return 0 if self._hidden: # Restored self._hidden = False self.dispatch_event('on_show') w, h = self._get_location(lParam) if not self._fullscreen: self._width, self._height = w, h self._update_view_location(self._width, self._height) self._reset_exclusive_mouse_screen() self.switch_to() self.dispatch_event('on_resize', self._width, self._height) return 0 @Win32EventHandler(WM_SYSCOMMAND) def _event_syscommand(self, msg, wParam, lParam): if wParam & 0xfff0 in (SC_MOVE, SC_SIZE): # Should be in WM_ENTERSIZEMOVE, but we never get that message. from pyglet import app if app.event_loop is not None: app.event_loop.enter_blocking() return 0 @Win32EventHandler(WM_MOVE) def _event_move(self, msg, wParam, lParam): x, y = self._get_location(lParam) self._reset_exclusive_mouse_screen() self.dispatch_event('on_move', x, y) return 0 @Win32EventHandler(WM_EXITSIZEMOVE) def _event_entersizemove(self, msg, wParam, lParam): from pyglet import app if app.event_loop is not None: app.event_loop.exit_blocking() return 0 ''' # Alternative to using WM_SETFOCUS and WM_KILLFOCUS. Which # is better? @Win32EventHandler(WM_ACTIVATE) def _event_activate(self, msg, wParam, lParam): if wParam & 0xffff == WA_INACTIVE: self.dispatch_event('on_deactivate') else: self.dispatch_event('on_activate') _user32.SetFocus(self._hwnd) return 0 ''' @Win32EventHandler(WM_SETFOCUS) def _event_setfocus(self, msg, wParam, lParam): self.dispatch_event('on_activate') self._has_focus = True self.set_exclusive_keyboard(self._exclusive_keyboard) self.set_exclusive_mouse(self._exclusive_mouse) return 0 @Win32EventHandler(WM_KILLFOCUS) def _event_killfocus(self, msg, wParam, lParam): self.dispatch_event('on_deactivate') self._has_focus = False self.set_exclusive_keyboard(self._exclusive_keyboard) self.set_exclusive_mouse(self._exclusive_mouse) return 0 @Win32EventHandler(WM_GETMINMAXINFO) def _event_getminmaxinfo(self, msg, wParam, lParam): info = MINMAXINFO.from_address(lParam) if self._minimum_size: info.ptMinTrackSize.x, info.ptMinTrackSize.y = \ self._client_to_window_size(*self._minimum_size) if self._maximum_size: info.ptMaxTrackSize.x, info.ptMaxTrackSize.y = \ self._client_to_window_size(*self._maximum_size) return 0 @Win32EventHandler(WM_ERASEBKGND) def _event_erasebkgnd(self, msg, wParam, lParam): # Prevent flicker during resize; but erase bkgnd if we're fullscreen. if self._fullscreen: return 0 else: return 1 @ViewEventHandler @Win32EventHandler(WM_ERASEBKGND) def _event_erasebkgnd_view(self, msg, wParam, lParam): # Prevent flicker during resize. return 1
Python
from pyglet.window import key, mouse from pyglet.libs.darwin.quartzkey import keymap, charmap from pyglet.libs.darwin.cocoapy import * NSTrackingArea = ObjCClass('NSTrackingArea') # Event data helper functions. def getMouseDelta(nsevent): dx = nsevent.deltaX() dy = nsevent.deltaY() return int(dx), int(dy) def getMousePosition(self, nsevent): in_window = nsevent.locationInWindow() in_window = self.convertPoint_fromView_(in_window, None) x = int(in_window.x) y = int(in_window.y) # Must record mouse position for BaseWindow.draw_mouse_cursor to work. self._window._mouse_x = x self._window._mouse_y = y return x, y def getModifiers(nsevent): modifiers = 0 modifierFlags = nsevent.modifierFlags() if modifierFlags & NSAlphaShiftKeyMask: modifiers |= key.MOD_CAPSLOCK if modifierFlags & NSShiftKeyMask: modifiers |= key.MOD_SHIFT if modifierFlags & NSControlKeyMask: modifiers |= key.MOD_CTRL if modifierFlags & NSAlternateKeyMask: modifiers |= key.MOD_ALT modifiers |= key.MOD_OPTION if modifierFlags & NSCommandKeyMask: modifiers |= key.MOD_COMMAND if modifierFlags & NSFunctionKeyMask: modifiers |= key.MOD_FUNCTION return modifiers def getSymbol(nsevent): keycode = nsevent.keyCode() return keymap[keycode] class PygletView_Implementation(object): PygletView = ObjCSubclass('NSView', 'PygletView') @PygletView.method('@'+NSRectEncoding+PyObjectEncoding) def initWithFrame_cocoaWindow_(self, frame, window): # The tracking area is used to get mouseEntered, mouseExited, and cursorUpdate # events so that we can custom set the mouse cursor within the view. self._tracking_area = None self = ObjCInstance(send_super(self, 'initWithFrame:', frame, argtypes=[NSRect])) if not self: return None # CocoaWindow object. self._window = window self.updateTrackingAreas() # Create an instance of PygletTextView to handle text events. # We must do this because NSOpenGLView doesn't conform to the # NSTextInputClient protocol by default, and the insertText: method will # not do the right thing with respect to translating key sequences like # "Option-e", "e" if the protocol isn't implemented. So the easiest # thing to do is to subclass NSTextView which *does* implement the # protocol and let it handle text input. PygletTextView = ObjCClass('PygletTextView') self._textview = PygletTextView.alloc().initWithCocoaWindow_(window) # Add text view to the responder chain. self.addSubview_(self._textview) return self @PygletView.method('v') def dealloc(self): self._window = None #send_message(self.objc_self, 'removeFromSuperviewWithoutNeedingDisplay') self._textview.release() self._textview = None self._tracking_area.release() self._tracking_area = None send_super(self, 'dealloc') @PygletView.method('v') def updateTrackingAreas(self): # This method is called automatically whenever the tracking areas need to be # recreated, for example when window resizes. if self._tracking_area: self.removeTrackingArea_(self._tracking_area) self._tracking_area.release() self._tracking_area = None tracking_options = NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp | NSTrackingCursorUpdate frame = self.frame() self._tracking_area = NSTrackingArea.alloc().initWithRect_options_owner_userInfo_( frame, # rect tracking_options, # options self, # owner None) # userInfo self.addTrackingArea_(self._tracking_area) @PygletView.method('B') def canBecomeKeyView(self): return True @PygletView.method('B') def isOpaque(self): return True ## Event responders. # This method is called whenever the view changes size. @PygletView.method('v'+NSSizeEncoding) def setFrameSize_(self, size): send_super(self, 'setFrameSize:', size, argtypes=[NSSize]) # This method is called when view is first installed as the # contentView of window. Don't do anything on first call. # This also helps ensure correct window creation event ordering. if not self._window.context.canvas: return width, height = int(size.width), int(size.height) self._window.switch_to() self._window.context.update_geometry() self._window.dispatch_event("on_resize", width, height) self._window.dispatch_event("on_expose") # Can't get app.event_loop.enter_blocking() working with Cocoa, because # when mouse clicks on the window's resize control, Cocoa enters into a # mini-event loop that only responds to mouseDragged and mouseUp events. # This means that using NSTimer to call idle() won't work. Our kludge # is to override NSWindow's nextEventMatchingMask_etc method and call # idle() from there. if self.inLiveResize(): from pyglet import app if app.event_loop is not None: app.event_loop.idle() @PygletView.method('v@') def pygletKeyDown_(self, nsevent): symbol = getSymbol(nsevent) modifiers = getModifiers(nsevent) self._window.dispatch_event('on_key_press', symbol, modifiers) @PygletView.method('v@') def pygletKeyUp_(self, nsevent): symbol = getSymbol(nsevent) modifiers = getModifiers(nsevent) self._window.dispatch_event('on_key_release', symbol, modifiers) @PygletView.method('v@') def pygletFlagsChanged_(self, nsevent): # Handles on_key_press and on_key_release events for modifier keys. # Note that capslock is handled differently than other keys; it acts # as a toggle, so on_key_release is only sent when it's turned off. # TODO: Move these constants somewhere else. # Undocumented left/right modifier masks found by experimentation: NSLeftShiftKeyMask = 1 << 1 NSRightShiftKeyMask = 1 << 2 NSLeftControlKeyMask = 1 << 0 NSRightControlKeyMask = 1 << 13 NSLeftAlternateKeyMask = 1 << 5 NSRightAlternateKeyMask = 1 << 6 NSLeftCommandKeyMask = 1 << 3 NSRightCommandKeyMask = 1 << 4 maskForKey = { key.LSHIFT : NSLeftShiftKeyMask, key.RSHIFT : NSRightShiftKeyMask, key.LCTRL : NSLeftControlKeyMask, key.RCTRL : NSRightControlKeyMask, key.LOPTION : NSLeftAlternateKeyMask, key.ROPTION : NSRightAlternateKeyMask, key.LCOMMAND : NSLeftCommandKeyMask, key.RCOMMAND : NSRightCommandKeyMask, key.CAPSLOCK : NSAlphaShiftKeyMask, key.FUNCTION : NSFunctionKeyMask } symbol = getSymbol(nsevent) # Ignore this event if symbol is not a modifier key. We must check this # because e.g., we receive a flagsChanged message when using CMD-tab to # switch applications, with symbol == "a" when command key is released. if symbol not in maskForKey: return modifiers = getModifiers(nsevent) modifierFlags = nsevent.modifierFlags() if symbol and modifierFlags & maskForKey[symbol]: self._window.dispatch_event('on_key_press', symbol, modifiers) else: self._window.dispatch_event('on_key_release', symbol, modifiers) # Overriding this method helps prevent system beeps for unhandled events. @PygletView.method('B@') def performKeyEquivalent_(self, nsevent): # Let arrow keys and certain function keys pass through the responder # chain so that the textview can handle on_text_motion events. modifierFlags = nsevent.modifierFlags() if modifierFlags & NSNumericPadKeyMask: return False if modifierFlags & NSFunctionKeyMask: ch = cfstring_to_string(nsevent.charactersIgnoringModifiers()) if ch in (NSHomeFunctionKey, NSEndFunctionKey, NSPageUpFunctionKey, NSPageDownFunctionKey): return False # Send the key equivalent to the main menu to perform menu items. NSApp = ObjCClass('NSApplication').sharedApplication() NSApp.mainMenu().performKeyEquivalent_(nsevent) # Indicate that we've handled the event so system won't beep. return True @PygletView.method('v@') def mouseMoved_(self, nsevent): if self._window._mouse_ignore_motion: self._window._mouse_ignore_motion = False return # Don't send on_mouse_motion events if we're not inside the content rectangle. if not self._window._mouse_in_window: return x, y = getMousePosition(self, nsevent) dx, dy = getMouseDelta(nsevent) self._window.dispatch_event('on_mouse_motion', x, y, dx, dy) @PygletView.method('v@') def scrollWheel_(self, nsevent): x, y = getMousePosition(self, nsevent) scroll_x, scroll_y = getMouseDelta(nsevent) self._window.dispatch_event('on_mouse_scroll', x, y, scroll_x, scroll_y) @PygletView.method('v@') def mouseDown_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.LEFT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_press', x, y, buttons, modifiers) @PygletView.method('v@') def mouseDragged_(self, nsevent): x, y = getMousePosition(self, nsevent) dx, dy = getMouseDelta(nsevent) buttons = mouse.LEFT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) @PygletView.method('v@') def mouseUp_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.LEFT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_release', x, y, buttons, modifiers) @PygletView.method('v@') def rightMouseDown_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.RIGHT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_press', x, y, buttons, modifiers) @PygletView.method('v@') def rightMouseDragged_(self, nsevent): x, y = getMousePosition(self, nsevent) dx, dy = getMouseDelta(nsevent) buttons = mouse.RIGHT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) @PygletView.method('v@') def rightMouseUp_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.RIGHT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_release', x, y, buttons, modifiers) @PygletView.method('v@') def otherMouseDown_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.MIDDLE modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_press', x, y, buttons, modifiers) @PygletView.method('v@') def otherMouseDragged_(self, nsevent): x, y = getMousePosition(self, nsevent) dx, dy = getMouseDelta(nsevent) buttons = mouse.MIDDLE modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) @PygletView.method('v@') def otherMouseUp_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.MIDDLE modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_release', x, y, buttons, modifiers) @PygletView.method('v@') def mouseEntered_(self, nsevent): x, y = getMousePosition(self, nsevent) self._window._mouse_in_window = True # Don't call self._window.set_mouse_platform_visible() from here. # Better to do it from cursorUpdate: self._window.dispatch_event('on_mouse_enter', x, y) @PygletView.method('v@') def mouseExited_(self, nsevent): x, y = getMousePosition(self, nsevent) self._window._mouse_in_window = False if not self._window._is_mouse_exclusive: self._window.set_mouse_platform_visible() self._window.dispatch_event('on_mouse_leave', x, y) @PygletView.method('v@') def cursorUpdate_(self, nsevent): # Called when mouse cursor enters view. Unlike mouseEntered:, # this method will be called if the view appears underneath a # motionless mouse cursor, as can happen during window creation, # or when switching into fullscreen mode. # BUG: If the mouse enters the window via the resize control at the # the bottom right corner, the resize control will set the cursor # to the default arrow and screw up our cursor tracking. self._window._mouse_in_window = True if not self._window._is_mouse_exclusive: self._window.set_mouse_platform_visible() PygletView = ObjCClass('PygletView')
Python
from pyglet.libs.darwin.cocoapy import * # This class is a wrapper around NSCursor which prevents us from # sending too many hide or unhide messages in a row. Apparently # NSCursor treats them like retain/release messages, which can be # problematic when we are e.g. switching between window & fullscreen. class SystemCursor: cursor_is_hidden = False @classmethod def hide(cls): if not cls.cursor_is_hidden: send_message('NSCursor', 'hide') cls.cursor_is_hidden = True @classmethod def unhide(cls): if cls.cursor_is_hidden: send_message('NSCursor', 'unhide') cls.cursor_is_hidden = False
Python
import unicodedata from pyglet.window import key from pyglet.libs.darwin.cocoapy import * NSArray = ObjCClass('NSArray') NSApplication = ObjCClass('NSApplication') # This custom NSTextView subclass is used for capturing all of the # on_text, on_text_motion, and on_text_motion_select events. class PygletTextView_Implementation(object): PygletTextView = ObjCSubclass('NSTextView', 'PygletTextView') @PygletTextView.method('@'+PyObjectEncoding) def initWithCocoaWindow_(self, window): self = ObjCInstance(send_super(self, 'init')) if not self: return None self._window = window # Interpret tab and return as raw characters self.setFieldEditor_(False) self.empty_string = CFSTR("") return self @PygletTextView.method('v') def dealloc(self): self.empty_string.release() @PygletTextView.method('v@') def keyDown_(self, nsevent): array = NSArray.arrayWithObject_(nsevent) self.interpretKeyEvents_(array) @PygletTextView.method('v@') def insertText_(self, text): text = cfstring_to_string(text) self.setString_(self.empty_string) # Don't send control characters (tab, newline) as on_text events. if unicodedata.category(text[0]) != 'Cc': self._window.dispatch_event("on_text", text) @PygletTextView.method('v@') def insertNewline_(self, sender): # Distinguish between carriage return (u'\r') and enter (u'\x03'). # Only the return key press gets sent as an on_text event. event = NSApplication.sharedApplication().currentEvent() chars = event.charactersIgnoringModifiers() ch = unichr(chars.characterAtIndex_(0)) if ch == u'\r': self._window.dispatch_event("on_text", u'\r') @PygletTextView.method('v@') def moveUp_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_UP) @PygletTextView.method('v@') def moveDown_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_DOWN) @PygletTextView.method('v@') def moveLeft_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_LEFT) @PygletTextView.method('v@') def moveRight_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_RIGHT) @PygletTextView.method('v@') def moveWordLeft_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_PREVIOUS_WORD) @PygletTextView.method('v@') def moveWordRight_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_NEXT_WORD) @PygletTextView.method('v@') def moveToBeginningOfLine_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_BEGINNING_OF_LINE) @PygletTextView.method('v@') def moveToEndOfLine_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_END_OF_LINE) @PygletTextView.method('v@') def scrollPageUp_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_PREVIOUS_PAGE) @PygletTextView.method('v@') def scrollPageDown_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_NEXT_PAGE) @PygletTextView.method('v@') def scrollToBeginningOfDocument_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion", key.MOTION_BEGINNING_OF_FILE) @PygletTextView.method('v@') def scrollToEndOfDocument_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion", key.MOTION_END_OF_FILE) @PygletTextView.method('v@') def deleteBackward_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_BACKSPACE) @PygletTextView.method('v@') def deleteForward_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_DELETE) @PygletTextView.method('v@') def moveUpAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_UP) @PygletTextView.method('v@') def moveDownAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_DOWN) @PygletTextView.method('v@') def moveLeftAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_LEFT) @PygletTextView.method('v@') def moveRightAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_RIGHT) @PygletTextView.method('v@') def moveWordLeftAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_PREVIOUS_WORD) @PygletTextView.method('v@') def moveWordRightAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_NEXT_WORD) @PygletTextView.method('v@') def moveToBeginningOfLineAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_BEGINNING_OF_LINE) @PygletTextView.method('v@') def moveToEndOfLineAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_END_OF_LINE) @PygletTextView.method('v@') def pageUpAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_PREVIOUS_PAGE) @PygletTextView.method('v@') def pageDownAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_NEXT_PAGE) @PygletTextView.method('v@') def moveToBeginningOfDocumentAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_BEGINNING_OF_FILE) @PygletTextView.method('v@') def moveToEndOfDocumentAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_END_OF_FILE) PygletTextView = ObjCClass('PygletTextView')
Python
from pyglet.libs.darwin.cocoapy import * class PygletWindow_Implementation(object): PygletWindow = ObjCSubclass('NSWindow', 'PygletWindow') @PygletWindow.method('B') def canBecomeKeyWindow(self): return True # When the window is being resized, it enters into a mini event loop that # only looks at mouseDragged and mouseUp events, blocking everything else. # Among other things, this makes it impossible to run an NSTimer to call the # idle() function in order to update the view during the resize. So we # override this method, called by the resizing event loop, and call the # idle() function from here. This *almost* works. I can't figure out what # is happening at the very beginning of a resize event. The NSView's # viewWillStartLiveResize method is called and then nothing happens until # the mouse is dragged. I think NSApplication's nextEventMatchingMask_etc # method is being called instead of this one. I don't really feel like # subclassing NSApplication just to fix this. Also, to prevent white flashes # while resizing, we must also call idle() from the view's reshape method. @PygletWindow.method('@'+NSUIntegerEncoding+'@@B') def nextEventMatchingMask_untilDate_inMode_dequeue_(self, mask, date, mode, dequeue): if self.inLiveResize(): # Call the idle() method while we're stuck in a live resize event. from pyglet import app if app.event_loop is not None: app.event_loop.idle() event = send_super(self, 'nextEventMatchingMask:untilDate:inMode:dequeue:', mask, date, mode, dequeue, argtypes=[NSUInteger, c_void_p, c_void_p, c_bool]) if event.value == None: return 0 else: return event.value # Need this for set_size to not flash. @PygletWindow.method('d'+NSRectEncoding) def animationResizeTime_(self, newFrame): return 0.0 class PygletToolWindow_Implementation(object): PygletToolWindow = ObjCSubclass('NSPanel', 'PygletToolWindow') @PygletToolWindow.method('@'+NSUIntegerEncoding+'@@B') def nextEventMatchingMask_untilDate_inMode_dequeue_(self, mask, date, mode, dequeue): if self.inLiveResize(): # Call the idle() method while we're stuck in a live resize event. from pyglet import app if app.event_loop is not None: app.event_loop.idle() event = send_super(self, 'nextEventMatchingMask:untilDate:inMode:dequeue:', mask, date, mode, dequeue, argtypes=[NSUInteger, c_void_p, c_void_p, c_bool]) if event.value == None: return 0 else: return event.value # Need this for set_size to not flash. @PygletToolWindow.method('d'+NSRectEncoding) def animationResizeTime_(self, newFrame): return 0.0 PygletWindow = ObjCClass('PygletWindow') PygletToolWindow = ObjCClass('PygletToolWindow')
Python
from pyglet.libs.darwin.cocoapy import * from systemcursor import SystemCursor NSNotificationCenter = ObjCClass('NSNotificationCenter') NSApplication = ObjCClass('NSApplication') class PygletDelegate_Implementation(object): PygletDelegate = ObjCSubclass('NSObject', 'PygletDelegate') @PygletDelegate.method('@'+PyObjectEncoding) def initWithWindow_(self, window): self = ObjCInstance(send_super(self, 'init')) if not self: return None # CocoaWindow object. self._window = window window._nswindow.setDelegate_(self) # Register delegate for hide and unhide notifications so that we # can dispatch the corresponding pyglet events. notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver_selector_name_object_( self, get_selector('applicationDidHide:'), NSApplicationDidHideNotification, None) notificationCenter.addObserver_selector_name_object_( self, get_selector('applicationDidUnhide:'), NSApplicationDidUnhideNotification, None) # Flag set when we pause exclusive mouse mode if window loses key status. self.did_pause_exclusive_mouse = False return self @PygletDelegate.method('v') def dealloc(self): # Unregister delegate from notification center. notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver_(self) self._window = None send_super(self, 'dealloc') @PygletDelegate.method('v@') def applicationDidHide_(self, notification): self._window.dispatch_event("on_hide") @PygletDelegate.method('v@') def applicationDidUnhide_(self, notification): if self._window._is_mouse_exclusive and quartz.CGCursorIsVisible(): # The cursor should be hidden, but for some reason it's not; # try to force the cursor to hide (without over-hiding). SystemCursor.unhide() SystemCursor.hide() pass self._window.dispatch_event("on_show") @PygletDelegate.method('B@') def windowShouldClose_(self, notification): # The method is not called if [NSWindow close] was used. self._window.dispatch_event("on_close") return False @PygletDelegate.method('v@') def windowDidMove_(self, notification): x, y = self._window.get_location() self._window.dispatch_event("on_move", x, y) @PygletDelegate.method('v@') def windowDidBecomeKey_(self, notification): # Restore exclusive mouse mode if it was active before we lost key status. if self.did_pause_exclusive_mouse: self._window.set_exclusive_mouse(True) self.did_pause_exclusive_mouse = False self._window._nswindow.setMovable_(True) # Mac OS 10.6 # Restore previous mouse visibility settings. self._window.set_mouse_platform_visible() self._window.dispatch_event("on_activate") @PygletDelegate.method('v@') def windowDidResignKey_(self, notification): # Pause exclusive mouse mode if it is active. if self._window._is_mouse_exclusive: self._window.set_exclusive_mouse(False) self.did_pause_exclusive_mouse = True # We need to prevent the window from being unintentionally dragged # (by the call to set_mouse_position in set_exclusive_mouse) when # the window is reactivated by clicking on its title bar. self._window._nswindow.setMovable_(False) # Mac OS X 10.6 # Make sure that cursor is visible. self._window.set_mouse_platform_visible(True) self._window.dispatch_event("on_deactivate") @PygletDelegate.method('v@') def windowDidMiniaturize_(self, notification): self._window.dispatch_event("on_hide") @PygletDelegate.method('v@') def windowDidDeminiaturize_(self, notification): if self._window._is_mouse_exclusive and quartz.CGCursorIsVisible(): # The cursor should be hidden, but for some reason it's not; # try to force the cursor to hide (without over-hiding). SystemCursor.unhide() SystemCursor.hide() pass self._window.dispatch_event("on_show") @PygletDelegate.method('v@') def windowDidExpose_(self, notification): self._window.dispatch_event("on_expose") @PygletDelegate.method('v@') def terminate_(self, sender): NSApp = NSApplication.sharedApplication() NSApp.terminate_(self) @PygletDelegate.method('B@') def validateMenuItem_(self, menuitem): # Disable quitting with command-q when in keyboard exclusive mode. if menuitem.action() == get_selector('terminate:'): return not self._window._is_keyboard_exclusive return True PygletDelegate = ObjCClass('PygletDelegate')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * import pyglet from pyglet.window import BaseWindow, WindowException from pyglet.window import MouseCursor, DefaultMouseCursor from pyglet.event import EventDispatcher from pyglet.canvas.cocoa import CocoaCanvas from pyglet.libs.darwin.cocoapy import * from systemcursor import SystemCursor from pyglet_delegate import PygletDelegate from pyglet_textview import PygletTextView from pyglet_window import PygletWindow, PygletToolWindow from pyglet_view import PygletView NSApplication = ObjCClass('NSApplication') NSCursor = ObjCClass('NSCursor') NSAutoreleasePool = ObjCClass('NSAutoreleasePool') NSColor = ObjCClass('NSColor') NSEvent = ObjCClass('NSEvent') NSImage = ObjCClass('NSImage') class CocoaMouseCursor(MouseCursor): drawable = False def __init__(self, cursorName): # cursorName is a string identifying one of the named default NSCursors # e.g. 'pointingHandCursor', and can be sent as message to NSCursor class. self.cursorName = cursorName def set(self): cursor = getattr(NSCursor, self.cursorName)() cursor.set() class CocoaWindow(BaseWindow): # NSWindow instance. _nswindow = None # Delegate object. _delegate = None # Window properties _minimum_size = None _maximum_size = None _is_mouse_exclusive = False _mouse_platform_visible = True _mouse_ignore_motion = False _is_keyboard_exclusive = False # Flag set during close() method. _was_closed = False # NSWindow style masks. _style_masks = { BaseWindow.WINDOW_STYLE_DEFAULT: NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask, BaseWindow.WINDOW_STYLE_DIALOG: NSTitledWindowMask | NSClosableWindowMask, BaseWindow.WINDOW_STYLE_TOOL: NSTitledWindowMask | NSClosableWindowMask | NSUtilityWindowMask, BaseWindow.WINDOW_STYLE_BORDERLESS: NSBorderlessWindowMask, } def _recreate(self, changes): if ('context' in changes): self.context.set_current() if 'fullscreen' in changes: if not self._fullscreen: # leaving fullscreen self.screen.release_display() self._create() def _create(self): # Create a temporary autorelease pool for this method. pool = NSAutoreleasePool.alloc().init() if self._nswindow: # The window is about the be recreated so destroy everything # associated with the old window, then destroy the window itself. nsview = self.canvas.nsview self.canvas = None self._nswindow.orderOut_(None) self._nswindow.close() self.context.detach() self._nswindow.release() self._nswindow = None nsview.release() self._delegate.release() self._delegate = None # Determine window parameters. content_rect = NSMakeRect(0, 0, self._width, self._height) WindowClass = PygletWindow if self._fullscreen: style_mask = NSBorderlessWindowMask else: if self._style not in self._style_masks: self._style = self.WINDOW_STYLE_DEFAULT style_mask = self._style_masks[self._style] if self._resizable: style_mask |= NSResizableWindowMask if self._style == BaseWindow.WINDOW_STYLE_TOOL: WindowClass = PygletToolWindow # First create an instance of our NSWindow subclass. # FIX ME: # Need to use this initializer to have any hope of multi-monitor support. # But currently causes problems on Mac OS X Lion. So for now, we initialize the # window without including screen information. # # self._nswindow = WindowClass.alloc().initWithContentRect_styleMask_backing_defer_screen_( # content_rect, # contentRect # style_mask, # styleMask # NSBackingStoreBuffered, # backing # False, # defer # self.screen.get_nsscreen()) # screen self._nswindow = WindowClass.alloc().initWithContentRect_styleMask_backing_defer_( content_rect, # contentRect style_mask, # styleMask NSBackingStoreBuffered, # backing False) # defer if self._fullscreen: # BUG: I suspect that this doesn't do the right thing when using # multiple monitors (which would be to go fullscreen on the monitor # where the window is located). However I've no way to test. blackColor = NSColor.blackColor() self._nswindow.setBackgroundColor_(blackColor) self._nswindow.setOpaque_(True) self.screen.capture_display() self._nswindow.setLevel_(quartz.CGShieldingWindowLevel()) self.context.set_full_screen() self._center_window() else: self._set_nice_window_location() # Then create a view and set it as our NSWindow's content view. self._nsview = PygletView.alloc().initWithFrame_cocoaWindow_(content_rect, self) self._nswindow.setContentView_(self._nsview) self._nswindow.makeFirstResponder_(self._nsview) # Create a canvas with the view as its drawable and attach context to it. self.canvas = CocoaCanvas(self.display, self.screen, self._nsview) self.context.attach(self.canvas) # Configure the window. self._nswindow.setAcceptsMouseMovedEvents_(True) self._nswindow.setReleasedWhenClosed_(False) self._nswindow.useOptimizedDrawing_(True) self._nswindow.setPreservesContentDuringLiveResize_(False) # Set the delegate. self._delegate = PygletDelegate.alloc().initWithWindow_(self) # Configure CocoaWindow. self.set_caption(self._caption) if self._minimum_size is not None: self.set_minimum_size(*self._minimum_size) if self._maximum_size is not None: self.set_maximum_size(*self._maximum_size) self.context.update_geometry() self.switch_to() self.set_vsync(self._vsync) self.set_visible(self._visible) pool.drain() def _set_nice_window_location(self): # Construct a list of all visible windows that aren't us. visible_windows = [ win for win in pyglet.app.windows if win is not self and win._nswindow and win._nswindow.isVisible() ] # If there aren't any visible windows, then center this window. if not visible_windows: self._center_window() # Otherwise, cascade from last window in list. else: point = visible_windows[-1]._nswindow.cascadeTopLeftFromPoint_(NSZeroPoint) self._nswindow.cascadeTopLeftFromPoint_(point) def _center_window(self): # [NSWindow center] does not move the window to a true center position # and also always moves the window to the main display. x = self.screen.x + int((self.screen.width - self._width)/2) y = self.screen.y + int((self.screen.height - self._height)/2) self._nswindow.setFrameOrigin_(NSPoint(x, y)) def close(self): # If we've already gone through this once, don't do it again. if self._was_closed: return # Create a temporary autorelease pool for this method. pool = NSAutoreleasePool.new() # Restore cursor visibility self.set_mouse_platform_visible(True) self.set_exclusive_mouse(False) self.set_exclusive_keyboard(False) # Remove the delegate object if self._delegate: self._nswindow.setDelegate_(None) self._delegate.release() self._delegate = None # Remove window from display and remove its view. if self._nswindow: self._nswindow.orderOut_(None) self._nswindow.setContentView_(None) self._nswindow.close() # Restore screen mode. This also releases the display # if it was captured for fullscreen mode. self.screen.restore_mode() # Remove view from canvas and then remove canvas. if self.canvas: self.canvas.nsview.release() self.canvas.nsview = None self.canvas = None # Do this last, so that we don't see white flash # when exiting application from fullscreen mode. super(CocoaWindow, self).close() self._was_closed = True pool.drain() def switch_to(self): if self.context: self.context.set_current() def flip(self): self.draw_mouse_cursor() if self.context: self.context.flip() def dispatch_events(self): self._allow_dispatch_event = True # Process all pyglet events. self.dispatch_pending_events() event = True # Dequeue and process all of the pending Cocoa events. pool = NSAutoreleasePool.new() NSApp = NSApplication.sharedApplication() while event and self._nswindow and self._context: event = NSApp.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, None, NSEventTrackingRunLoopMode, True) if event: event_type = event.type() # Pass on all events. NSApp.sendEvent_(event) # And resend key events to special handlers. if event_type == NSKeyDown and not event.isARepeat(): NSApp.sendAction_to_from_(get_selector('pygletKeyDown:'), None, event) elif event_type == NSKeyUp: NSApp.sendAction_to_from_(get_selector('pygletKeyUp:'), None, event) elif event_type == NSFlagsChanged: NSApp.sendAction_to_from_(get_selector('pygletFlagsChanged:'), None, event) NSApp.updateWindows() pool.drain() self._allow_dispatch_event = False def dispatch_pending_events(self): while self._event_queue: event = self._event_queue.pop(0) EventDispatcher.dispatch_event(self, *event) def set_caption(self, caption): self._caption = caption if self._nswindow is not None: self._nswindow.setTitle_(get_NSString(caption)) def set_icon(self, *images): # Only use the biggest image from the list. max_image = images[0] for img in images: if img.width > max_image.width and img.height > max_image.height: max_image = img # Grab image data from pyglet image. image = max_image.get_image_data() format = 'ARGB' bytesPerRow = len(format) * image.width data = image.get_data(format, -bytesPerRow) # Use image data to create a data provider. # Using CGDataProviderCreateWithData crashes PyObjC 2.2b3, so we create # a CFDataRef object first and use it to create the data provider. cfdata = c_void_p(cf.CFDataCreate(None, data, len(data))) provider = c_void_p(quartz.CGDataProviderCreateWithCFData(cfdata)) colorSpace = c_void_p(quartz.CGColorSpaceCreateDeviceRGB()) # Then create a CGImage from the provider. cgimage = c_void_p(quartz.CGImageCreate( image.width, image.height, 8, 32, bytesPerRow, colorSpace, kCGImageAlphaFirst, provider, None, True, kCGRenderingIntentDefault)) if not cgimage: return cf.CFRelease(cfdata) quartz.CGDataProviderRelease(provider) quartz.CGColorSpaceRelease(colorSpace) # Turn the CGImage into an NSImage. size = NSMakeSize(image.width, image.height) nsimage = NSImage.alloc().initWithCGImage_size_(cgimage, size) if not nsimage: return # And finally set the app icon. NSApp = NSApplication.sharedApplication() NSApp.setApplicationIconImage_(nsimage) nsimage.release() def get_location(self): window_frame = self._nswindow.frame() rect = self._nswindow.contentRectForFrameRect_(window_frame) screen_frame = self._nswindow.screen().frame() screen_width = int(screen_frame.size.width) screen_height = int(screen_frame.size.height) return int(rect.origin.x), int(screen_height - rect.origin.y - rect.size.height) def set_location(self, x, y): window_frame = self._nswindow.frame() rect = self._nswindow.contentRectForFrameRect_(window_frame) screen_frame = self._nswindow.screen().frame() screen_width = int(screen_frame.size.width) screen_height = int(screen_frame.size.height) origin = NSPoint(x, screen_height - y - rect.size.height) self._nswindow.setFrameOrigin_(origin) def get_size(self): window_frame = self._nswindow.frame() rect = self._nswindow.contentRectForFrameRect_(window_frame) return int(rect.size.width), int(rect.size.height) def set_size(self, width, height): if self._fullscreen: raise WindowException('Cannot set size of fullscreen window.') self._width = max(1, int(width)) self._height = max(1, int(height)) # Move frame origin down so that top-left corner of window doesn't move. window_frame = self._nswindow.frame() rect = self._nswindow.contentRectForFrameRect_(window_frame) rect.origin.y += rect.size.height - self._height rect.size.width = self._width rect.size.height = self._height new_frame = self._nswindow.frameRectForContentRect_(rect) # The window background flashes when the frame size changes unless it's # animated, but we can set the window's animationResizeTime to zero. is_visible = self._nswindow.isVisible() self._nswindow.setFrame_display_animate_(new_frame, True, is_visible) def set_minimum_size(self, width, height): self._minimum_size = NSSize(width, height) if self._nswindow is not None: self._nswindow.setContentMinSize_(self._minimum_size) def set_maximum_size(self, width, height): self._maximum_size = NSSize(width, height) if self._nswindow is not None: self._nswindow.setContentMaxSize_(self._maximum_size) def activate(self): if self._nswindow is not None: NSApp = NSApplication.sharedApplication() NSApp.activateIgnoringOtherApps_(True) self._nswindow.makeKeyAndOrderFront_(None) def set_visible(self, visible=True): self._visible = visible if self._nswindow is not None: if visible: # Not really sure why on_resize needs to be here, # but it's what pyglet wants. self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_show') self.dispatch_event('on_expose') self._nswindow.makeKeyAndOrderFront_(None) else: self._nswindow.orderOut_(None) def minimize(self): self._mouse_in_window = False if self._nswindow is not None: self._nswindow.miniaturize_(None) def maximize(self): if self._nswindow is not None: self._nswindow.zoom_(None) def set_vsync(self, vsync): if pyglet.options['vsync'] is not None: vsync = pyglet.options['vsync'] self._vsync = vsync # _recreate depends on this if self.context: self.context.set_vsync(vsync) def _mouse_in_content_rect(self): # Returns true if mouse is inside the window's content rectangle. # Better to use this method to check manually rather than relying # on instance variables that may not be set correctly. point = NSEvent.mouseLocation() window_frame = self._nswindow.frame() rect = self._nswindow.contentRectForFrameRect_(window_frame) return foundation.NSMouseInRect(point, rect, False) def set_mouse_platform_visible(self, platform_visible=None): # When the platform_visible argument is supplied with a boolean, then this # method simply sets whether or not the platform mouse cursor is visible. if platform_visible is not None: if platform_visible: SystemCursor.unhide() else: SystemCursor.hide() # But if it has been called without an argument, it turns into # a completely different function. Now we are trying to figure out # whether or not the mouse *should* be visible, and if so, what it should # look like. else: # If we are in mouse exclusive mode, then hide the mouse cursor. if self._is_mouse_exclusive: SystemCursor.hide() # If we aren't inside the window, then always show the mouse # and make sure that it is the default cursor. elif not self._mouse_in_content_rect(): NSCursor.arrowCursor().set() SystemCursor.unhide() # If we are in the window, then what we do depends on both # the current pyglet-set visibility setting for the mouse and # the type of the mouse cursor. If the cursor has been hidden # in the window with set_mouse_visible() then don't show it. elif not self._mouse_visible: SystemCursor.hide() # If the mouse is set as a system-defined cursor, then we # need to set the cursor and show the mouse. # *** FIX ME *** elif isinstance(self._mouse_cursor, CocoaMouseCursor): self._mouse_cursor.set() SystemCursor.unhide() # If the mouse cursor is drawable, then it we need to hide # the system mouse cursor, so that the cursor can draw itself. elif self._mouse_cursor.drawable: SystemCursor.hide() # Otherwise, show the default cursor. else: NSCursor.arrowCursor().set() SystemCursor.unhide() def get_system_mouse_cursor(self, name): # It would make a lot more sense for most of this code to be # inside the CocoaMouseCursor class, but all of the CURSOR_xxx # constants are defined as properties of BaseWindow. if name == self.CURSOR_DEFAULT: return DefaultMouseCursor() cursors = { self.CURSOR_CROSSHAIR: 'crosshairCursor', self.CURSOR_HAND: 'pointingHandCursor', self.CURSOR_HELP: 'arrowCursor', self.CURSOR_NO: 'operationNotAllowedCursor', # Mac OS 10.6 self.CURSOR_SIZE: 'arrowCursor', self.CURSOR_SIZE_UP: 'resizeUpCursor', self.CURSOR_SIZE_UP_RIGHT: 'arrowCursor', self.CURSOR_SIZE_RIGHT: 'resizeRightCursor', self.CURSOR_SIZE_DOWN_RIGHT: 'arrowCursor', self.CURSOR_SIZE_DOWN: 'resizeDownCursor', self.CURSOR_SIZE_DOWN_LEFT: 'arrowCursor', self.CURSOR_SIZE_LEFT: 'resizeLeftCursor', self.CURSOR_SIZE_UP_LEFT: 'arrowCursor', self.CURSOR_SIZE_UP_DOWN: 'resizeUpDownCursor', self.CURSOR_SIZE_LEFT_RIGHT: 'resizeLeftRightCursor', self.CURSOR_TEXT: 'IBeamCursor', self.CURSOR_WAIT: 'arrowCursor', # No wristwatch cursor in Cocoa self.CURSOR_WAIT_ARROW: 'arrowCursor', # No wristwatch cursor in Cocoa } if name not in cursors: raise RuntimeError('Unknown cursor name "%s"' % name) return CocoaMouseCursor(cursors[name]) def set_mouse_position(self, x, y, absolute=False): if absolute: # If absolute, then x, y is given in global display coordinates # which sets (0,0) at top left corner of main display. It is possible # to warp the mouse position to a point inside of another display. quartz.CGWarpMouseCursorPosition(CGPoint(x,y)) else: # Window-relative coordinates: (x, y) are given in window coords # with (0,0) at bottom-left corner of window and y up. We find # which display the window is in and then convert x, y into local # display coords where (0,0) is now top-left of display and y down. screenInfo = self._nswindow.screen().deviceDescription() displayID = screenInfo.objectForKey_(get_NSString('NSScreenNumber')) displayID = displayID.intValue() displayBounds = quartz.CGDisplayBounds(displayID) frame = self._nswindow.frame() windowOrigin = frame.origin x += windowOrigin.x y = displayBounds.size.height - windowOrigin.y - y quartz.CGDisplayMoveCursorToPoint(displayID, NSPoint(x,y)) def set_exclusive_mouse(self, exclusive=True): self._is_mouse_exclusive = exclusive if exclusive: # Skip the next motion event, which would return a large delta. self._mouse_ignore_motion = True # Move mouse to center of window. frame = self._nswindow.frame() width, height = frame.size.width, frame.size.height self.set_mouse_position(width/2, height/2) quartz.CGAssociateMouseAndMouseCursorPosition(False) else: quartz.CGAssociateMouseAndMouseCursorPosition(True) # Update visibility of mouse cursor. self.set_mouse_platform_visible() def set_exclusive_keyboard(self, exclusive=True): # http://developer.apple.com/mac/library/technotes/tn2002/tn2062.html # http://developer.apple.com/library/mac/#technotes/KioskMode/ # BUG: System keys like F9 or command-tab are disabled, however # pyglet also does not receive key press events for them. # This flag is queried by window delegate to determine whether # the quit menu item is active. self._is_keyboard_exclusive = exclusive if exclusive: # "Be nice! Don't disable force-quit!" # -- Patrick Swayze, Road House (1989) options = NSApplicationPresentationHideDock | \ NSApplicationPresentationHideMenuBar | \ NSApplicationPresentationDisableProcessSwitching | \ NSApplicationPresentationDisableHideApplication else: options = NSApplicationPresentationDefault NSApp = NSApplication.sharedApplication() NSApp.setPresentationOptions_(options)
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Event dispatch framework. All objects that produce events in pyglet implement `EventDispatcher`, providing a consistent interface for registering and manipulating event handlers. A commonly used event dispatcher is `pyglet.window.Window`. Event types =========== For each event dispatcher there is a set of events that it dispatches; these correspond with the type of event handlers you can attach. Event types are identified by their name, for example, ''on_resize''. If you are creating a new class which implements `EventDispatcher`, you must call `EventDispatcher.register_event_type` for each event type. Attaching event handlers ======================== An event handler is simply a function or method. You can attach an event handler by setting the appropriate function on the instance:: def on_resize(width, height): # ... dispatcher.on_resize = on_resize There is also a convenience decorator that reduces typing:: @dispatcher.event def on_resize(width, height): # ... You may prefer to subclass and override the event handlers instead:: class MyDispatcher(DispatcherClass): def on_resize(self, width, height): # ... Event handler stack =================== When attaching an event handler to a dispatcher using the above methods, it replaces any existing handler (causing the original handler to no longer be called). Each dispatcher maintains a stack of event handlers, allowing you to insert an event handler "above" the existing one rather than replacing it. There are two main use cases for "pushing" event handlers: * Temporarily intercepting the events coming from the dispatcher by pushing a custom set of handlers onto the dispatcher, then later "popping" them all off at once. * Creating "chains" of event handlers, where the event propagates from the top-most (most recently added) handler to the bottom, until a handler takes care of it. Use `EventDispatcher.push_handlers` to create a new level in the stack and attach handlers to it. You can push several handlers at once:: dispatcher.push_handlers(on_resize, on_key_press) If your function handlers have different names to the events they handle, use keyword arguments:: dispatcher.push_handlers(on_resize=my_resize, on_key_press=my_key_press) After an event handler has processed an event, it is passed on to the next-lowest event handler, unless the handler returns `EVENT_HANDLED`, which prevents further propagation. To remove all handlers on the top stack level, use `EventDispatcher.pop_handlers`. Note that any handlers pushed onto the stack have precedence over the handlers set directly on the instance (for example, using the methods described in the previous section), regardless of when they were set. For example, handler ``foo`` is called before handler ``bar`` in the following example:: dispatcher.push_handlers(on_resize=foo) dispatcher.on_resize = bar Dispatching events ================== pyglet uses a single-threaded model for all application code. Event handlers are only ever invoked as a result of calling EventDispatcher.dispatch_events`. It is up to the specific event dispatcher to queue relevant events until they can be dispatched, at which point the handlers are called in the order the events were originally generated. This implies that your application runs with a main loop that continuously updates the application state and checks for new events:: while True: dispatcher.dispatch_events() # ... additional per-frame processing Not all event dispatchers require the call to ``dispatch_events``; check with the particular class documentation. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import inspect EVENT_HANDLED = True EVENT_UNHANDLED = None class EventException(Exception): '''An exception raised when an event handler could not be attached. ''' pass class EventDispatcher(object): '''Generic event dispatcher interface. See the module docstring for usage. ''' # Placeholder empty stack; real stack is created only if needed _event_stack = () @classmethod def register_event_type(cls, name): '''Register an event type with the dispatcher. Registering event types allows the dispatcher to validate event handler names as they are attached, and to search attached objects for suitable handlers. :Parameters: `name` : str Name of the event to register. ''' if not hasattr(cls, 'event_types'): cls.event_types = [] cls.event_types.append(name) return name def push_handlers(self, *args, **kwargs): '''Push a level onto the top of the handler stack, then attach zero or more event handlers. If keyword arguments are given, they name the event type to attach. Otherwise, a callable's `__name__` attribute will be used. Any other object may also be specified, in which case it will be searched for callables with event names. ''' # Create event stack if necessary if type(self._event_stack) is tuple: self._event_stack = [] # Place dict full of new handlers at beginning of stack self._event_stack.insert(0, {}) self.set_handlers(*args, **kwargs) def _get_handlers(self, args, kwargs): '''Implement handler matching on arguments for set_handlers and remove_handlers. ''' for object in args: if inspect.isroutine(object): # Single magically named function name = object.__name__ if name not in self.event_types: raise EventException('Unknown event "%s"' % name) yield name, object else: # Single instance with magically named methods for name in dir(object): if name in self.event_types: yield name, getattr(object, name) for name, handler in kwargs.items(): # Function for handling given event (no magic) if name not in self.event_types: raise EventException('Unknown event "%s"' % name) yield name, handler def set_handlers(self, *args, **kwargs): '''Attach one or more event handlers to the top level of the handler stack. See `push_handlers` for the accepted argument types. ''' # Create event stack if necessary if type(self._event_stack) is tuple: self._event_stack = [{}] for name, handler in self._get_handlers(args, kwargs): self.set_handler(name, handler) def set_handler(self, name, handler): '''Attach a single event handler. :Parameters: `name` : str Name of the event type to attach to. `handler` : callable Event handler to attach. ''' # Create event stack if necessary if type(self._event_stack) is tuple: self._event_stack = [{}] self._event_stack[0][name] = handler def pop_handlers(self): '''Pop the top level of event handlers off the stack. ''' assert self._event_stack and 'No handlers pushed' del self._event_stack[0] def remove_handlers(self, *args, **kwargs): '''Remove event handlers from the event stack. See `push_handlers` for the accepted argument types. All handlers are removed from the first stack frame that contains any of the given handlers. No error is raised if any handler does not appear in that frame, or if no stack frame contains any of the given handlers. If the stack frame is empty after removing the handlers, it is removed from the stack. Note that this interferes with the expected symmetry of `push_handlers` and `pop_handlers`. ''' handlers = list(self._get_handlers(args, kwargs)) # Find the first stack frame containing any of the handlers def find_frame(): for frame in self._event_stack: for name, handler in handlers: try: if frame[name] == handler: return frame except KeyError: pass frame = find_frame() # No frame matched; no error. if not frame: return # Remove each handler from the frame. for name, handler in handlers: try: if frame[name] == handler: del frame[name] except KeyError: pass # Remove the frame if it's empty. if not frame: self._event_stack.remove(frame) def remove_handler(self, name, handler): '''Remove a single event handler. The given event handler is removed from the first handler stack frame it appears in. The handler must be the exact same callable as passed to `set_handler`, `set_handlers` or `push_handlers`; and the name must match the event type it is bound to. No error is raised if the event handler is not set. :Parameters: `name` : str Name of the event type to remove. `handler` : callable Event handler to remove. ''' for frame in self._event_stack: try: if frame[name] is handler: del frame[name] break except KeyError: pass def dispatch_event(self, event_type, *args): '''Dispatch a single event to the attached handlers. The event is propagated to all handlers from from the top of the stack until one returns `EVENT_HANDLED`. This method should be used only by `EventDispatcher` implementors; applications should call the ``dispatch_events`` method. Since pyglet 1.2, the method returns `EVENT_HANDLED` if an event handler returned `EVENT_HANDLED` or `EVENT_UNHANDLED` if all events returned `EVENT_UNHANDLED`. If no matching event handlers are in the stack, ``False`` is returned. :Parameters: `event_type` : str Name of the event. `args` : sequence Arguments to pass to the event handler. :rtype: bool or None :return: (Since pyglet 1.2) `EVENT_HANDLED` if an event handler returned `EVENT_HANDLED`; `EVENT_UNHANDLED` if one or more event handlers were invoked but returned only `EVENT_UNHANDLED`; otherwise ``False``. In pyglet 1.1 and earler, the return value is always ``None``. ''' assert event_type in self.event_types, "%r not found in %r.event_types == %r" % (event_type, self, self.event_types) invoked = False # Search handler stack for matching event handlers for frame in list(self._event_stack): handler = frame.get(event_type, None) if handler: try: invoked = True if handler(*args): return EVENT_HANDLED except TypeError: self._raise_dispatch_exception(event_type, args, handler) # Check instance for an event handler if hasattr(self, event_type): try: invoked = True if getattr(self, event_type)(*args): return EVENT_HANDLED except TypeError: self._raise_dispatch_exception( event_type, args, getattr(self, event_type)) if invoked: return EVENT_UNHANDLED return False def _raise_dispatch_exception(self, event_type, args, handler): # A common problem in applications is having the wrong number of # arguments in an event handler. This is caught as a TypeError in # dispatch_event but the error message is obfuscated. # # Here we check if there is indeed a mismatch in argument count, # and construct a more useful exception message if so. If this method # doesn't find a problem with the number of arguments, the error # is re-raised as if we weren't here. n_args = len(args) # Inspect the handler handler_args, handler_varargs, _, handler_defaults = \ inspect.getargspec(handler) n_handler_args = len(handler_args) # Remove "self" arg from handler if it's a bound method if inspect.ismethod(handler) and handler.im_self: n_handler_args -= 1 # Allow *args varargs to overspecify arguments if handler_varargs: n_handler_args = max(n_handler_args, n_args) # Allow default values to overspecify arguments if (n_handler_args > n_args and handler_defaults and n_handler_args - len(handler_defaults) <= n_args): n_handler_args = n_args if n_handler_args != n_args: if inspect.isfunction(handler) or inspect.ismethod(handler): descr = '%s at %s:%d' % ( handler.func_name, handler.func_code.co_filename, handler.func_code.co_firstlineno) else: descr = repr(handler) raise TypeError( '%s event was dispatched with %d arguments, but ' 'handler %s has an incompatible function signature' % (event_type, len(args), descr)) else: raise def event(self, *args): '''Function decorator for an event handler. Usage:: win = window.Window() @win.event def on_resize(self, width, height): # ... or:: @win.event('on_resize') def foo(self, width, height): # ... ''' if len(args) == 0: # @window.event() def decorator(func): name = func.__name__ self.set_handler(name, func) return func return decorator elif inspect.isroutine(args[0]): # @window.event func = args[0] name = func.__name__ self.set_handler(name, func) return args[0] elif type(args[0]) in (str, unicode): # @window.event('on_resize') name = args[0] def decorator(func): self.set_handler(name, func) return func return decorator
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Get environment information useful for debugging. Intended usage is to create a file for bug reports, e.g.:: python -m pyglet.info > info.txt ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' _first_heading = True def _heading(heading): global _first_heading if not _first_heading: print else: _first_heading = False print heading print '-' * 78 def dump_python(): '''Dump Python version and environment to stdout.''' import os import sys print 'sys.version:', sys.version print 'sys.platform:', sys.platform print 'sys.maxint:', sys.maxint if sys.platform == 'darwin': try: from objc import __version__ as pyobjc_version print 'objc.__version__:', pyobjc_version except: print 'PyObjC not available' print 'os.getcwd():', os.getcwd() for key, value in os.environ.items(): if key.startswith('PYGLET_'): print "os.environ['%s']: %s" % (key, value) def dump_pyglet(): '''Dump pyglet version and options.''' import pyglet print 'pyglet.version:', pyglet.version print 'pyglet.__file__:', pyglet.__file__ for key, value in pyglet.options.items(): print "pyglet.options['%s'] = %r" % (key, value) def dump_window(): '''Dump display, window, screen and default config info.''' import pyglet.window platform = pyglet.window.get_platform() print 'platform:', repr(platform) display = platform.get_default_display() print 'display:', repr(display) screens = display.get_screens() for i, screen in enumerate(screens): print 'screens[%d]: %r' % (i, screen) window = pyglet.window.Window(visible=False) for key, value in window.config.get_gl_attributes(): print "config['%s'] = %r" % (key, value) print 'context:', repr(window.context) _heading('window.context._info') dump_gl(window.context) window.close() def dump_gl(context=None): '''Dump GL info.''' if context is not None: info = context.get_info() else: from pyglet.gl import gl_info as info print 'gl_info.get_version():', info.get_version() print 'gl_info.get_vendor():', info.get_vendor() print 'gl_info.get_renderer():', info.get_renderer() print 'gl_info.get_extensions():' extensions = list(info.get_extensions()) extensions.sort() for name in extensions: print ' ', name def dump_glu(): '''Dump GLU info.''' from pyglet.gl import glu_info print 'glu_info.get_version():', glu_info.get_version() print 'glu_info.get_extensions():' extensions = list(glu_info.get_extensions()) extensions.sort() for name in extensions: print ' ', name def dump_glx(): '''Dump GLX info.''' try: from pyglet.gl import glx_info except: print 'GLX not available.' return import pyglet window = pyglet.window.Window(visible=False) print 'context.is_direct():', window.context.is_direct() window.close() if not glx_info.have_version(1, 1): print 'Version: < 1.1' else: print 'glx_info.get_server_vendor():', glx_info.get_server_vendor() print 'glx_info.get_server_version():', glx_info.get_server_version() print 'glx_info.get_server_extensions():' for name in glx_info.get_server_extensions(): print ' ', name print 'glx_info.get_client_vendor():', glx_info.get_client_vendor() print 'glx_info.get_client_version():', glx_info.get_client_version() print 'glx_info.get_client_extensions():' for name in glx_info.get_client_extensions(): print ' ', name print 'glx_info.get_extensions():' for name in glx_info.get_extensions(): print ' ', name def dump_media(): '''Dump pyglet.media info.''' import pyglet.media print 'audio driver:', pyglet.media.get_audio_driver() def dump_avbin(): '''Dump AVbin info.''' try: import pyglet.media.avbin print 'Library:', pyglet.media.avbin.av print 'AVbin version:', pyglet.media.avbin.av.avbin_get_version() print 'FFmpeg revision:', \ pyglet.media.avbin.av.avbin_get_ffmpeg_revision() except: print 'AVbin not available.' def dump_al(): '''Dump OpenAL info.''' try: from pyglet.media.drivers import openal except: print 'OpenAL not available.' return print 'Library:', openal.al._lib driver = openal.create_audio_driver() print 'Version:', driver.get_version() print 'Extensions:' for extension in driver.get_extensions(): print ' ', extension def dump_wintab(): '''Dump WinTab info.''' try: from pyglet.input import wintab except: print 'WinTab not available.' return interface_name = wintab.get_interface_name() impl_version = wintab.get_implementation_version() spec_version = wintab.get_spec_version() print 'WinTab: %s %d.%d (Spec %d.%d)' % (interface_name, impl_version >> 8, impl_version & 0xff, spec_version >> 8, spec_version & 0xff) def _try_dump(heading, func): _heading(heading) try: func() except: import traceback traceback.print_exc() def dump(): '''Dump all information to stdout.''' _try_dump('Python', dump_python) _try_dump('pyglet', dump_pyglet) _try_dump('pyglet.window', dump_window) _try_dump('pyglet.gl.glu_info', dump_glu) _try_dump('pyglet.gl.glx_info', dump_glx) _try_dump('pyglet.media', dump_media) _try_dump('pyglet.media.avbin', dump_avbin) _try_dump('pyglet.media.drivers.openal', dump_al) _try_dump('pyglet.input.wintab', dump_wintab) if __name__ == '__main__': dump()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Precise framerate calculation, scheduling and framerate limiting. Measuring time ============== The `tick` and `get_fps` functions can be used in conjunction to fulfil most games' basic requirements:: from pyglet import clock while True: dt = clock.tick() # ... update and render ... print 'FPS is %f' % clock.get_fps() The ``dt`` value returned gives the number of seconds (as a float) since the last "tick". The `get_fps` function averages the framerate over a sliding window of approximately 1 second. (You can calculate the instantaneous framerate by taking the reciprocal of ``dt``). Always remember to `tick` the clock! Limiting frame-rate =================== The framerate can be limited:: clock.set_fps_limit(60) This causes `clock` to sleep during each `tick` in an attempt to keep the number of ticks (frames) per second below 60. The implementation uses platform-dependent high-resolution sleep functions to achieve better accuracy with busy-waiting than would be possible using just the `time` module. Scheduling ========== You can schedule a function to be called every time the clock is ticked:: def callback(dt): print '%f seconds since last callback' % dt clock.schedule(callback) The `schedule_interval` method causes a function to be called every "n" seconds:: clock.schedule_interval(callback, .5) # called twice a second The `schedule_once` method causes a function to be called once "n" seconds in the future:: clock.schedule_once(callback, 5) # called in 5 seconds All of the `schedule` methods will pass on any additional args or keyword args you specify to the callback function:: def animate(dt, velocity, sprite): sprite.position += dt * velocity clock.schedule(animate, velocity=5.0, sprite=alien) You can cancel a function scheduled with any of these methods using `unschedule`:: clock.unschedule(animate) Displaying FPS ============== The ClockDisplay class provides a simple FPS counter. You should create an instance of ClockDisplay once during the application's start up:: fps_display = clock.ClockDisplay() Call draw on the ClockDisplay object for each frame:: fps_display.draw() There are several options to change the font, color and text displayed within the __init__ method. Using multiple clocks ===================== The clock functions are all relayed to an instance of `Clock` which is initialised with the module. You can get this instance to use directly:: clk = clock.get_default() You can also replace the default clock with your own: myclk = clock.Clock() clock.set_default(myclk) Each clock maintains its own set of scheduled functions and FPS limiting/measurement. Each clock must be "ticked" separately. Multiple and derived clocks potentially allow you to separate "game-time" and "wall-time", or to synchronise your clock to an audio or video stream instead of the system clock. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import time import sys import ctypes import pyglet.lib if sys.platform in ('win32', 'cygwin'): # Win32 Sleep function is only 10-millisecond resolution, so instead # use a waitable timer object, which has up to 100-nanosecond resolution # (hardware and implementation dependent, of course). _kernel32 = ctypes.windll.kernel32 class _ClockBase(object): def __init__(self): self._timer = _kernel32.CreateWaitableTimerA(None, True, None) def sleep(self, microseconds): delay = ctypes.c_longlong(int(-microseconds * 10)) _kernel32.SetWaitableTimer(self._timer, ctypes.byref(delay), 0, ctypes.c_void_p(), ctypes.c_void_p(), False) _kernel32.WaitForSingleObject(self._timer, 0xffffffff) _default_time_function = time.clock else: _c = pyglet.lib.load_library('c', darwin='/usr/lib/libc.dylib') _c.usleep.argtypes = [ctypes.c_ulong] class _ClockBase(object): def sleep(self, microseconds): _c.usleep(int(microseconds)) _default_time_function = time.time class _ScheduledItem(object): __slots__ = ['func', 'args', 'kwargs'] def __init__(self, func, args, kwargs): self.func = func self.args = args self.kwargs = kwargs class _ScheduledIntervalItem(object): __slots__ = ['func', 'interval', 'last_ts', 'next_ts', 'args', 'kwargs'] def __init__(self, func, interval, last_ts, next_ts, args, kwargs): self.func = func self.interval = interval self.last_ts = last_ts self.next_ts = next_ts self.args = args self.kwargs = kwargs def _dummy_schedule_func(*args, **kwargs): '''Dummy function that does nothing, placed onto zombie scheduled items to ensure they have no side effect if already queued inside tick() method. ''' pass class Clock(_ClockBase): '''Class for calculating and limiting framerate, and for calling scheduled functions. ''' #: The minimum amount of time in seconds this clock will attempt to sleep #: for when framerate limiting. Higher values will increase the #: accuracy of the limiting but also increase CPU usage while #: busy-waiting. Lower values mean the process sleeps more often, but is #: prone to over-sleep and run at a potentially lower or uneven framerate #: than desired. MIN_SLEEP = 0.005 #: The amount of time in seconds this clock subtracts from sleep values #: to compensate for lazy operating systems. SLEEP_UNDERSHOOT = MIN_SLEEP - 0.001 # List of functions to call every tick. _schedule_items = None # List of schedule interval items kept in sort order. _schedule_interval_items = None # If True, a sleep(0) is inserted on every tick. _force_sleep = False def __init__(self, fps_limit=None, time_function=_default_time_function): '''Initialise a Clock, with optional framerate limit and custom time function. :Parameters: `fps_limit` : float If not None, the maximum allowable framerate. Defaults to None. Deprecated in pyglet 1.2. `time_function` : function Function to return the elapsed time of the application, in seconds. Defaults to time.time, but can be replaced to allow for easy time dilation effects or game pausing. ''' super(Clock, self).__init__() self.time = time_function self.next_ts = self.time() self.last_ts = None self.times = [] self.set_fps_limit(fps_limit) self.cumulative_time = 0 self._schedule_items = [] self._schedule_interval_items = [] def update_time(self): '''Get the elapsed time since the last call to `update_time`. This updates the clock's internal measure of time and returns the difference since the last update (or since the clock was created). :since: pyglet 1.2 :rtype: float :return: The number of seconds since the last `update_time`, or 0 if this was the first time it was called. ''' ts = self.time() if self.last_ts is None: delta_t = 0 else: delta_t = ts - self.last_ts self.times.insert(0, delta_t) if len(self.times) > self.window_size: self.cumulative_time -= self.times.pop() self.cumulative_time += delta_t self.last_ts = ts return delta_t def call_scheduled_functions(self, dt): '''Call scheduled functions that elapsed on the last `update_time`. :since: pyglet 1.2 :Parameters: dt : float The elapsed time since the last update to pass to each scheduled function. This is *not* used to calculate which functions have elapsed. :rtype: bool :return: True if any functions were called, otherwise False. ''' ts = self.last_ts result = False # Call functions scheduled for every frame # Dupe list just in case one of the items unchedules itself for item in list(self._schedule_items): result = True item.func(dt, *item.args, **item.kwargs) # Call all scheduled interval functions and reschedule for future. need_resort = False # Dupe list just in case one of the items unchedules itself for item in list(self._schedule_interval_items): if item.next_ts > ts: break result = True item.func(ts - item.last_ts, *item.args, **item.kwargs) if item.interval: # Try to keep timing regular, even if overslept this time; # but don't schedule in the past (which could lead to # infinitely-worsing error). item.next_ts = item.last_ts + item.interval item.last_ts = ts if item.next_ts <= ts: if ts - item.next_ts < 0.05: # Only missed by a little bit, keep the same schedule item.next_ts = ts + item.interval else: # Missed by heaps, do a soft reschedule to avoid # lumping everything together. item.next_ts = self._get_soft_next_ts(ts, item.interval) # Fake last_ts to avoid repeatedly over-scheduling in # future. Unfortunately means the next reported dt is # incorrect (looks like interval but actually isn't). item.last_ts = item.next_ts - item.interval need_resort = True else: item.next_ts = None # Remove finished one-shots. self._schedule_interval_items = \ [item for item in self._schedule_interval_items \ if item.next_ts is not None] if need_resort: # TODO bubble up changed items might be faster self._schedule_interval_items.sort(key=lambda a: a.next_ts) return result def tick(self, poll=False): '''Signify that one frame has passed. This will call any scheduled functions that have elapsed. :Parameters: `poll` : bool If True, the function will call any scheduled functions but will not sleep or busy-wait for any reason. Recommended for advanced applications managing their own sleep timers only. Since pyglet 1.1. :rtype: float :return: The number of seconds since the last "tick", or 0 if this was the first frame. ''' if poll: if self.period_limit: self.next_ts = self.next_ts + self.period_limit else: if self.period_limit: self._limit() if self._force_sleep: self.sleep(0) delta_t = self.update_time() self.call_scheduled_functions(delta_t) return delta_t def _limit(self): '''Sleep until the next frame is due. Called automatically by `tick` if a framerate limit has been set. This method uses several heuristics to determine whether to sleep or busy-wait (or both). ''' ts = self.time() # Sleep to just before the desired time sleeptime = self.get_sleep_time(False) while sleeptime - self.SLEEP_UNDERSHOOT > self.MIN_SLEEP: self.sleep(1000000 * (sleeptime - self.SLEEP_UNDERSHOOT)) sleeptime = self.get_sleep_time(False) # Busy-loop CPU to get closest to the mark sleeptime = self.next_ts - self.time() while sleeptime > 0: sleeptime = self.next_ts - self.time() if sleeptime < -2 * self.period_limit: # Missed the time by a long shot, let's reset the clock # print >> sys.stderr, 'Step %f' % -sleeptime self.next_ts = ts + 2 * self.period_limit else: # Otherwise keep the clock steady self.next_ts = self.next_ts + self.period_limit def get_sleep_time(self, sleep_idle): '''Get the time until the next item is scheduled. This method considers all scheduled items and the current ``fps_limit``, if any. Applications can choose to continue receiving updates at the maximum framerate during idle time (when no functions are scheduled), or they can sleep through their idle time and allow the CPU to switch to other processes or run in low-power mode. If `sleep_idle` is ``True`` the latter behaviour is selected, and ``None`` will be returned if there are no scheduled items. Otherwise, if `sleep_idle` is ``False``, a sleep time allowing the maximum possible framerate (considering ``fps_limit``) will be returned; or an earlier time if a scheduled function is ready. :Parameters: `sleep_idle` : bool If True, the application intends to sleep through its idle time; otherwise it will continue ticking at the maximum frame rate allowed. :rtype: float :return: Time until the next scheduled event in seconds, or ``None`` if there is no event scheduled. :since: pyglet 1.1 ''' if self._schedule_items or not sleep_idle: if not self.period_limit: return 0. else: wake_time = self.next_ts if self._schedule_interval_items: wake_time = min(wake_time, self._schedule_interval_items[0].next_ts) return max(wake_time - self.time(), 0.) if self._schedule_interval_items: return max(self._schedule_interval_items[0].next_ts - self.time(), 0) return None def set_fps_limit(self, fps_limit): '''Set the framerate limit. The framerate limit applies only when a function is scheduled for every frame. That is, the framerate limit can be exceeded by scheduling a function for a very small period of time. :Parameters: `fps_limit` : float Maximum frames per second allowed, or None to disable limiting. :deprecated: Use `pyglet.app.run` and `schedule_interval` instead. ''' if not fps_limit: self.period_limit = None else: self.period_limit = 1. / fps_limit self.window_size = fps_limit or 60 def get_fps_limit(self): '''Get the framerate limit. :rtype: float :return: The framerate limit previously set in the constructor or `set_fps_limit`, or None if no limit was set. ''' if self.period_limit: return 1. / self.period_limit else: return 0 def get_fps(self): '''Get the average FPS of recent history. The result is the average of a sliding window of the last "n" frames, where "n" is some number designed to cover approximately 1 second. :rtype: float :return: The measured frames per second. ''' if not self.cumulative_time: return 0 return len(self.times) / self.cumulative_time def schedule(self, func, *args, **kwargs): '''Schedule a function to be called every frame. The function should have a prototype that includes ``dt`` as the first argument, which gives the elapsed time, in seconds, since the last clock tick. Any additional arguments given to this function are passed on to the callback:: def callback(dt, *args, **kwargs): pass :Parameters: `func` : function The function to call each frame. ''' item = _ScheduledItem(func, args, kwargs) self._schedule_items.append(item) def _schedule_item(self, func, last_ts, next_ts, interval, *args, **kwargs): item = _ScheduledIntervalItem( func, interval, last_ts, next_ts, args, kwargs) # Insert in sort order for i, other in enumerate(self._schedule_interval_items): if other.next_ts is not None and other.next_ts > next_ts: self._schedule_interval_items.insert(i, item) break else: self._schedule_interval_items.append(item) def schedule_interval(self, func, interval, *args, **kwargs): '''Schedule a function to be called every `interval` seconds. Specifying an interval of 0 prevents the function from being called again (see `schedule` to call a function as often as possible). The callback function prototype is the same as for `schedule`. :Parameters: `func` : function The function to call when the timer lapses. `interval` : float The number of seconds to wait between each call. ''' last_ts = self.last_ts or self.next_ts # Schedule from now, unless now is sufficiently close to last_ts, in # which case use last_ts. This clusters together scheduled items that # probably want to be scheduled together. The old (pre 1.1.1) # behaviour was to always use self.last_ts, and not look at ts. The # new behaviour is needed because clock ticks can now be quite # irregular, and span several seconds. ts = self.time() if ts - last_ts > 0.2: last_ts = ts next_ts = last_ts + interval self._schedule_item(func, last_ts, next_ts, interval, *args, **kwargs) def schedule_interval_soft(self, func, interval, *args, **kwargs): '''Schedule a function to be called every `interval` seconds, beginning at a time that does not coincide with other scheduled events. This method is similar to `schedule_interval`, except that the clock will move the interval out of phase with other scheduled functions so as to distribute CPU more load evenly over time. This is useful for functions that need to be called regularly, but not relative to the initial start time. `pyglet.media` does this for scheduling audio buffer updates, which need to occur regularly -- if all audio updates are scheduled at the same time (for example, mixing several tracks of a music score, or playing multiple videos back simultaneously), the resulting load on the CPU is excessive for those intervals but idle outside. Using the soft interval scheduling, the load is more evenly distributed. Soft interval scheduling can also be used as an easy way to schedule graphics animations out of phase; for example, multiple flags waving in the wind. :since: pyglet 1.1 :Parameters: `func` : function The function to call when the timer lapses. `interval` : float The number of seconds to wait between each call. ''' last_ts = self.last_ts or self.next_ts # See schedule_interval ts = self.time() if ts - last_ts > 0.2: last_ts = ts next_ts = self._get_soft_next_ts(last_ts, interval) last_ts = next_ts - interval self._schedule_item(func, last_ts, next_ts, interval, *args, **kwargs) def _get_soft_next_ts(self, last_ts, interval): def taken(ts, e): '''Return True if the given time has already got an item scheduled nearby. ''' for item in self._schedule_interval_items: if item.next_ts is None: pass elif abs(item.next_ts - ts) <= e: return True elif item.next_ts > ts + e: return False return False # Binary division over interval: # # 0 interval # |--------------------------| # 5 3 6 2 7 4 8 1 Order of search # # i.e., first scheduled at interval, # then at interval/2 # then at interval/4 # then at interval*3/4 # then at ... # # Schedule is hopefully then evenly distributed for any interval, # and any number of scheduled functions. next_ts = last_ts + interval if not taken(next_ts, interval / 4): return next_ts dt = interval divs = 1 while True: next_ts = last_ts for i in range(divs - 1): next_ts += dt if not taken(next_ts, dt / 4): return next_ts dt /= 2 divs *= 2 # Avoid infinite loop in pathological case if divs > 16: return next_ts def schedule_once(self, func, delay, *args, **kwargs): '''Schedule a function to be called once after `delay` seconds. The callback function prototype is the same as for `schedule`. :Parameters: `func` : function The function to call when the timer lapses. `delay` : float The number of seconds to wait before the timer lapses. ''' last_ts = self.last_ts or self.next_ts # See schedule_interval ts = self.time() if ts - last_ts > 0.2: last_ts = ts next_ts = last_ts + delay self._schedule_item(func, last_ts, next_ts, 0, *args, **kwargs) def unschedule(self, func): '''Remove a function from the schedule. If the function appears in the schedule more than once, all occurrences are removed. If the function was not scheduled, no error is raised. :Parameters: `func` : function The function to remove from the schedule. ''' # First replace zombie items' func with a dummy func that does # nothing, in case the list has already been cloned inside tick(). # (Fixes issue 326). for item in self._schedule_items: if item.func == func: item.func = _dummy_schedule_func for item in self._schedule_interval_items: if item.func == func: item.func = _dummy_schedule_func # Now remove matching items from both schedule lists. self._schedule_items = \ [item for item in self._schedule_items \ if item.func is not _dummy_schedule_func] self._schedule_interval_items = \ [item for item in self._schedule_interval_items \ if item.func is not _dummy_schedule_func] # Default clock. _default = Clock() def set_default(default): '''Set the default clock to use for all module-level functions. By default an instance of `Clock` is used. :Parameters: `default` : `Clock` The default clock to use. ''' global _default _default = default def get_default(): '''Return the `Clock` instance that is used by all module-level clock functions. :rtype: `Clock` :return: The default clock. ''' return _default def tick(poll=False): '''Signify that one frame has passed on the default clock. This will call any scheduled functions that have elapsed. :Parameters: `poll` : bool If True, the function will call any scheduled functions but will not sleep or busy-wait for any reason. Recommended for advanced applications managing their own sleep timers only. Since pyglet 1.1. :rtype: float :return: The number of seconds since the last "tick", or 0 if this was the first frame. ''' return _default.tick(poll) def get_sleep_time(sleep_idle): '''Get the time until the next item is scheduled on the default clock. See `Clock.get_sleep_time` for details. :Parameters: `sleep_idle` : bool If True, the application intends to sleep through its idle time; otherwise it will continue ticking at the maximum frame rate allowed. :rtype: float :return: Time until the next scheduled event in seconds, or ``None`` if there is no event scheduled. :since: pyglet 1.1 ''' return _default.get_sleep_time(sleep_idle) def get_fps(): '''Return the current measured FPS of the default clock. :rtype: float ''' return _default.get_fps() def set_fps_limit(fps_limit): '''Set the framerate limit for the default clock. :Parameters: `fps_limit` : float Maximum frames per second allowed, or None to disable limiting. :deprecated: Use `pyglet.app.run` and `schedule_interval` instead. ''' _default.set_fps_limit(fps_limit) def get_fps_limit(): '''Get the framerate limit for the default clock. :return: The framerate limit previously set by `set_fps_limit`, or None if no limit was set. ''' return _default.get_fps_limit() def schedule(func, *args, **kwargs): '''Schedule 'func' to be called every frame on the default clock. The arguments passed to func are ``dt``, followed by any ``*args`` and ``**kwargs`` given here. :Parameters: `func` : function The function to call each frame. ''' _default.schedule(func, *args, **kwargs) def schedule_interval(func, interval, *args, **kwargs): '''Schedule 'func' to be called every 'interval' seconds on the default clock. The arguments passed to 'func' are 'dt' (time since last function call), followed by any ``*args`` and ``**kwargs`` given here. :Parameters: `func` : function The function to call when the timer lapses. `interval` : float The number of seconds to wait between each call. ''' _default.schedule_interval(func, interval, *args, **kwargs) def schedule_interval_soft(func, interval, *args, **kwargs): '''Schedule 'func' to be called every 'interval' seconds on the default clock, beginning at a time that does not coincide with other scheduled events. The arguments passed to 'func' are 'dt' (time since last function call), followed by any ``*args`` and ``**kwargs`` given here. :see: `Clock.schedule_interval_soft` :since: pyglet 1.1 :Parameters: `func` : function The function to call when the timer lapses. `interval` : float The number of seconds to wait between each call. ''' _default.schedule_interval_soft(func, interval, *args, **kwargs) def schedule_once(func, delay, *args, **kwargs): '''Schedule 'func' to be called once after 'delay' seconds (can be a float) on the default clock. The arguments passed to 'func' are 'dt' (time since last function call), followed by any ``*args`` and ``**kwargs`` given here. If no default clock is set, the func is queued and will be scheduled on the default clock as soon as it is created. :Parameters: `func` : function The function to call when the timer lapses. `delay` : float The number of seconds to wait before the timer lapses. ''' _default.schedule_once(func, delay, *args, **kwargs) def unschedule(func): '''Remove 'func' from the default clock's schedule. No error is raised if the func was never scheduled. :Parameters: `func` : function The function to remove from the schedule. ''' _default.unschedule(func) class ClockDisplay(object): '''Display current clock values, such as FPS. This is a convenience class for displaying diagnostics such as the framerate. See the module documentation for example usage. :Ivariables: `label` : `pyglet.font.Text` The label which is displayed. :deprecated: This class presents values that are often misleading, as they reflect the rate of clock ticks, not displayed framerate. Use pyglet.window.FPSDisplay instead. ''' def __init__(self, font=None, interval=0.25, format='%(fps).2f', color=(.5, .5, .5, .5), clock=None): '''Create a ClockDisplay. All parameters are optional. By default, a large translucent font will be used to display the FPS to two decimal places. :Parameters: `font` : `pyglet.font.Font` The font to format text in. `interval` : float The number of seconds between updating the display. `format` : str A format string describing the format of the text. This string is modulated with the dict ``{'fps' : fps}``. `color` : 4-tuple of float The color, including alpha, passed to ``glColor4f``. `clock` : `Clock` The clock which determines the time. If None, the default clock is used. ''' if clock is None: clock = _default self.clock = clock self.clock.schedule_interval(self.update_text, interval) if not font: from pyglet.font import load as load_font font = load_font('', 36, bold=True) import pyglet.font self.label = pyglet.font.Text(font, '', color=color, x=10, y=10) self.format = format def unschedule(self): '''Remove the display from its clock's schedule. `ClockDisplay` uses `Clock.schedule_interval` to periodically update its display label. Even if the ClockDisplay is not being used any more, its update method will still be scheduled, which can be a resource drain. Call this method to unschedule the update method and allow the ClockDisplay to be garbage collected. :since: pyglet 1.1 ''' self.clock.unschedule(self.update_text) def update_text(self, dt=0): '''Scheduled method to update the label text.''' fps = self.clock.get_fps() self.label.text = self.format % {'fps': fps} def draw(self): '''Method called each frame to render the label.''' self.label.draw() def test_clock(): import getopt test_seconds = 1 test_fps = 60 show_fps = False options, args = getopt.getopt(sys.argv[1:], 'vht:f:', ['time=', 'fps=', 'help']) for key, value in options: if key in ('-t', '--time'): test_seconds = float(value) elif key in ('-f', '--fps'): test_fps = float(value) elif key in ('-v'): show_fps = True elif key in ('-h', '--help'): print ('Usage: clock.py <options>\n' '\n' 'Options:\n' ' -t --time Number of seconds to run for.\n' ' -f --fps Target FPS.\n' '\n' 'Tests the clock module by measuring how close we can\n' 'get to the desired FPS by sleeping and busy-waiting.') sys.exit(0) set_fps_limit(test_fps) start = time.time() # Add one because first frame has no update interval. n_frames = int(test_seconds * test_fps + 1) print 'Testing %f FPS for %f seconds...' % (test_fps, test_seconds) for i in xrange(n_frames): tick() if show_fps: print get_fps() total_time = time.time() - start total_error = total_time - test_seconds print 'Total clock error: %f secs' % total_error print 'Total clock error / secs: %f secs/secs' % \ (total_error / test_seconds) # Not fair to add the extra frame in this calc, since no-one's interested # in the startup situation. print 'Average FPS: %f' % ((n_frames - 1) / total_time) if __name__ == '__main__': test_clock()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Group multiple small images into larger textures. This module is used by `pyglet.resource` to efficiently pack small images into larger textures. `TextureAtlas` maintains one texture; `TextureBin` manages a collection of atlases of a given size. Example usage:: # Load images from disk car_image = pyglet.image.load('car.png') boat_image = pyglet.image.load('boat.png') # Pack these images into one or more textures bin = TextureBin() car_texture = bin.add(car_image) boat_texture = bin.add(boat_image) The result of `TextureBin.add` is a `TextureRegion` containing the image. Once added, an image cannot be removed from a bin (or an atlas); nor can a list of images be obtained from a given bin or atlas -- it is the application's responsibility to keep track of the regions returned by the ``add`` methods. :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import pyglet class AllocatorException(Exception): '''The allocator does not have sufficient free space for the requested image size.''' pass class _Strip(object): def __init__(self, y, max_height): self.x = 0 self.y = y self.max_height = max_height self.y2 = y def add(self, width, height): assert width > 0 and height > 0 assert height <= self.max_height x, y = self.x, self.y self.x += width self.y2 = max(self.y + height, self.y2) return x, y def compact(self): self.max_height = self.y2 - self.y class Allocator(object): '''Rectangular area allocation algorithm. Initialise with a given ``width`` and ``height``, then repeatedly call `alloc` to retrieve free regions of the area and protect that area from future allocations. `Allocator` uses a fairly simple strips-based algorithm. It performs best when rectangles are allocated in decreasing height order. ''' def __init__(self, width, height): '''Create an `Allocator` of the given size. :Parameters: `width` : int Width of the allocation region. `height` : int Height of the allocation region. ''' assert width > 0 and height > 0 self.width = width self.height = height self.strips = [_Strip(0, height)] self.used_area = 0 def alloc(self, width, height): '''Get a free area in the allocator of the given size. After calling `alloc`, the requested area will no longer be used. If there is not enough room to fit the given area `AllocatorException` is raised. :Parameters: `width` : int Width of the area to allocate. `height` : int Height of the area to allocate. :rtype: int, int :return: The X and Y coordinates of the bottom-left corner of the allocated region. ''' for strip in self.strips: if self.width - strip.x >= width and strip.max_height >= height: self.used_area += width * height return strip.add(width, height) if self.width >= width and self.height - strip.y2 >= height: self.used_area += width * height strip.compact() newstrip = _Strip(strip.y2, self.height - strip.y2) self.strips.append(newstrip) return newstrip.add(width, height) raise AllocatorException('No more space in %r for box %dx%d' % ( self, width, height)) def get_usage(self): '''Get the fraction of area already allocated. This method is useful for debugging and profiling only. :rtype: float ''' return self.used_area / float(self.width * self.height) def get_fragmentation(self): '''Get the fraction of area that's unlikely to ever be used, based on current allocation behaviour. This method is useful for debugging and profiling only. :rtype: float ''' # The total unused area in each compacted strip is summed. if not self.strips: return 0. possible_area = self.strips[-1].y2 * self.width return 1.0 - self.used_area / float(possible_area) class TextureAtlas(object): '''Collection of images within a texture. ''' def __init__(self, width=256, height=256): '''Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. `height` : int Height of the underlying texture. ''' self.texture = pyglet.image.Texture.create( width, height, pyglet.gl.GL_RGBA, rectangle=True) self.allocator = Allocator(width, height) def add(self, img): '''Add an image to the atlas. This method will fail if the given image cannot be transferred directly to a texture (for example, if it is another texture). `ImageData` is the usual image type for this method. `AllocatorException` will be raised if there is no room in the atlas for the image. :Parameters: `img` : `AbstractImage` The image to add. :rtype: `TextureRegion` :return: The region of the atlas containing the newly added image. ''' x, y = self.allocator.alloc(img.width, img.height) self.texture.blit_into(img, x, y, 0) region = self.texture.get_region(x, y, img.width, img.height) return region class TextureBin(object): '''Collection of texture atlases. `TextureBin` maintains a collection of texture atlases, and creates new ones as necessary to accommodate images added to the bin. ''' def __init__(self, texture_width=256, texture_height=256): '''Create a texture bin for holding atlases of the given size. :Parameters: `texture_width` : int Width of texture atlases to create. `texture_height` : int Height of texture atlases to create. ''' self.atlases = [] self.texture_width = texture_width self.texture_height = texture_height def add(self, img): '''Add an image into this texture bin. This method calls `TextureAtlas.add` for the first atlas that has room for the image. `AllocatorException` is raised if the image exceeds the dimensions of ``texture_width`` and ``texture_height``. :Parameters: `img` : `AbstractImage` The image to add. :rtype: `TextureRegion` :return: The region of an atlas containing the newly added image. ''' for atlas in list(self.atlases): try: return atlas.add(img) except AllocatorException: # Remove atlases that are no longer useful (this is so their # textures can later be freed if the images inside them get # collected). if img.width < 64 and img.height < 64: self.atlases.remove(atlas) atlas = TextureAtlas(self.texture_width, self.texture_height) self.atlases.append(atlas) return atlas.add(img)
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Image load, capture and high-level texture functions. Only basic functionality is described here; for full reference see the accompanying documentation. To load an image:: from pyglet import image pic = image.load('picture.png') The supported image file types include PNG, BMP, GIF, JPG, and many more, somewhat depending on the operating system. To load an image from a file-like object instead of a filename:: pic = image.load('hint.jpg', file=fileobj) The hint helps the module locate an appropriate decoder to use based on the file extension. It is optional. Once loaded, images can be used directly by most other modules of pyglet. All images have a width and height you can access:: width, height = pic.width, pic.height You can extract a region of an image (this keeps the original image intact; the memory is shared efficiently):: subimage = pic.get_region(x, y, width, height) Remember that y-coordinates are always increasing upwards. Drawing images -------------- To draw an image at some point on the screen:: pic.blit(x, y, z) This assumes an appropriate view transform and projection have been applied. Some images have an intrinsic "anchor point": this is the point which will be aligned to the ``x`` and ``y`` coordinates when the image is drawn. By default the anchor point is the lower-left corner of the image. You can use the anchor point to center an image at a given point, for example:: pic.anchor_x = pic.width // 2 pic.anchor_y = pic.height // 2 pic.blit(x, y, z) Texture access -------------- If you are using OpenGL directly, you can access the image as a texture:: texture = pic.get_texture() (This is the most efficient way to obtain a texture; some images are immediately loaded as textures, whereas others go through an intermediate form). To use a texture with pyglet.gl:: from pyglet.gl import * glEnable(texture.target) # typically target is GL_TEXTURE_2D glBindTexture(texture.target, texture.id) # ... draw with the texture Pixel access ------------ To access raw pixel data of an image:: rawimage = pic.get_image_data() (If the image has just been loaded this will be a very quick operation; however if the image is a texture a relatively expensive readback operation will occur). The pixels can be accessed as a string:: format = 'RGBA' pitch = rawimage.width * len(format) pixels = rawimage.get_data(format, pitch) "format" strings consist of characters that give the byte order of each color component. For example, if rawimage.format is 'RGBA', there are four color components: red, green, blue and alpha, in that order. Other common format strings are 'RGB', 'LA' (luminance, alpha) and 'I' (intensity). The "pitch" of an image is the number of bytes in a row (this may validly be more than the number required to make up the width of the image, it is common to see this for word alignment). If "pitch" is negative the rows of the image are ordered from top to bottom, otherwise they are ordered from bottom to top. Retrieving data with the format and pitch given in `ImageData.format` and `ImageData.pitch` avoids the need for data conversion (assuming you can make use of the data in this arbitrary format). ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import sys import re import warnings import weakref from ctypes import * from math import ceil from StringIO import StringIO from pyglet import gl from pyglet.gl import * from pyglet.gl import gl_info from pyglet import graphics from pyglet.window import * from pyglet.image import atlas from pyglet.compat import asbytes, bytes_type class ImageException(Exception): pass def load(filename, file=None, decoder=None): '''Load an image from a file. :note: You can make no assumptions about the return type; usually it will be ImageData or CompressedImageData, but decoders are free to return any subclass of AbstractImage. :Parameters: `filename` : str Used to guess the image format, and to load the file if `file` is unspecified. `file` : file-like object or None Source of image data in any supported format. `decoder` : ImageDecoder or None If unspecified, all decoders that are registered for the filename extension are tried. If none succeed, the exception from the first decoder is raised. :rtype: AbstractImage ''' if not file: file = open(filename, 'rb') if not hasattr(file, 'seek'): file = StringIO(file.read()) if decoder: return decoder.decode(file, filename) else: first_exception = None for decoder in codecs.get_decoders(filename): try: image = decoder.decode(file, filename) return image except codecs.ImageDecodeException, e: if (not first_exception or first_exception.exception_priority < e.exception_priority): first_exception = e file.seek(0) if not first_exception: raise codecs.ImageDecodeException('No image decoders are available') raise first_exception def create(width, height, pattern=None): '''Create an image optionally filled with the given pattern. :note: You can make no assumptions about the return type; usually it will be ImageData or CompressedImageData, but patterns are free to return any subclass of AbstractImage. :Parameters: `width` : int Width of image to create `height` : int Height of image to create `pattern` : ImagePattern or None Pattern to fill image with. If unspecified, the image will initially be transparent. :rtype: AbstractImage ''' if not pattern: pattern = SolidColorImagePattern() return pattern.create_image(width, height) class ImagePattern(object): '''Abstract image creation class.''' def create_image(self, width, height): '''Create an image of the given size. :Parameters: `width` : int Width of image to create `height` : int Height of image to create :rtype: AbstractImage ''' raise NotImplementedError('abstract') class SolidColorImagePattern(ImagePattern): '''Creates an image filled with a solid color.''' def __init__(self, color=(0, 0, 0, 0)): '''Create a solid image pattern with the given color. :Parameters: `color` : (int, int, int, int) 4-tuple of ints in range [0,255] giving RGBA components of color to fill with. ''' self.color = '%c%c%c%c' % color def create_image(self, width, height): data = self.color * width * height return ImageData(width, height, 'RGBA', data) class CheckerImagePattern(ImagePattern): '''Create an image with a tileable checker image. ''' def __init__(self, color1=(150,150,150,255), color2=(200,200,200,255)): '''Initialise with the given colors. :Parameters: `color1` : (int, int, int, int) 4-tuple of ints in range [0,255] giving RGBA components of color to fill with. This color appears in the top-left and bottom-right corners of the image. `color2` : (int, int, int, int) 4-tuple of ints in range [0,255] giving RGBA components of color to fill with. This color appears in the top-right and bottom-left corners of the image. ''' self.color1 = '%c%c%c%c' % color1 self.color2 = '%c%c%c%c' % color2 def create_image(self, width, height): hw = width // 2 hh = height // 2 row1 = self.color1 * hw + self.color2 * hw row2 = self.color2 * hw + self.color1 * hw data = row1 * hh + row2 * hh return ImageData(width, height, 'RGBA', data) class AbstractImage(object): '''Abstract class representing an image. :Ivariables: `width` : int Width of image `height` : int Height of image `anchor_x` : int X coordinate of anchor, relative to left edge of image data `anchor_y` : int Y coordinate of anchor, relative to bottom edge of image data ''' anchor_x = 0 anchor_y = 0 _is_rectangle = False def __init__(self, width, height): self.width = width self.height = height def __repr__(self): return '<%s %dx%d>' % (self.__class__.__name__, self.width, self.height) def get_image_data(self): '''Get an ImageData view of this image. Changes to the returned instance may or may not be reflected in this image. :rtype: `ImageData` :since: pyglet 1.1 ''' raise ImageException('Cannot retrieve image data for %r' % self) image_data = property(lambda self: self.get_image_data(), doc='''An `ImageData` view of this image. Changes to the returned instance may or may not be reflected in this image. Read-only. :deprecated: Use `get_image_data`. :type: `ImageData` ''') def get_texture(self, rectangle=False, force_rectangle=False): '''A `Texture` view of this image. By default, textures are created with dimensions that are powers of two. Smaller images will return a `TextureRegion` that covers just the image portion of the larger texture. This restriction is required on older video cards, and for compressed textures, or where texture repeat modes will be used, or where mipmapping is desired. If the `rectangle` parameter is ``True``, this restriction is ignored and a texture the size of the image may be created if the driver supports the ``GL_ARB_texture_rectangle`` or ``GL_NV_texture_rectangle`` extensions. If the extensions are not present, the image already is a texture, or the image has power 2 dimensions, the `rectangle` parameter is ignored. Examine `Texture.target` to determine if the returned texture is a rectangle (``GL_TEXTURE_RECTANGLE_ARB`` or ``GL_TEXTURE_RECTANGLE_NV``) or not (``GL_TEXTURE_2D``). If the `force_rectangle` parameter is ``True``, one of these extensions must be present, and the returned texture always has target ``GL_TEXTURE_RECTANGLE_ARB`` or ``GL_TEXTURE_RECTANGLE_NV``. Changes to the returned instance may or may not be reflected in this image. :Parameters: `rectangle` : bool True if the texture can be created as a rectangle. `force_rectangle` : bool True if the texture must be created as a rectangle. **Since:** pyglet 1.1.4. :rtype: `Texture` :since: pyglet 1.1 ''' raise ImageException('Cannot retrieve texture for %r' % self) texture = property(lambda self: self.get_texture(), doc='''Get a `Texture` view of this image. Changes to the returned instance may or may not be reflected in this image. :deprecated: Use `get_texture`. :type: `Texture` ''') def get_mipmapped_texture(self): '''Retrieve a `Texture` instance with all mipmap levels filled in. Requires that image dimensions be powers of 2. :rtype: `Texture` :since: pyglet 1.1 ''' raise ImageException('Cannot retrieve mipmapped texture for %r' % self) mipmapped_texture = property(lambda self: self.get_mipmapped_texture(), doc='''A Texture view of this image. The returned Texture will have mipmaps filled in for all levels. Requires that image dimensions be powers of 2. Read-only. :deprecated: Use `get_mipmapped_texture`. :type: `Texture` ''') def get_region(self, x, y, width, height): '''Retrieve a rectangular region of this image. :Parameters: `x` : int Left edge of region. `y` : int Bottom edge of region. `width` : int Width of region. `height` : int Height of region. :rtype: AbstractImage ''' raise ImageException('Cannot get region for %r' % self) def save(self, filename=None, file=None, encoder=None): '''Save this image to a file. :Parameters: `filename` : str Used to set the image file format, and to open the output file if `file` is unspecified. `file` : file-like object or None File to write image data to. `encoder` : ImageEncoder or None If unspecified, all encoders matching the filename extension are tried. If all fail, the exception from the first one attempted is raised. ''' if not file: file = open(filename, 'wb') if encoder: encoder.encode(self, file, filename) else: first_exception = None for encoder in codecs.get_encoders(filename): try: encoder.encode(self, file, filename) return except codecs.ImageDecodeException, e: first_exception = first_exception or e file.seek(0) if not first_exception: raise codecs.ImageEncodeException( 'No image encoders are available') raise first_exception def blit(self, x, y, z=0): '''Draw this image to the active framebuffers. The image will be drawn with the lower-left corner at (``x -`` `anchor_x`, ``y -`` `anchor_y`, ``z``). ''' raise ImageException('Cannot blit %r.' % self) def blit_into(self, source, x, y, z): '''Draw `source` on this image. `source` will be copied into this image such that its anchor point is aligned with the `x` and `y` parameters. If this image is a 3D texture, the `z` coordinate gives the image slice to copy into. Note that if `source` is larger than this image (or the positioning would cause the copy to go out of bounds) then you must pass a region of `source` to this method, typically using get_region(). ''' raise ImageException('Cannot blit images onto %r.' % self) def blit_to_texture(self, target, level, x, y, z=0): '''Draw this image on the currently bound texture at `target`. This image is copied into the texture such that this image's anchor point is aligned with the given `x` and `y` coordinates of the destination texture. If the currently bound texture is a 3D texture, the `z` coordinate gives the image slice to blit into. ''' raise ImageException('Cannot blit %r to a texture.' % self) class AbstractImageSequence(object): '''Abstract sequence of images. The sequence is useful for storing image animations or slices of a volume. For efficient access, use the `texture_sequence` member. The class also implements the sequence interface (`__len__`, `__getitem__`, `__setitem__`). ''' def get_texture_sequence(self): '''Get a TextureSequence. :rtype: `TextureSequence` :since: pyglet 1.1 ''' raise NotImplementedError('abstract') texture_sequence = property(lambda self: self.get_texture_sequence(), doc='''Access this image sequence as a texture sequence. :deprecated: Use `get_texture_sequence` :type: `TextureSequence` ''') def get_animation(self, period, loop=True): '''Create an animation over this image sequence for the given constant framerate. :Parameters `period` : float Number of seconds to display each frame. `loop` : bool If True, the animation will loop continuously. :rtype: `Animation` :since: pyglet 1.1 ''' return Animation.from_image_sequence(self, period, loop) def __getitem__(self, slice): '''Retrieve a (list of) image. :rtype: AbstractImage ''' raise NotImplementedError('abstract') def __setitem__(self, slice, image): '''Replace one or more images in the sequence. :Parameters: `image` : `AbstractImage` The replacement image. The actual instance may not be used, depending on this implementation. ''' raise NotImplementedError('abstract') def __len__(self): raise NotImplementedError('abstract') def __iter__(self): '''Iterate over the images in sequence. :rtype: Iterator :since: pyglet 1.1 ''' raise NotImplementedError('abstract') class TextureSequence(AbstractImageSequence): '''Interface for a sequence of textures. Typical implementations store multiple `TextureRegion` s within one `Texture` so as to minimise state changes. ''' def get_texture_sequence(self): return self class UniformTextureSequence(TextureSequence): '''Interface for a sequence of textures, each with the same dimensions. :Ivariables: `item_width` : int Width of each texture in the sequence. `item_height` : int Height of each texture in the sequence. ''' def _get_item_width(self): raise NotImplementedError('abstract') item_width = property(_get_item_width) def _get_item_height(self): raise NotImplementedError('abstract') item_height = property(_get_item_height) class ImageData(AbstractImage): '''An image represented as a string of unsigned bytes. :Ivariables: `data` : str Pixel data, encoded according to `format` and `pitch`. `format` : str The format string to use when reading or writing `data`. `pitch` : int Number of bytes per row. Negative values indicate a top-to-bottom arrangement. Setting the `format` and `pitch` instance variables and reading `data` is deprecated; use `get_data` and `set_data` in new applications. (Reading `format` and `pitch` to obtain the current encoding is not deprecated). ''' _swap1_pattern = re.compile(asbytes('(.)'), re.DOTALL) _swap2_pattern = re.compile(asbytes('(.)(.)'), re.DOTALL) _swap3_pattern = re.compile(asbytes('(.)(.)(.)'), re.DOTALL) _swap4_pattern = re.compile(asbytes('(.)(.)(.)(.)'), re.DOTALL) _current_texture = None _current_mipmap_texture = None def __init__(self, width, height, format, data, pitch=None): '''Initialise image data. :Parameters: `width` : int Width of image data `height` : int Height of image data `format` : str A valid format string, such as 'RGB', 'RGBA', 'ARGB', etc. `data` : sequence String or array/list of bytes giving the decoded data. `pitch` : int or None If specified, the number of bytes per row. Negative values indicate a top-to-bottom arrangement. Defaults to ``width * len(format)``. ''' super(ImageData, self).__init__(width, height) self._current_format = self._desired_format = format.upper() self._current_data = data if not pitch: pitch = width * len(format) self._current_pitch = self.pitch = pitch self.mipmap_images = [] def __getstate__(self): return { 'width': self.width, 'height': self.height, '_current_data': self.get_data(self._current_format, self._current_pitch), '_current_format': self._current_format, '_desired_format': self._desired_format, '_current_pitch': self._current_pitch, 'pitch': self.pitch, 'mipmap_images': self.mipmap_images } def get_image_data(self): return self def _set_format(self, format): self._desired_format = format.upper() self._current_texture = None format = property(lambda self: self._desired_format, _set_format, doc='''Format string of the data. Read-write. :type: str ''') def _get_data(self): if self._current_pitch != self.pitch or \ self._current_format != self.format: self._current_data = self._convert(self.format, self.pitch) self._current_format = self.format self._current_pitch = self.pitch self._ensure_string_data() return self._current_data def _set_data(self, data): self._current_data = data self._current_format = self.format self._current_pitch = self.pitch self._current_texture = None self._current_mipmapped_texture = None data = property(_get_data, _set_data, doc='''The byte data of the image. Read-write. :deprecated: Use `get_data` and `set_data`. :type: sequence of bytes, or str ''') def get_data(self, format, pitch): '''Get the byte data of the image. :Parameters: `format` : str Format string of the return data. `pitch` : int Number of bytes per row. Negative values indicate a top-to-bottom arrangement. :since: pyglet 1.1 :rtype: sequence of bytes, or str ''' if format == self._current_format and pitch == self._current_pitch: return self._current_data return self._convert(format, pitch) def set_data(self, format, pitch, data): '''Set the byte data of the image. :Parameters: `format` : str Format string of the return data. `pitch` : int Number of bytes per row. Negative values indicate a top-to-bottom arrangement. `data` : str or sequence of bytes Image data. :since: pyglet 1.1 ''' self._current_format = format self._current_pitch = pitch self._current_data = data self._current_texture = None self._current_mipmapped_texture = None def set_mipmap_image(self, level, image): '''Set a mipmap image for a particular level. The mipmap image will be applied to textures obtained via `get_mipmapped_texture`. :Parameters: `level` : int Mipmap level to set image at, must be >= 1. `image` : AbstractImage Image to set. Must have correct dimensions for that mipmap level (i.e., width >> level, height >> level) ''' if level == 0: raise ImageException( 'Cannot set mipmap image at level 0 (it is this image)') if not _is_pow2(self.width) or not _is_pow2(self.height): raise ImageException( 'Image dimensions must be powers of 2 to use mipmaps.') # Check dimensions of mipmap width, height = self.width, self.height for i in range(level): width >>= 1 height >>= 1 if width != image.width or height != image.height: raise ImageException( 'Mipmap image has wrong dimensions for level %d' % level) # Extend mipmap_images list to required level self.mipmap_images += [None] * (level - len(self.mipmap_images)) self.mipmap_images[level - 1] = image def create_texture(self, cls, rectangle=False, force_rectangle=False): '''Create a texture containing this image. If the image's dimensions are not powers of 2, a TextureRegion of a larger Texture will be returned that matches the dimensions of this image. :Parameters: `cls` : class (subclass of Texture) Class to construct. `rectangle` : bool ``True`` if a rectangle can be created; see `AbstractImage.get_texture`. **Since:** pyglet 1.1 `force_rectangle` : bool ``True`` if a rectangle must be created; see `AbstractImage.get_texture`. **Since:** pyglet 1.1.4 :rtype: cls or cls.region_class ''' internalformat = self._get_internalformat(self.format) texture = cls.create(self.width, self.height, internalformat, rectangle, force_rectangle) if self.anchor_x or self.anchor_y: texture.anchor_x = self.anchor_x texture.anchor_y = self.anchor_y self.blit_to_texture(texture.target, texture.level, self.anchor_x, self.anchor_y, 0, None) return texture def get_texture(self, rectangle=False, force_rectangle=False): if (not self._current_texture or (not self._current_texture._is_rectangle and force_rectangle)): self._current_texture = self.create_texture(Texture, rectangle, force_rectangle) return self._current_texture def get_mipmapped_texture(self): '''Return a Texture with mipmaps. If `set_mipmap_image` has been called with at least one image, the set of images defined will be used. Otherwise, mipmaps will be automatically generated. The texture dimensions must be powers of 2 to use mipmaps. :rtype: `Texture` :since: pyglet 1.1 ''' if self._current_mipmap_texture: return self._current_mipmap_texture if not _is_pow2(self.width) or not _is_pow2(self.height): raise ImageException( 'Image dimensions must be powers of 2 to use mipmaps.') texture = Texture.create_for_size( GL_TEXTURE_2D, self.width, self.height) if self.anchor_x or self.anchor_y: texture.anchor_x = self.anchor_x texture.anchor_y = self.anchor_y internalformat = self._get_internalformat(self.format) glBindTexture(texture.target, texture.id) glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) if self.mipmap_images: self.blit_to_texture(texture.target, texture.level, self.anchor_x, self.anchor_y, 0, internalformat) level = 0 for image in self.mipmap_images: level += 1 if image: image.blit_to_texture(texture.target, level, self.anchor_x, self.anchor_y, 0, internalformat) # TODO: should set base and max mipmap level if some mipmaps # are missing. elif gl_info.have_version(1, 4): glTexParameteri(texture.target, GL_GENERATE_MIPMAP, GL_TRUE) self.blit_to_texture(texture.target, texture.level, self.anchor_x, self.anchor_y, 0, internalformat) else: raise NotImplementedError('TODO: gluBuild2DMipmaps') self._current_mipmap_texture = texture return texture def get_region(self, x, y, width, height): '''Retrieve a rectangular region of this image data. :Parameters: `x` : int Left edge of region. `y` : int Bottom edge of region. `width` : int Width of region. `height` : int Height of region. :rtype: ImageDataRegion ''' return ImageDataRegion(x, y, width, height, self) def blit(self, x, y, z=0, width=None, height=None): self.get_texture().blit(x, y, z, width, height) def blit_to_texture(self, target, level, x, y, z, internalformat=None): '''Draw this image to to the currently bound texture at `target`. This image's anchor point will be aligned to the given `x` and `y` coordinates. If the currently bound texture is a 3D texture, the `z` parameter gives the image slice to blit into. If `internalformat` is specified, glTexImage is used to initialise the texture; otherwise, glTexSubImage is used to update a region. ''' x -= self.anchor_x y -= self.anchor_y data_format = self.format data_pitch = abs(self._current_pitch) # Determine pixel format from format string matrix = None format, type = self._get_gl_format_and_type(data_format) if format is None: if (len(data_format) in (3, 4) and gl_info.have_extension('GL_ARB_imaging')): # Construct a color matrix to convert to GL_RGBA def component_column(component): try: pos = 'RGBA'.index(component) return [0] * pos + [1] + [0] * (3 - pos) except ValueError: return [0, 0, 0, 0] # pad to avoid index exceptions lookup_format = data_format + 'XXX' matrix = (component_column(lookup_format[0]) + component_column(lookup_format[1]) + component_column(lookup_format[2]) + component_column(lookup_format[3])) format = { 3: GL_RGB, 4: GL_RGBA}.get(len(data_format)) type = GL_UNSIGNED_BYTE glMatrixMode(GL_COLOR) glPushMatrix() glLoadMatrixf((GLfloat * 16)(*matrix)) else: # Need to convert data to a standard form data_format = { 1: 'L', 2: 'LA', 3: 'RGB', 4: 'RGBA'}.get(len(data_format)) format, type = self._get_gl_format_and_type(data_format) # Workaround: don't use GL_UNPACK_ROW_LENGTH if gl.current_context._workaround_unpack_row_length: data_pitch = self.width * len(data_format) # Get data in required format (hopefully will be the same format it's # already in, unless that's an obscure format, upside-down or the # driver is old). data = self._convert(data_format, data_pitch) if data_pitch & 0x1: alignment = 1 elif data_pitch & 0x2: alignment = 2 else: alignment = 4 row_length = data_pitch // len(data_format) glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT) glPixelStorei(GL_UNPACK_ALIGNMENT, alignment) glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length) self._apply_region_unpack() if target == GL_TEXTURE_3D: assert not internalformat glTexSubImage3D(target, level, x, y, z, self.width, self.height, 1, format, type, data) elif internalformat: glTexImage2D(target, level, internalformat, self.width, self.height, 0, format, type, data) else: glTexSubImage2D(target, level, x, y, self.width, self.height, format, type, data) glPopClientAttrib() if matrix: glPopMatrix() glMatrixMode(GL_MODELVIEW) # Flush image upload before data get GC'd. glFlush() def _apply_region_unpack(self): pass def _convert(self, format, pitch): '''Return data in the desired format; does not alter this instance's current format or pitch. ''' if format == self._current_format and pitch == self._current_pitch: if type(self._current_data) is str: return asbytes(self._current_data) return self._current_data self._ensure_string_data() data = self._current_data current_pitch = self._current_pitch current_format = self._current_format sign_pitch = current_pitch // abs(current_pitch) if format != self._current_format: # Create replacement string, e.g. r'\4\1\2\3' to convert RGBA to # ARGB repl = asbytes('') for c in format: try: idx = current_format.index(c) + 1 except ValueError: idx = 1 repl += asbytes(r'\%d' % idx) if len(current_format) == 1: swap_pattern = self._swap1_pattern elif len(current_format) == 2: swap_pattern = self._swap2_pattern elif len(current_format) == 3: swap_pattern = self._swap3_pattern elif len(current_format) == 4: swap_pattern = self._swap4_pattern else: raise ImageException( 'Current image format is wider than 32 bits.') packed_pitch = self.width * len(current_format) if abs(self._current_pitch) != packed_pitch: # Pitch is wider than pixel data, need to go row-by-row. rows = re.findall( asbytes('.') * abs(self._current_pitch), data, re.DOTALL) rows = [swap_pattern.sub(repl, r[:packed_pitch]) for r in rows] data = asbytes('').join(rows) else: # Rows are tightly packed, apply regex over whole image. data = swap_pattern.sub(repl, data) # After conversion, rows will always be tightly packed current_pitch = sign_pitch * (len(format) * self.width) if pitch != current_pitch: diff = abs(current_pitch) - abs(pitch) if diff > 0: # New pitch is shorter than old pitch, chop bytes off each row pattern = re.compile( asbytes('(%s)%s' % ('.' * abs(pitch), '.' * diff)), re.DOTALL) data = pattern.sub(asbytes(r'\1'), data) elif diff < 0: # New pitch is longer than old pitch, add '0' bytes to each row pattern = re.compile( asbytes('(%s)' % ('.' * abs(current_pitch))), re.DOTALL) pad = '.' * -diff data = pattern.sub(asbytes(r'\1%s' % pad), data) if current_pitch * pitch < 0: # Pitch differs in sign, swap row order rows = re.findall(asbytes('.') * abs(pitch), data, re.DOTALL) rows.reverse() data = asbytes('').join(rows) return asbytes(data) def _ensure_string_data(self): if type(self._current_data) is not bytes_type: buf = create_string_buffer(len(self._current_data)) memmove(buf, self._current_data, len(self._current_data)) self._current_data = buf.raw def _get_gl_format_and_type(self, format): if format == 'I': return GL_LUMINANCE, GL_UNSIGNED_BYTE elif format == 'L': return GL_LUMINANCE, GL_UNSIGNED_BYTE elif format == 'LA': return GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE elif format == 'R': return GL_RED, GL_UNSIGNED_BYTE elif format == 'G': return GL_GREEN, GL_UNSIGNED_BYTE elif format == 'B': return GL_BLUE, GL_UNSIGNED_BYTE elif format == 'A': return GL_ALPHA, GL_UNSIGNED_BYTE elif format == 'RGB': return GL_RGB, GL_UNSIGNED_BYTE elif format == 'RGBA': return GL_RGBA, GL_UNSIGNED_BYTE elif (format == 'ARGB' and gl_info.have_extension('GL_EXT_bgra') and gl_info.have_extension('GL_APPLE_packed_pixels')): return GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV elif (format == 'ABGR' and gl_info.have_extension('GL_EXT_abgr')): return GL_ABGR_EXT, GL_UNSIGNED_BYTE elif (format == 'BGR' and gl_info.have_extension('GL_EXT_bgra')): return GL_BGR, GL_UNSIGNED_BYTE elif (format == 'BGRA' and gl_info.have_extension('GL_EXT_bgra')): return GL_BGRA, GL_UNSIGNED_BYTE return None, None def _get_internalformat(self, format): if len(format) == 4: return GL_RGBA elif len(format) == 3: return GL_RGB elif len(format) == 2: return GL_LUMINANCE_ALPHA elif format == 'A': return GL_ALPHA elif format == 'L': return GL_LUMINANCE elif format == 'I': return GL_INTENSITY return GL_RGBA class ImageDataRegion(ImageData): def __init__(self, x, y, width, height, image_data): super(ImageDataRegion, self).__init__(width, height, image_data._current_format, image_data._current_data, image_data._current_pitch) self.x = x self.y = y def __getstate__(self): return { 'width': self.width, 'height': self.height, '_current_data': self.get_data(self._current_format, self._current_pitch), '_current_format': self._current_format, '_desired_format': self._desired_format, '_current_pitch': self._current_pitch, 'pitch': self.pitch, 'mipmap_images': self.mipmap_images, 'x': self.x, 'y': self.y } def _get_data(self): # Crop the data first x1 = len(self._current_format) * self.x x2 = len(self._current_format) * (self.x + self.width) self._ensure_string_data() data = self._convert(self._current_format, abs(self._current_pitch)) rows = re.findall('.' * abs(self._current_pitch), data, re.DOTALL) rows = [row[x1:x2] for row in rows[self.y:self.y+self.height]] self._current_data = ''.join(rows) self._current_pitch = self.width * len(self._current_format) self._current_texture = None self.x = 0 self.y = 0 return super(ImageDataRegion, self)._get_data() def _set_data(self, data): self.x = 0 self.y = 0 super(ImageDataRegion, self)._set_data(data) data = property(_get_data, _set_data) def get_data(self, format, pitch): x1 = len(self._current_format) * self.x x2 = len(self._current_format) * (self.x + self.width) self._ensure_string_data() data = self._convert(self._current_format, abs(self._current_pitch)) rows = re.findall(asbytes('.') * abs(self._current_pitch), data, re.DOTALL) rows = [row[x1:x2] for row in rows[self.y:self.y+self.height]] self._current_data = asbytes('').join(rows) self._current_pitch = self.width * len(self._current_format) self._current_texture = None self.x = 0 self.y = 0 return super(ImageDataRegion, self).get_data(format, pitch) def _apply_region_unpack(self): glPixelStorei(GL_UNPACK_SKIP_PIXELS, self.x) glPixelStorei(GL_UNPACK_SKIP_ROWS, self.y) def _ensure_string_data(self): super(ImageDataRegion, self)._ensure_string_data() def get_region(self, x, y, width, height): x += self.x y += self.y return super(ImageDataRegion, self).get_region(x, y, width, height) class CompressedImageData(AbstractImage): '''Image representing some compressed data suitable for direct uploading to driver. ''' _current_texture = None _current_mipmapped_texture = None def __init__(self, width, height, gl_format, data, extension=None, decoder=None): '''Construct a CompressedImageData with the given compressed data. :Parameters: `width` : int Width of image `height` : int Height of image `gl_format` : int GL constant giving format of compressed data; for example, ``GL_COMPRESSED_RGBA_S3TC_DXT5_EXT``. `data` : sequence String or array/list of bytes giving compressed image data. `extension` : str or None If specified, gives the name of a GL extension to check for before creating a texture. `decoder` : function(data, width, height) -> AbstractImage A function to decode the compressed data, to be used if the required extension is not present. ''' if not _is_pow2(width) or not _is_pow2(height): raise ImageException('Dimensions of %r must be powers of 2' % self) super(CompressedImageData, self).__init__(width, height) self.data = data self.gl_format = gl_format self.extension = extension self.decoder = decoder self.mipmap_data = [] def set_mipmap_data(self, level, data): '''Set data for a mipmap level. Supplied data gives a compressed image for the given mipmap level. The image must be of the correct dimensions for the level (i.e., width >> level, height >> level); but this is not checked. If any mipmap levels are specified, they are used; otherwise, mipmaps for `mipmapped_texture` are generated automatically. :Parameters: `level` : int Level of mipmap image to set. `data` : sequence String or array/list of bytes giving compressed image data. Data must be in same format as specified in constructor. ''' # Extend mipmap_data list to required level self.mipmap_data += [None] * (level - len(self.mipmap_data)) self.mipmap_data[level - 1] = data def _have_extension(self): return self.extension is None or gl_info.have_extension(self.extension) def _verify_driver_supported(self): '''Assert that the extension required for this image data is supported. Raises `ImageException` if not. ''' if not self._have_extension(): raise ImageException('%s is required to decode %r' % \ (self.extension, self)) def get_texture(self, rectangle=False, force_rectangle=False): if force_rectangle: raise ImageException( 'Compressed texture rectangles not supported') if self._current_texture: return self._current_texture texture = Texture.create_for_size( GL_TEXTURE_2D, self.width, self.height) if self.anchor_x or self.anchor_y: texture.anchor_x = self.anchor_x texture.anchor_y = self.anchor_y glBindTexture(texture.target, texture.id) glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER, texture.min_filter) glTexParameteri(texture.target, GL_TEXTURE_MAG_FILTER, texture.mag_filter) if self._have_extension(): glCompressedTexImage2DARB(texture.target, texture.level, self.gl_format, self.width, self.height, 0, len(self.data), self.data) else: image = self.decoder(self.data, self.width, self.height) texture = image.get_texture() assert texture.width == self.width assert texture.height == self.height glFlush() self._current_texture = texture return texture def get_mipmapped_texture(self): if self._current_mipmap_texture: return self._current_mipmap_texture if not self._have_extension(): # TODO mip-mapped software decoded compressed textures. For now, # just return a non-mipmapped texture. return self.get_texture() texture = Texture.create_for_size( GL_TEXTURE_2D, self.width, self.height) if self.anchor_x or self.anchor_y: texture.anchor_x = self.anchor_x texture.anchor_y = self.anchor_y glBindTexture(texture.target, texture.id) glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) if not self.mipmap_data: if not gl_info.have_version(1, 4): raise ImageException( 'Require GL 1.4 to generate mipmaps for compressed textures') glTexParameteri(texture.target, GL_GENERATE_MIPMAP, GL_TRUE) glCompressedTexImage2DARB(texture.target, texture.level, self.gl_format, self.width, self.height, 0, len(self.data), self.data) width, height = self.width, self.height level = 0 for data in self.mipmap_data: width >>= 1 height >>= 1 level += 1 glCompressedTexImage2DARB(texture.target, level, self.gl_format, width, height, 0, len(data), data) glFlush() self._current_mipmap_texture = texture return texture def blit_to_texture(self, target, level, x, y, z): self._verify_driver_supported() if target == GL_TEXTURE_3D: glCompressedTexSubImage3DARB(target, level, x - self.anchor_x, y - self.anchor_y, z, self.width, self.height, 1, self.gl_format, len(self.data), self.data) else: glCompressedTexSubImage2DARB(target, level, x - self.anchor_x, y - self.anchor_y, self.width, self.height, self.gl_format, len(self.data), self.data) def _nearest_pow2(v): # From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 # Credit: Sean Anderson v -= 1 v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 return v + 1 def _is_pow2(v): # http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 return (v & (v - 1)) == 0 class Texture(AbstractImage): '''An image loaded into video memory that can be efficiently drawn to the framebuffer. Typically you will get an instance of Texture by accessing the `texture` member of any other AbstractImage. :Ivariables: `region_class` : class (subclass of TextureRegion) Class to use when constructing regions of this texture. `tex_coords` : tuple 12-tuple of float, named (u1, v1, r1, u2, v2, r2, ...). u, v, r give the 3D texture coordinates for vertices 1-4. The vertices are specified in the order bottom-left, bottom-right, top-right and top-left. `target` : int The GL texture target (e.g., ``GL_TEXTURE_2D``). `level` : int The mipmap level of this texture. ''' region_class = None # Set to TextureRegion after it's defined tex_coords = (0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0.) tex_coords_order = (0, 1, 2, 3) level = 0 images = 1 x = y = z = 0 def __init__(self, width, height, target, id): super(Texture, self).__init__(width, height) self.target = target self.id = id self._context = gl.current_context def delete(self): '''Delete the texture from video memory. :deprecated: Textures are automatically released during object finalization. ''' warnings.warn( 'Texture.delete() is deprecated; textures are ' 'released through GC now') self._context.delete_texture(self.id) self.id = 0 def __del__(self): try: self._context.delete_texture(self.id) except: pass @classmethod def create(cls, width, height, internalformat=GL_RGBA, rectangle=False, force_rectangle=False, min_filter=GL_LINEAR, mag_filter=GL_LINEAR): '''Create an empty Texture. If `rectangle` is ``False`` or the appropriate driver extensions are not available, a larger texture than requested will be created, and a `TextureRegion` corresponding to the requested size will be returned. :Parameters: `width` : int Width of the texture. `height` : int Height of the texture. `internalformat` : int GL constant giving the internal format of the texture; for example, ``GL_RGBA``. `rectangle` : bool ``True`` if a rectangular texture is permitted. See `AbstractImage.get_texture`. `force_rectangle` : bool ``True`` if a rectangular texture is required. See `AbstractImage.get_texture`. **Since:** pyglet 1.1.4. `min_filter` : int The minifaction filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST`` `mag_filter` : int The magnification filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST`` :rtype: `Texture` :since: pyglet 1.1 ''' target = GL_TEXTURE_2D if rectangle or force_rectangle: if not force_rectangle and _is_pow2(width) and _is_pow2(height): rectangle = False elif gl_info.have_extension('GL_ARB_texture_rectangle'): target = GL_TEXTURE_RECTANGLE_ARB rectangle = True elif gl_info.have_extension('GL_NV_texture_rectangle'): target = GL_TEXTURE_RECTANGLE_NV rectangle = True else: rectangle = False if force_rectangle and not rectangle: raise ImageException('Texture rectangle extensions not available') if rectangle: texture_width = width texture_height = height else: texture_width = _nearest_pow2(width) texture_height = _nearest_pow2(height) id = GLuint() glGenTextures(1, byref(id)) glBindTexture(target, id.value) glTexParameteri(target, GL_TEXTURE_MIN_FILTER, min_filter) glTexParameteri(target, GL_TEXTURE_MAG_FILTER, mag_filter) blank = (GLubyte * (texture_width * texture_height * 4))() glTexImage2D(target, 0, internalformat, texture_width, texture_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, blank) texture = cls(texture_width, texture_height, target, id.value) texture.min_filter = min_filter texture.mag_filter = mag_filter if rectangle: texture._is_rectangle = True texture.tex_coords = (0., 0., 0., width, 0., 0., width, height, 0., 0., height, 0.) glFlush() if texture_width == width and texture_height == height: return texture return texture.get_region(0, 0, width, height) @classmethod def create_for_size(cls, target, min_width, min_height, internalformat=None, min_filter=GL_LINEAR, mag_filter=GL_LINEAR): '''Create a Texture with dimensions at least min_width, min_height. On return, the texture will be bound. :Parameters: `target` : int GL constant giving texture target to use, typically ``GL_TEXTURE_2D``. `min_width` : int Minimum width of texture (may be increased to create a power of 2). `min_height` : int Minimum height of texture (may be increased to create a power of 2). `internalformat` : int GL constant giving internal format of texture; for example, ``GL_RGBA``. If unspecified, the texture will not be initialised (only the texture name will be created on the instance). If specified, the image will be initialised to this format with zero'd data. `min_filter` : int The minifaction filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST`` `mag_filter` : int The magnification filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST`` :rtype: `Texture` ''' if target not in (GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_RECTANGLE_ARB): width = _nearest_pow2(min_width) height = _nearest_pow2(min_height) tex_coords = cls.tex_coords else: width = min_width height = min_height tex_coords = (0., 0., 0., width, 0., 0., width, height, 0., 0., height, 0.) id = GLuint() glGenTextures(1, byref(id)) glBindTexture(target, id.value) glTexParameteri(target, GL_TEXTURE_MIN_FILTER, min_filter) glTexParameteri(target, GL_TEXTURE_MAG_FILTER, mag_filter) if internalformat is not None: blank = (GLubyte * (width * height * 4))() glTexImage2D(target, 0, internalformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, blank) glFlush() texture = cls(width, height, target, id.value) texture.min_filter = min_filter texture.mag_filter = mag_filter texture.tex_coords = tex_coords return texture def get_image_data(self, z=0): '''Get the image data of this texture. Changes to the returned instance will not be reflected in this texture. :Parameters: `z` : int For 3D textures, the image slice to retrieve. :rtype: `ImageData` ''' glBindTexture(self.target, self.id) # Always extract complete RGBA data. Could check internalformat # to only extract used channels. XXX format = 'RGBA' gl_format = GL_RGBA glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT) glPixelStorei(GL_PACK_ALIGNMENT, 1) buffer = \ (GLubyte * (self.width * self.height * self.images * len(format)))() glGetTexImage(self.target, self.level, gl_format, GL_UNSIGNED_BYTE, buffer) glPopClientAttrib() data = ImageData(self.width, self.height, format, buffer) if self.images > 1: data = data.get_region(0, z * self.height, self.width, self.height) return data image_data = property(lambda self: self.get_image_data(), doc='''An ImageData view of this texture. Changes to the returned instance will not be reflected in this texture. If the texture is a 3D texture, the first image will be returned. See also `get_image_data`. Read-only. :deprecated: Use `get_image_data`. :type: `ImageData` ''') def get_texture(self, rectangle=False, force_rectangle=False): if force_rectangle and not self._is_rectangle: raise ImageException('Texture is not a rectangle.') return self # no implementation of blit_to_texture yet (could use aux buffer) def blit(self, x, y, z=0, width=None, height=None): t = self.tex_coords x1 = x - self.anchor_x y1 = y - self.anchor_y x2 = x1 + (width is None and self.width or width) y2 = y1 + (height is None and self.height or height) array = (GLfloat * 32)( t[0], t[1], t[2], 1., x1, y1, z, 1., t[3], t[4], t[5], 1., x2, y1, z, 1., t[6], t[7], t[8], 1., x2, y2, z, 1., t[9], t[10], t[11], 1., x1, y2, z, 1.) glPushAttrib(GL_ENABLE_BIT) glEnable(self.target) glBindTexture(self.target, self.id) glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glInterleavedArrays(GL_T4F_V4F, 0, array) glDrawArrays(GL_QUADS, 0, 4) glPopClientAttrib() glPopAttrib() def blit_into(self, source, x, y, z): glBindTexture(self.target, self.id) source.blit_to_texture(self.target, self.level, x, y, z) def get_region(self, x, y, width, height): return self.region_class(x, y, 0, width, height, self) def get_transform(self, flip_x=False, flip_y=False, rotate=0): '''Create a copy of this image applying a simple transformation. The transformation is applied to the texture coordinates only; `get_image_data` will return the untransformed data. The transformation is applied around the anchor point. :Parameters: `flip_x` : bool If True, the returned image will be flipped horizontally. `flip_y` : bool If True, the returned image will be flipped vertically. `rotate` : int Degrees of clockwise rotation of the returned image. Only 90-degree increments are supported. :rtype: `TextureRegion` ''' transform = self.get_region(0, 0, self.width, self.height) bl, br, tr, tl = 0, 1, 2, 3 transform.anchor_x = self.anchor_x transform.anchor_y = self.anchor_y if flip_x: bl, br, tl, tr = br, bl, tr, tl transform.anchor_x = self.width - self.anchor_x if flip_y: bl, br, tl, tr = tl, tr, bl, br transform.anchor_y = self.height - self.anchor_y rotate %= 360 if rotate < 0: rotate += 360 if rotate == 0: pass elif rotate == 90: bl, br, tr, tl = br, tr, tl, bl transform.anchor_x, transform.anchor_y = \ transform.anchor_y, \ transform.width - transform.anchor_x elif rotate == 180: bl, br, tr, tl = tr, tl, bl, br transform.anchor_x = transform.width - transform.anchor_x transform.anchor_y = transform.height - transform.anchor_y elif rotate == 270: bl, br, tr, tl = tl, bl, br, tr transform.anchor_x, transform.anchor_y = \ transform.height - transform.anchor_y, \ transform.anchor_x else: assert False, 'Only 90 degree rotations are supported.' if rotate in (90, 270): transform.width, transform.height = \ transform.height, transform.width transform._set_tex_coords_order(bl, br, tr, tl) return transform def _set_tex_coords_order(self, bl, br, tr, tl): tex_coords = (self.tex_coords[:3], self.tex_coords[3:6], self.tex_coords[6:9], self.tex_coords[9:]) self.tex_coords = \ tex_coords[bl] + tex_coords[br] + tex_coords[tr] + tex_coords[tl] order = self.tex_coords_order self.tex_coords_order = \ (order[bl], order[br], order[tr], order[tl]) class TextureRegion(Texture): '''A rectangular region of a texture, presented as if it were a separate texture. ''' def __init__(self, x, y, z, width, height, owner): super(TextureRegion, self).__init__( width, height, owner.target, owner.id) self.x = x self.y = y self.z = z self.owner = owner owner_u1 = owner.tex_coords[0] owner_v1 = owner.tex_coords[1] owner_u2 = owner.tex_coords[3] owner_v2 = owner.tex_coords[7] scale_u = owner_u2 - owner_u1 scale_v = owner_v2 - owner_v1 u1 = x / float(owner.width) * scale_u + owner_u1 v1 = y / float(owner.height) * scale_v + owner_v1 u2 = (x + width) / float(owner.width) * scale_u + owner_u1 v2 = (y + height) / float(owner.height) * scale_v + owner_v1 r = z / float(owner.images) + owner.tex_coords[2] self.tex_coords = (u1, v1, r, u2, v1, r, u2, v2, r, u1, v2, r) def get_image_data(self): image_data = self.owner.get_image_data(self.z) return image_data.get_region(self.x, self.y, self.width, self.height) def get_region(self, x, y, width, height): x += self.x y += self.y region = self.region_class(x, y, self.z, width, height, self.owner) region._set_tex_coords_order(*self.tex_coords_order) return region def blit_into(self, source, x, y, z): self.owner.blit_into(source, x + self.x, y + self.y, z + self.z) def __del__(self): # only the owner Texture should handle deletion pass Texture.region_class = TextureRegion class Texture3D(Texture, UniformTextureSequence): '''A texture with more than one image slice. Use `create_for_images` or `create_for_image_grid` classmethod to construct. ''' item_width = 0 item_height = 0 items = () @classmethod def create_for_images(cls, images, internalformat=GL_RGBA): item_width = images[0].width item_height = images[0].height for image in images: if image.width != item_width or image.height != item_height: raise ImageException('Images do not have same dimensions.') depth = len(images) if not gl_info.have_version(2,0): depth = _nearest_pow2(depth) texture = cls.create_for_size(GL_TEXTURE_3D, item_width, item_height) if images[0].anchor_x or images[0].anchor_y: texture.anchor_x = images[0].anchor_x texture.anchor_y = images[0].anchor_y texture.images = depth blank = (GLubyte * (texture.width * texture.height * texture.images))() glBindTexture(texture.target, texture.id) glTexImage3D(texture.target, texture.level, internalformat, texture.width, texture.height, texture.images, 0, GL_ALPHA, GL_UNSIGNED_BYTE, blank) items = [] for i, image in enumerate(images): item = cls.region_class(0, 0, i, item_width, item_height, texture) items.append(item) image.blit_to_texture(texture.target, texture.level, image.anchor_x, image.anchor_y, i) glFlush() texture.items = items texture.item_width = item_width texture.item_height = item_height return texture @classmethod def create_for_image_grid(cls, grid, internalformat=GL_RGBA): return cls.create_for_images(grid[:], internalformat) def __len__(self): return len(self.items) def __getitem__(self, index): return self.items[index] def __setitem__(self, index, value): if type(index) is slice: for item, image in zip(self[index], value): image.blit_to_texture(self.target, self.level, image.anchor_x, image.anchor_y, item.z) else: value.blit_to_texture(self.target, self.level, value.anchor_x, value.anchor_y, self[index].z) def __iter__(self): return iter(self.items) class TileableTexture(Texture): '''A texture that can be tiled efficiently. Use `create_for_image` classmethod to construct. ''' def __init__(self, width, height, target, id): if not _is_pow2(width) or not _is_pow2(height): raise ImageException( 'TileableTexture requires dimensions that are powers of 2') super(TileableTexture, self).__init__(width, height, target, id) def get_region(self, x, y, width, height): raise ImageException('Cannot get region of %r' % self) def blit_tiled(self, x, y, z, width, height): '''Blit this texture tiled over the given area. The image will be tiled with the bottom-left corner of the destination rectangle aligned with the anchor point of this texture. ''' u1 = self.anchor_x / float(self.width) v1 = self.anchor_y / float(self.height) u2 = u1 + width / float(self.width) v2 = v1 + height / float(self.height) w, h = width, height t = self.tex_coords array = (GLfloat * 32)( u1, v1, t[2], 1., x, y, z, 1., u2, v1, t[5], 1., x + w, y, z, 1., u2, v2, t[8], 1., x + w, y + h, z, 1., u1, v2, t[11], 1., x, y + h, z, 1.) glPushAttrib(GL_ENABLE_BIT) glEnable(self.target) glBindTexture(self.target, self.id) glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glInterleavedArrays(GL_T4F_V4F, 0, array) glDrawArrays(GL_QUADS, 0, 4) glPopClientAttrib() glPopAttrib() @classmethod def create_for_image(cls, image): if not _is_pow2(image.width) or not _is_pow2(image.height): # Potentially unnecessary conversion if a GL format exists. image = image.get_image_data() texture_width = _nearest_pow2(image.width) texture_height = _nearest_pow2(image.height) newdata = c_buffer(texture_width * texture_height * 4) gluScaleImage(GL_RGBA, image.width, image.height, GL_UNSIGNED_BYTE, image.get_data('RGBA', image.width * 4), texture_width, texture_height, GL_UNSIGNED_BYTE, newdata) image = ImageData(texture_width, texture_height, 'RGBA', newdata) image = image.get_image_data() return image.create_texture(cls) class DepthTexture(Texture): '''A texture with depth samples (typically 24-bit).''' def blit_into(self, source, x, y, z): glBindTexture(self.target, self.id) source.blit_to_texture(self.level, x, y, z) class BufferManager(object): '''Manages the set of framebuffers for a context. Use `get_buffer_manager` to obtain the instance of this class for the current context. ''' def __init__(self): self.color_buffer = None self.depth_buffer = None aux_buffers = GLint() glGetIntegerv(GL_AUX_BUFFERS, byref(aux_buffers)) self.free_aux_buffers = [GL_AUX0, GL_AUX1, GL_AUX2, GL_AUX3][:aux_buffers.value] stencil_bits = GLint() glGetIntegerv(GL_STENCIL_BITS, byref(stencil_bits)) self.free_stencil_bits = range(stencil_bits.value) self.refs = [] def get_viewport(self): '''Get the current OpenGL viewport dimensions. :rtype: 4-tuple of float. :return: Left, top, right and bottom dimensions. ''' viewport = (GLint * 4)() glGetIntegerv(GL_VIEWPORT, viewport) return viewport def get_color_buffer(self): '''Get the color buffer. :rtype: `ColorBufferImage` ''' viewport = self.get_viewport() viewport_width = viewport[2] viewport_height = viewport[3] if (not self.color_buffer or viewport_width != self.color_buffer.width or viewport_height != self.color_buffer.height): self.color_buffer = ColorBufferImage(*viewport) return self.color_buffer def get_aux_buffer(self): '''Get a free auxiliary buffer. If not aux buffers are available, `ImageException` is raised. Buffers are released when they are garbage collected. :rtype: `ColorBufferImage` ''' if not self.free_aux_buffers: raise ImageException('No free aux buffer is available.') gl_buffer = self.free_aux_buffers.pop(0) viewport = self.get_viewport() buffer = ColorBufferImage(*viewport) buffer.gl_buffer = gl_buffer def release_buffer(ref, self=self): self.free_aux_buffers.insert(0, gl_buffer) self.refs.append(weakref.ref(buffer, release_buffer)) return buffer def get_depth_buffer(self): '''Get the depth buffer. :rtype: `DepthBufferImage` ''' viewport = self.get_viewport() viewport_width = viewport[2] viewport_height = viewport[3] if (not self.depth_buffer or viewport_width != self.depth_buffer.width or viewport_height != self.depth_buffer.height): self.depth_buffer = DepthBufferImage(*viewport) return self.depth_buffer def get_buffer_mask(self): '''Get a free bitmask buffer. A bitmask buffer is a buffer referencing a single bit in the stencil buffer. If no bits are free, `ImageException` is raised. Bits are released when the bitmask buffer is garbage collected. :rtype: `BufferImageMask` ''' if not self.free_stencil_bits: raise ImageException('No free stencil bits are available.') stencil_bit = self.free_stencil_bits.pop(0) x, y, width, height = self.get_viewport() buffer = BufferImageMask(x, y, width, height) buffer.stencil_bit = stencil_bit def release_buffer(ref, self=self): self.free_stencil_bits.insert(0, stencil_bit) self.refs.append(weakref.ref(buffer, release_buffer)) return buffer def get_buffer_manager(): '''Get the buffer manager for the current OpenGL context. :rtype: `BufferManager` ''' context = gl.current_context if not hasattr(context, 'image_buffer_manager'): context.image_buffer_manager = BufferManager() return context.image_buffer_manager # XXX BufferImage could be generalised to support EXT_framebuffer_object's # renderbuffer. class BufferImage(AbstractImage): '''An abstract framebuffer. ''' #: The OpenGL read and write target for this buffer. gl_buffer = GL_BACK #: The OpenGL format constant for image data. gl_format = 0 #: The format string used for image data. format = '' owner = None # TODO: enable methods def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height def get_image_data(self): buffer = (GLubyte * (len(self.format) * self.width * self.height))() x = self.x y = self.y if self.owner: x += self.owner.x y += self.owner.y glReadBuffer(self.gl_buffer) glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT) glPixelStorei(GL_PACK_ALIGNMENT, 1) glReadPixels(x, y, self.width, self.height, self.gl_format, GL_UNSIGNED_BYTE, buffer) glPopClientAttrib() return ImageData(self.width, self.height, self.format, buffer) def get_region(self, x, y, width, height): if self.owner: return self.owner.get_region(x + self.x, y + self.y, width, height) region = self.__class__(x + self.x, y + self.y, width, height) region.gl_buffer = self.gl_buffer region.owner = self return region class ColorBufferImage(BufferImage): '''A color framebuffer. This class is used to wrap both the primary color buffer (i.e., the back buffer) or any one of the auxiliary buffers. ''' gl_format = GL_RGBA format = 'RGBA' def get_texture(self, rectangle=False, force_rectangle=False): texture = Texture.create(self.width, self.height, GL_RGBA, rectangle, force_rectangle) self.blit_to_texture(texture.target, texture.level, self.anchor_x, self.anchor_y, 0) return texture def blit_to_texture(self, target, level, x, y, z): glReadBuffer(self.gl_buffer) glCopyTexSubImage2D(target, level, x - self.anchor_x, y - self.anchor_y, self.x, self.y, self.width, self.height) class DepthBufferImage(BufferImage): '''The depth buffer. ''' gl_format = GL_DEPTH_COMPONENT format = 'L' def get_texture(self, rectangle=False, force_rectangle=False): assert rectangle == False and force_rectangle == False, \ 'Depth textures cannot be rectangular' if not _is_pow2(self.width) or not _is_pow2(self.height): raise ImageException( 'Depth texture requires that buffer dimensions be powers of 2') texture = DepthTexture.create_for_size(GL_TEXTURE_2D, self.width, self.height) if self.anchor_x or self.anchor_y: texture.anchor_x = self.anchor_x texture.anchor_y = self.anchor_y glReadBuffer(self.gl_buffer) glCopyTexImage2D(texture.target, 0, GL_DEPTH_COMPONENT, self.x, self.y, self.width, self.height, 0) return texture def blit_to_texture(self, target, level, x, y, z): glReadBuffer(self.gl_buffer) glCopyTexSubImage2D(target, level, x - self.anchor_x, y - self.anchor_y, self.x, self.y, self.width, self.height) class BufferImageMask(BufferImage): '''A single bit of the stencil buffer. ''' gl_format = GL_STENCIL_INDEX format = 'L' # TODO mask methods class ImageGrid(AbstractImage, AbstractImageSequence): '''An imaginary grid placed over an image allowing easy access to regular regions of that image. The grid can be accessed either as a complete image, or as a sequence of images. The most useful applications are to access the grid as a `TextureGrid`:: image_grid = ImageGrid(...) texture_grid = image_grid.get_texture_sequence() or as a `Texture3D`:: image_grid = ImageGrid(...) texture_3d = Texture3D.create_for_image_grid(image_grid) ''' _items = () _texture_grid = None def __init__(self, image, rows, columns, item_width=None, item_height=None, row_padding=0, column_padding=0): '''Construct a grid for the given image. You can specify parameters for the grid, for example setting the padding between cells. Grids are always aligned to the bottom-left corner of the image. :Parameters: `image` : AbstractImage Image over which to construct the grid. `rows` : int Number of rows in the grid. `columns` : int Number of columns in the grid. `item_width` : int Width of each column. If unspecified, is calculated such that the entire image width is used. `item_height` : int Height of each row. If unspecified, is calculated such that the entire image height is used. `row_padding` : int Pixels separating adjacent rows. The padding is only inserted between rows, not at the edges of the grid. `column_padding` : int Pixels separating adjacent columns. The padding is only inserted between columns, not at the edges of the grid. ''' super(ImageGrid, self).__init__(image.width, image.height) if item_width is None: item_width = \ int((image.width - column_padding * (columns - 1)) / columns) if item_height is None: item_height = \ int((image.height - row_padding * (rows - 1)) / rows) self.image = image self.rows = rows self.columns = columns self.item_width = item_width self.item_height = item_height self.row_padding = row_padding self.column_padding = column_padding def get_texture(self, rectangle=False, force_rectangle=False): return self.image.get_texture(rectangle, force_rectangle) def get_image_data(self): return self.image.get_image_data() def get_texture_sequence(self): if not self._texture_grid: self._texture_grid = TextureGrid(self) return self._texture_grid def __len__(self): return self.rows * self.columns def _update_items(self): if not self._items: self._items = [] y = 0 for row in range(self.rows): x = 0 for col in range(self.columns): self._items.append(self.image.get_region( x, y, self.item_width, self.item_height)) x += self.item_width + self.column_padding y += self.item_height + self.row_padding def __getitem__(self, index): self._update_items() # TODO tuples return self._items[index] def __iter__(self): self._update_items() return iter(self._items) class TextureGrid(TextureRegion, UniformTextureSequence): '''A texture containing a regular grid of texture regions. To construct, create an `ImageGrid` first:: image_grid = ImageGrid(...) texture_grid = TextureGrid(image_grid) The texture grid can be accessed as a single texture, or as a sequence of `TextureRegion`. When accessing as a sequence, you can specify integer indexes, in which the images are arranged in rows from the bottom-left to the top-right:: # assume the texture_grid is 3x3: current_texture = texture_grid[3] # get the middle-left image You can also specify tuples in the sequence methods, which are addressed as ``row, column``:: # equivalent to the previous example: current_texture = texture_grid[1, 0] When using tuples in a slice, the returned sequence is over the rectangular region defined by the slice:: # returns center, center-right, center-top, top-right images in that # order: images = texture_grid[(1,1):] # equivalent to images = texture_grid[(1,1):(3,3)] ''' items = () rows = 1 columns = 1 item_width = 0 item_height = 0 def __init__(self, grid): image = grid.get_texture() if isinstance(image, TextureRegion): owner = image.owner else: owner = image super(TextureGrid, self).__init__( image.x, image.y, image.z, image.width, image.height, owner) items = [] y = 0 for row in range(grid.rows): x = 0 for col in range(grid.columns): items.append( self.get_region(x, y, grid.item_width, grid.item_height)) x += grid.item_width + grid.column_padding y += grid.item_height + grid.row_padding self.items = items self.rows = grid.rows self.columns = grid.columns self.item_width = grid.item_width self.item_height = grid.item_height def get(self, row, column): return self[(row, column)] def __getitem__(self, index): if type(index) is slice: if type(index.start) is not tuple and \ type(index.stop) is not tuple: return self.items[index] else: row1 = 0 col1 = 0 row2 = self.rows col2 = self.columns if type(index.start) is tuple: row1, col1 = index.start elif type(index.start) is int: row1 = index.start / self.columns col1 = index.start % self.columns assert row1 >= 0 and col1 >= 0 and \ row1 < self.rows and col1 < self.columns if type(index.stop) is tuple: row2, col2 = index.stop elif type(index.stop) is int: row2 = index.stop / self.columns col2 = index.stop % self.columns assert row2 >= 0 and col2 >= 0 and \ row2 <= self.rows and col2 <= self.columns result = [] i = row1 * self.columns for row in range(row1, row2): result += self.items[i+col1:i+col2] i += self.columns return result else: if type(index) is tuple: row, column = index assert row >= 0 and column >= 0 and \ row < self.rows and column < self.columns return self.items[row * self.columns + column] elif type(index) is int: return self.items[index] def __setitem__(self, index, value): if type(index) is slice: for region, image in zip(self[index], value): if image.width != self.item_width or \ image.height != self.item_height: raise ImageException('Image has incorrect dimensions') image.blit_into(region, image.anchor_x, image.anchor_y, 0) else: image = value if image.width != self.item_width or \ image.height != self.item_height: raise ImageException('Image has incorrect dimensions') image.blit_into(self[index], image.anchor_x, image.anchor_y, 0) def __len__(self): return len(self.items) def __iter__(self): return iter(self.items) # -------------------------------------------------------------------------- # Animation stuff here. Vote on if this should be in pyglet.image.animation # or just leave it tacked on here. # TODO: # conversion Animation -> media.Source # move to another module? # pyglet.animation? # pyglet.image.animation? def load_animation(filename, file=None, decoder=None): '''Load an animation from a file. Currently, the only supported format is GIF. :Parameters: `filename` : str Used to guess the animation format, and to load the file if `file` is unspecified. `file` : file-like object or None File object containing the animation stream. `decoder` : ImageDecoder or None If unspecified, all decoders that are registered for the filename extension are tried. If none succeed, the exception from the first decoder is raised. :rtype: Animation ''' if not file: file = open(filename, 'rb') if not hasattr(file, 'seek'): file = StringIO(file.read()) if decoder: return decoder.decode(file, filename) else: first_exception = None for decoder in codecs.get_animation_decoders(filename): try: image = decoder.decode_animation(file, filename) return image except codecs.ImageDecodeException, e: first_exception = first_exception or e file.seek(0) if not first_exception: raise codecs.ImageDecodeException('No image decoders are available') raise first_exception class Animation(object): '''Sequence of images with timing information. If no frames of the animation have a duration of ``None``, the animation loops continuously; otherwise the animation stops at the first frame with duration of ``None``. :Ivariables: `frames` : list of `AnimationFrame` The frames that make up the animation. ''' def __init__(self, frames): '''Create an animation directly from a list of frames. :Parameters: `frames` : list of `AnimationFrame` The frames that make up the animation. ''' assert len(frames) self.frames = frames def add_to_texture_bin(self, bin): '''Add the images of the animation to a `TextureBin`. The animation frames are modified in-place to refer to the texture bin regions. :Parameters: `bin` : `TextureBin` Texture bin to upload animation frames into. ''' for frame in self.frames: frame.image = bin.add(frame.image) def get_transform(self, flip_x=False, flip_y=False, rotate=0): '''Create a copy of this animation applying a simple transformation. The transformation is applied around the image's anchor point of each frame. The texture data is shared between the original animation and the transformed animation. :Parameters: `flip_x` : bool If True, the returned animation will be flipped horizontally. `flip_y` : bool If True, the returned animation will be flipped vertically. `rotate` : int Degrees of clockwise rotation of the returned animation. Only 90-degree increments are supported. :rtype: `Animation` ''' frames = [AnimationFrame( frame.image.get_texture().get_transform( flip_x, flip_y, rotate), frame.duration) \ for frame in self.frames] return Animation(frames) def get_duration(self): '''Get the total duration of the animation in seconds. :rtype: float ''' return sum([frame.duration for frame in self.frames \ if frame.duration is not None]) def get_max_width(self): '''Get the maximum image frame width. This method is useful for determining texture space requirements: due to the use of ``anchor_x`` the actual required playback area may be larger. :rtype: int ''' return max([frame.image.width for frame in self.frames]) def get_max_height(self): '''Get the maximum image frame height. This method is useful for determining texture space requirements: due to the use of ``anchor_y`` the actual required playback area may be larger. :rtype: int ''' return max([frame.image.height for frame in self.frames]) @classmethod def from_image_sequence(cls, sequence, period, loop=True): '''Create an animation from a list of images and a constant framerate. :Parameters: `sequence` : list of `AbstractImage` Images that make up the animation, in sequence. `period` : float Number of seconds to display each image. `loop` : bool If True, the animation will loop continuously. :rtype: `Animation` ''' frames = [AnimationFrame(image, period) for image in sequence] if not loop: frames[-1].duration = None return cls(frames) class AnimationFrame(object): '''A single frame of an animation. ''' def __init__(self, image, duration): '''Create an animation frame from an image. :Parameters: `image` : `AbstractImage` The image of this frame. `duration` : float Number of seconds to display the frame, or ``None`` if it is the last frame in the animation. ''' self.image = image self.duration = duration def __repr__(self): return 'AnimationFrame(%r, %r)' % (self.image, self.duration) # Initialise default codecs from pyglet.image import codecs as _codecs _codecs.add_default_image_codecs()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''DDS texture loader. Reference: http://msdn2.microsoft.com/en-us/library/bb172993.aspx ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' from ctypes import * import struct from pyglet.gl import * from pyglet.image import CompressedImageData from pyglet.image import codecs from pyglet.image.codecs import s3tc from pyglet.compat import izip_longest class DDSException(codecs.ImageDecodeException): exception_priority = 0 # dwFlags of DDSURFACEDESC2 DDSD_CAPS = 0x00000001 DDSD_HEIGHT = 0x00000002 DDSD_WIDTH = 0x00000004 DDSD_PITCH = 0x00000008 DDSD_PIXELFORMAT = 0x00001000 DDSD_MIPMAPCOUNT = 0x00020000 DDSD_LINEARSIZE = 0x00080000 DDSD_DEPTH = 0x00800000 # ddpfPixelFormat of DDSURFACEDESC2 DDPF_ALPHAPIXELS = 0x00000001 DDPF_FOURCC = 0x00000004 DDPF_RGB = 0x00000040 # dwCaps1 of DDSCAPS2 DDSCAPS_COMPLEX = 0x00000008 DDSCAPS_TEXTURE = 0x00001000 DDSCAPS_MIPMAP = 0x00400000 # dwCaps2 of DDSCAPS2 DDSCAPS2_CUBEMAP = 0x00000200 DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400 DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800 DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000 DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000 DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000 DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000 DDSCAPS2_VOLUME = 0x00200000 class _filestruct(object): def __init__(self, data): if len(data) < self.get_size(): raise DDSException('Not a DDS file') items = struct.unpack(self.get_format(), data) for field, value in izip_longest(self._fields, items, fillvalue=None): setattr(self, field[0], value) def __repr__(self): name = self.__class__.__name__ return '%s(%s)' % \ (name, (', \n%s' % (' ' * (len(name) + 1))).join( \ ['%s = %s' % (field[0], repr(getattr(self, field[0]))) \ for field in self._fields])) @classmethod def get_format(cls): return '<' + ''.join([f[1] for f in cls._fields]) @classmethod def get_size(cls): return struct.calcsize(cls.get_format()) class DDSURFACEDESC2(_filestruct): _fields = [ ('dwMagic', '4s'), ('dwSize', 'I'), ('dwFlags', 'I'), ('dwHeight', 'I'), ('dwWidth', 'I'), ('dwPitchOrLinearSize', 'I'), ('dwDepth', 'I'), ('dwMipMapCount', 'I'), ('dwReserved1', '44s'), ('ddpfPixelFormat', '32s'), ('dwCaps1', 'I'), ('dwCaps2', 'I'), ('dwCapsReserved', '8s'), ('dwReserved2', 'I') ] def __init__(self, data): super(DDSURFACEDESC2, self).__init__(data) self.ddpfPixelFormat = DDPIXELFORMAT(self.ddpfPixelFormat) class DDPIXELFORMAT(_filestruct): _fields = [ ('dwSize', 'I'), ('dwFlags', 'I'), ('dwFourCC', '4s'), ('dwRGBBitCount', 'I'), ('dwRBitMask', 'I'), ('dwGBitMask', 'I'), ('dwBBitMask', 'I'), ('dwRGBAlphaBitMask', 'I') ] _compression_formats = { ('DXT1', False): (GL_COMPRESSED_RGB_S3TC_DXT1_EXT, s3tc.decode_dxt1_rgb), ('DXT1', True): (GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, s3tc.decode_dxt1_rgba), ('DXT3', False): (GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, s3tc.decode_dxt3), ('DXT3', True): (GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, s3tc.decode_dxt3), ('DXT5', False): (GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, s3tc.decode_dxt5), ('DXT5', True): (GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, s3tc.decode_dxt5), } def _check_error(): e = glGetError() if e != 0: print 'GL error %d' % e class DDSImageDecoder(codecs.ImageDecoder): def get_file_extensions(self): return ['.dds'] def decode(self, file, filename): header = file.read(DDSURFACEDESC2.get_size()) desc = DDSURFACEDESC2(header) if desc.dwMagic != 'DDS ' or desc.dwSize != 124: raise DDSException('Invalid DDS file (incorrect header).') width = desc.dwWidth height = desc.dwHeight mipmaps = 1 if desc.dwFlags & DDSD_DEPTH: raise DDSException('Volume DDS files unsupported') if desc.dwFlags & DDSD_MIPMAPCOUNT: mipmaps = desc.dwMipMapCount if desc.ddpfPixelFormat.dwSize != 32: raise DDSException('Invalid DDS file (incorrect pixel format).') if desc.dwCaps2 & DDSCAPS2_CUBEMAP: raise DDSException('Cubemap DDS files unsupported') if not desc.ddpfPixelFormat.dwFlags & DDPF_FOURCC: raise DDSException('Uncompressed DDS textures not supported.') has_alpha = desc.ddpfPixelFormat.dwRGBAlphaBitMask != 0 format, decoder = _compression_formats.get( (desc.ddpfPixelFormat.dwFourCC, has_alpha), None) if not format: raise DDSException('Unsupported texture compression %s' % \ desc.ddpfPixelFormat.dwFourCC) if format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT: block_size = 8 else: block_size = 16 datas = [] w, h = width, height for i in range(mipmaps): if not w and not h: break if not w: w = 1 if not h: h = 1 size = ((w + 3) / 4) * ((h + 3) / 4) * block_size data = file.read(size) datas.append(data) w >>= 1 h >>= 1 image = CompressedImageData(width, height, format, datas[0], 'GL_EXT_texture_compression_s3tc', decoder) level = 0 for data in datas[1:]: level += 1 image.set_mipmap_data(level, data) return image def get_decoders(): return [DDSImageDecoder()] def get_encoders(): return []
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: pil.py 163 2006-11-13 04:15:46Z Alex.Holkner $' import sys from ctypes import * from pyglet.gl import * from pyglet.image import * from pyglet.image.codecs import * from pyglet.window.carbon import carbon, quicktime, _oscheck from pyglet.libs.darwin.constants import _name from pyglet.libs.darwin.types import * Handle = POINTER(POINTER(c_byte)) GWorldPtr = c_void_p carbon.NewHandle.restype = Handle HandleDataHandlerSubType = _name('hndl') PointerDataHandlerSubType = _name('ptr ') kDataHCanRead = 1 kDataRefExtensionFileName = _name('fnam') kDataRefExtensionMIMEType = _name('mime') ComponentInstance = c_void_p k1MonochromePixelFormat = 0x00000001 k2IndexedPixelFormat = 0x00000002 k4IndexedPixelFormat = 0x00000004 k8IndexedPixelFormat = 0x00000008 k16BE555PixelFormat = 0x00000010 k24RGBPixelFormat = 0x00000018 k32ARGBPixelFormat = 0x00000020 k32BGRAPixelFormat = _name('BGRA') k1IndexedGrayPixelFormat = 0x00000021 k2IndexedGrayPixelFormat = 0x00000022 k4IndexedGrayPixelFormat = 0x00000024 k8IndexedGrayPixelFormat = 0x00000028 kNativeEndianPixMap = 1 << 8 kGraphicsImporterDontDoGammaCorrection = 1 << 0 kGraphicsImporterDontUseColorMatching = 1 << 3 newMovieActive = 1 noErr = 0 movieTrackMediaType = 1 << 0 movieTrackCharacteristic = 1 << 1 movieTrackEnabledOnly = 1 << 2 VisualMediaCharacteristic = _name('eyes') nextTimeMediaSample = 1 class PointerDataRefRecord(Structure): _fields_ = [ ('data', c_void_p), ('dataLength', c_long) ] def Str255(value): return create_string_buffer(chr(len(value)) + value) class QuickTimeImageDecoder(ImageDecoder): def get_file_extensions(self): # Only most common ones shown here return ['.bmp', '.cur', '.gif', '.ico', '.jpg', '.jpeg', '.pcx', '.png', '.tga', '.tif', '.tiff', '.xbm', '.xpm'] def get_animation_file_extensions(self): return ['.gif'] def _get_data_ref(self, file, filename): self._data_hold = data = create_string_buffer(file.read()) dataref = carbon.NewHandle(sizeof(PointerDataRefRecord)) datarec = cast(dataref, POINTER(POINTER(PointerDataRefRecord))).contents.contents datarec.data = addressof(data) datarec.dataLength = len(data) self._data_handler_holder = data_handler = ComponentInstance() r = quicktime.OpenADataHandler(dataref, PointerDataHandlerSubType, None, 0, None, kDataHCanRead, byref(data_handler)) _oscheck(r) extension_handle = Handle() self._filename_hold = filename = Str255(filename) r = carbon.PtrToHand(filename, byref(extension_handle), len(filename)) r = quicktime.DataHSetDataRefExtension(data_handler, extension_handle, kDataRefExtensionFileName) _oscheck(r) quicktime.DisposeHandle(extension_handle) quicktime.DisposeHandle(dataref) dataref = c_void_p() r = quicktime.DataHGetDataRef(data_handler, byref(dataref)) _oscheck(r) quicktime.CloseComponent(data_handler) return dataref def _get_formats(self): # TODO choose 24 bit where appropriate. if sys.byteorder == 'big': format = 'ARGB' qtformat = k32ARGBPixelFormat else: format = 'BGRA' qtformat = k32BGRAPixelFormat return format, qtformat def decode(self, file, filename): dataref = self._get_data_ref(file, filename) importer = ComponentInstance() quicktime.GetGraphicsImporterForDataRef(dataref, PointerDataHandlerSubType, byref(importer)) if not importer: raise ImageDecodeException(filename or file) rect = Rect() quicktime.GraphicsImportGetNaturalBounds(importer, byref(rect)) width = rect.right height = rect.bottom format, qtformat = self._get_formats() buffer = (c_byte * (width * height * len(format)))() world = GWorldPtr() quicktime.QTNewGWorldFromPtr(byref(world), qtformat, byref(rect), c_void_p(), c_void_p(), 0, buffer, len(format) * width) flags = (kGraphicsImporterDontUseColorMatching | kGraphicsImporterDontDoGammaCorrection) quicktime.GraphicsImportSetFlags(importer, flags) quicktime.GraphicsImportSetGWorld(importer, world, c_void_p()) result = quicktime.GraphicsImportDraw(importer) quicktime.DisposeGWorld(world) quicktime.CloseComponent(importer) if result != 0: raise ImageDecodeException(filename or file) pitch = len(format) * width return ImageData(width, height, format, buffer, -pitch) def decode_animation(self, file, filename): # TODO: Stop playing chicken with the GC # TODO: Cleanup in errors quicktime.EnterMovies() data_ref = self._get_data_ref(file, filename) if not data_ref: raise ImageDecodeException(filename or file) movie = c_void_p() id = c_short() result = quicktime.NewMovieFromDataRef(byref(movie), newMovieActive, 0, data_ref, PointerDataHandlerSubType) if not movie: #_oscheck(result) raise ImageDecodeException(filename or file) quicktime.GoToBeginningOfMovie(movie) time_scale = float(quicktime.GetMovieTimeScale(movie)) format, qtformat = self._get_formats() # Get movie width and height rect = Rect() quicktime.GetMovieBox(movie, byref(rect)) width = rect.right height = rect.bottom pitch = len(format) * width # Set gworld buffer = (c_byte * (width * height * len(format)))() world = GWorldPtr() quicktime.QTNewGWorldFromPtr(byref(world), qtformat, byref(rect), c_void_p(), c_void_p(), 0, buffer, len(format) * width) quicktime.SetGWorld(world, 0) quicktime.SetMovieGWorld(movie, world, 0) visual = quicktime.GetMovieIndTrackType(movie, 1, VisualMediaCharacteristic, movieTrackCharacteristic) if not visual: raise ImageDecodeException('No video track') time = 0 interesting_time = c_int() quicktime.GetTrackNextInterestingTime( visual, nextTimeMediaSample, time, 1, byref(interesting_time), None) duration = interesting_time.value / time_scale frames = [] while time >= 0: result = quicktime.GetMoviesError() if result == noErr: # force redraw result = quicktime.UpdateMovie(movie) if result == noErr: # process movie quicktime.MoviesTask(movie, 0) result = quicktime.GetMoviesError() _oscheck(result) buffer_copy = (c_byte * len(buffer))() memmove(buffer_copy, buffer, len(buffer)) image = ImageData(width, height, format, buffer_copy, -pitch) frames.append(AnimationFrame(image, duration)) interesting_time = c_int() duration = c_int() quicktime.GetTrackNextInterestingTime( visual, nextTimeMediaSample, time, 1, byref(interesting_time), byref(duration)) quicktime.SetMovieTimeValue(movie, interesting_time) time = interesting_time.value duration = duration.value / time_scale if duration <= 0.01: duration = 0.1 quicktime.DisposeMovie(movie) carbon.DisposeHandle(data_ref) quicktime.ExitMovies() return Animation(frames) def get_decoders(): return [QuickTimeImageDecoder()] def get_encoders(): return []
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: pil.py 163 2006-11-13 04:15:46Z Alex.Holkner $' from ctypes import * from pyglet.gl import * from pyglet.image import * from pyglet.image.codecs import * from pyglet.libs.win32.constants import * from pyglet.libs.win32.types import * from pyglet.libs.win32 import _kernel32 as kernel32 ole32 = windll.ole32 gdiplus = windll.gdiplus LPSTREAM = c_void_p REAL = c_float PixelFormat1bppIndexed = 196865 PixelFormat4bppIndexed = 197634 PixelFormat8bppIndexed = 198659 PixelFormat16bppGrayScale = 1052676 PixelFormat16bppRGB555 = 135173 PixelFormat16bppRGB565 = 135174 PixelFormat16bppARGB1555 = 397319 PixelFormat24bppRGB = 137224 PixelFormat32bppRGB = 139273 PixelFormat32bppARGB = 2498570 PixelFormat32bppPARGB = 925707 PixelFormat48bppRGB = 1060876 PixelFormat64bppARGB = 3424269 PixelFormat64bppPARGB = 29622286 PixelFormatMax = 15 ImageLockModeRead = 1 ImageLockModeWrite = 2 ImageLockModeUserInputBuf = 4 class GdiplusStartupInput(Structure): _fields_ = [ ('GdiplusVersion', c_uint32), ('DebugEventCallback', c_void_p), ('SuppressBackgroundThread', BOOL), ('SuppressExternalCodecs', BOOL) ] class GdiplusStartupOutput(Structure): _fields = [ ('NotificationHookProc', c_void_p), ('NotificationUnhookProc', c_void_p) ] class BitmapData(Structure): _fields_ = [ ('Width', c_uint), ('Height', c_uint), ('Stride', c_int), ('PixelFormat', c_int), ('Scan0', POINTER(c_byte)), ('Reserved', POINTER(c_uint)) ] class Rect(Structure): _fields_ = [ ('X', c_int), ('Y', c_int), ('Width', c_int), ('Height', c_int) ] PropertyTagFrameDelay = 0x5100 class PropertyItem(Structure): _fields_ = [ ('id', c_uint), ('length', c_ulong), ('type', c_short), ('value', c_void_p) ] INT_PTR = POINTER(INT) UINT_PTR = POINTER(UINT) ole32.CreateStreamOnHGlobal.argtypes = [HGLOBAL, BOOL, LPSTREAM] gdiplus.GdipBitmapLockBits.restype = c_int gdiplus.GdipBitmapLockBits.argtypes = [c_void_p, c_void_p, UINT, c_int, c_void_p] gdiplus.GdipBitmapUnlockBits.restype = c_int gdiplus.GdipBitmapUnlockBits.argtypes = [c_void_p, c_void_p] gdiplus.GdipCloneStringFormat.restype = c_int gdiplus.GdipCloneStringFormat.argtypes = [c_void_p, c_void_p] gdiplus.GdipCreateBitmapFromScan0.restype = c_int gdiplus.GdipCreateBitmapFromScan0.argtypes = [c_int, c_int, c_int, c_int, POINTER(BYTE), c_void_p] gdiplus.GdipCreateBitmapFromStream.restype = c_int gdiplus.GdipCreateBitmapFromStream.argtypes = [c_void_p, c_void_p] gdiplus.GdipCreateFont.restype = c_int gdiplus.GdipCreateFont.argtypes = [c_void_p, REAL, INT, c_int, c_void_p] gdiplus.GdipCreateFontFamilyFromName.restype = c_int gdiplus.GdipCreateFontFamilyFromName.argtypes = [c_wchar_p, c_void_p, c_void_p] gdiplus.GdipCreateMatrix.restype = None gdiplus.GdipCreateMatrix.argtypes = [c_void_p] gdiplus.GdipCreateSolidFill.restype = c_int gdiplus.GdipCreateSolidFill.argtypes = [c_int, c_void_p] # ARGB gdiplus.GdipDisposeImage.restype = c_int gdiplus.GdipDisposeImage.argtypes = [c_void_p] gdiplus.GdipDrawString.restype = c_int gdiplus.GdipDrawString.argtypes = [c_void_p, c_wchar_p, c_int, c_void_p, c_void_p, c_void_p, c_void_p] gdiplus.GdipFlush.restype = c_int gdiplus.GdipFlush.argtypes = [c_void_p, c_int] gdiplus.GdipGetImageDimension.restype = c_int gdiplus.GdipGetImageDimension.argtypes = [c_void_p, POINTER(REAL), POINTER(REAL)] gdiplus.GdipGetImageGraphicsContext.restype = c_int gdiplus.GdipGetImageGraphicsContext.argtypes = [c_void_p, c_void_p] gdiplus.GdipGetImagePixelFormat.restype = c_int gdiplus.GdipGetImagePixelFormat.argtypes = [c_void_p, c_void_p] gdiplus.GdipGetPropertyItem.restype = c_int gdiplus.GdipGetPropertyItem.argtypes = [c_void_p, c_uint, c_uint, c_void_p] gdiplus.GdipGetPropertyItemSize.restype = c_int gdiplus.GdipGetPropertyItemSize.argtypes = [c_void_p, c_uint, UINT_PTR] gdiplus.GdipGraphicsClear.restype = c_int gdiplus.GdipGraphicsClear.argtypes = [c_void_p, c_int] # ARGB gdiplus.GdipImageGetFrameCount.restype = c_int gdiplus.GdipImageGetFrameCount.argtypes = [c_void_p, c_void_p, UINT_PTR] gdiplus.GdipImageGetFrameDimensionsCount.restype = c_int gdiplus.GdipImageGetFrameDimensionsCount.argtypes = [c_void_p, UINT_PTR] gdiplus.GdipImageGetFrameDimensionsList.restype = c_int gdiplus.GdipImageGetFrameDimensionsList.argtypes = [c_void_p, c_void_p, UINT] gdiplus.GdipImageSelectActiveFrame.restype = c_int gdiplus.GdipImageSelectActiveFrame.argtypes = [c_void_p, c_void_p, UINT] gdiplus.GdipMeasureString.restype = c_int gdiplus.GdipMeasureString.argtypes = [c_void_p, c_wchar_p, c_int, c_void_p, c_void_p, c_void_p, c_void_p, INT_PTR, INT_PTR] gdiplus.GdipNewPrivateFontCollection.restype = c_int gdiplus.GdipNewPrivateFontCollection.argtypes = [c_void_p] gdiplus.GdipPrivateAddMemoryFont.restype = c_int gdiplus.GdipPrivateAddMemoryFont.argtypes = [c_void_p, c_void_p, c_int] gdiplus.GdipSetPageUnit.restype = c_int gdiplus.GdipSetPageUnit.argtypes = [c_void_p, c_int] gdiplus.GdipSetStringFormatFlags.restype = c_int gdiplus.GdipSetStringFormatFlags.argtypes = [c_void_p, c_int] gdiplus.GdipSetTextRenderingHint.restype = c_int gdiplus.GdipSetTextRenderingHint.argtypes = [c_void_p, c_int] gdiplus.GdipStringFormatGetGenericTypographic.restype = c_int gdiplus.GdipStringFormatGetGenericTypographic.argtypes = [c_void_p] gdiplus.GdiplusShutdown.restype = None gdiplus.GdiplusShutdown.argtypes = [POINTER(ULONG)] gdiplus.GdiplusStartup.restype = c_int gdiplus.GdiplusStartup.argtypes = [c_void_p, c_void_p, c_void_p] class GDIPlusDecoder(ImageDecoder): def get_file_extensions(self): return ['.bmp', '.gif', '.jpg', '.jpeg', '.exif', '.png', '.tif', '.tiff'] def get_animation_file_extensions(self): # TIFF also supported as a multi-page image; but that's not really an # animation, is it? return ['.gif'] def _load_bitmap(self, file, filename): data = file.read() # Create a HGLOBAL with image data hglob = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data)) ptr = kernel32.GlobalLock(hglob) memmove(ptr, data, len(data)) kernel32.GlobalUnlock(hglob) # Create IStream for the HGLOBAL stream = LPSTREAM() ole32.CreateStreamOnHGlobal(hglob, True, byref(stream)) # Load image from stream bitmap = c_void_p() status = gdiplus.GdipCreateBitmapFromStream(stream, byref(bitmap)) if status != 0: # TODO release stream raise ImageDecodeException( 'GDI+ cannot load %r' % (filename or file)) return bitmap def _get_image(self, bitmap): # Get size of image (Bitmap subclasses Image) width = REAL() height = REAL() gdiplus.GdipGetImageDimension(bitmap, byref(width), byref(height)) width = int(width.value) height = int(height.value) # Get image pixel format pf = c_int() gdiplus.GdipGetImagePixelFormat(bitmap, byref(pf)) pf = pf.value # Reverse from what's documented because of Intel little-endianness. format = 'BGRA' if pf == PixelFormat24bppRGB: format = 'BGR' elif pf == PixelFormat32bppRGB: pass elif pf == PixelFormat32bppARGB: pass elif pf in (PixelFormat16bppARGB1555, PixelFormat32bppPARGB, PixelFormat64bppARGB, PixelFormat64bppPARGB): pf = PixelFormat32bppARGB else: format = 'BGR' pf = PixelFormat24bppRGB # Lock pixel data in best format rect = Rect() rect.X = 0 rect.Y = 0 rect.Width = width rect.Height = height bitmap_data = BitmapData() gdiplus.GdipBitmapLockBits(bitmap, byref(rect), ImageLockModeRead, pf, byref(bitmap_data)) # Create buffer for RawImage buffer = create_string_buffer(bitmap_data.Stride * height) memmove(buffer, bitmap_data.Scan0, len(buffer)) # Unlock data gdiplus.GdipBitmapUnlockBits(bitmap, byref(bitmap_data)) return ImageData(width, height, format, buffer, -bitmap_data.Stride) def _delete_bitmap(self, bitmap): # Release image and stream gdiplus.GdipDisposeImage(bitmap) # TODO: How to call IUnknown::Release on stream? def decode(self, file, filename): bitmap = self._load_bitmap(file, filename) image = self._get_image(bitmap) self._delete_bitmap(bitmap) return image def decode_animation(self, file, filename): bitmap = self._load_bitmap(file, filename) dimension_count = c_uint() gdiplus.GdipImageGetFrameDimensionsCount(bitmap, byref(dimension_count)) if dimension_count.value < 1: self._delete_bitmap(bitmap) raise ImageDecodeException('Image has no frame dimensions') # XXX Make sure this dimension is time? dimensions = (c_void_p * dimension_count.value)() gdiplus.GdipImageGetFrameDimensionsList(bitmap, dimensions, dimension_count.value) frame_count = c_uint() gdiplus.GdipImageGetFrameCount(bitmap, dimensions, byref(frame_count)) prop_id = PropertyTagFrameDelay prop_size = c_uint() gdiplus.GdipGetPropertyItemSize(bitmap, prop_id, byref(prop_size)) prop_buffer = c_buffer(prop_size.value) prop_item = cast(prop_buffer, POINTER(PropertyItem)).contents gdiplus.GdipGetPropertyItem(bitmap, prop_id, prop_size.value, prop_buffer) # XXX Sure it's long? n_delays = prop_item.length / sizeof(c_long) delays = cast(prop_item.value, POINTER(c_long * n_delays)).contents frames = [] for i in range(frame_count.value): gdiplus.GdipImageSelectActiveFrame(bitmap, dimensions, i) image = self._get_image(bitmap) delay = delays[i] if delay <= 1: delay = 10 frames.append(AnimationFrame(image, delay/100.)) self._delete_bitmap(bitmap) return Animation(frames) def get_decoders(): return [GDIPlusDecoder()] def get_encoders(): return [] def init(): token = c_ulong() startup_in = GdiplusStartupInput() startup_in.GdiplusVersion = 1 startup_out = GdiplusStartupOutput() gdiplus.GdiplusStartup(byref(token), byref(startup_in), byref(startup_out)) # Shutdown later? # gdiplus.GdiplusShutdown(token) init()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import os.path from pyglet.gl import * from pyglet.image import * from pyglet.image.codecs import * try: import Image except ImportError: from PIL import Image class PILImageDecoder(ImageDecoder): def get_file_extensions(self): # Only most common ones shown here return ['.bmp', '.cur', '.gif', '.ico', '.jpg', '.jpeg', '.pcx', '.png', '.tga', '.tif', '.tiff', '.xbm', '.xpm'] def decode(self, file, filename): try: image = Image.open(file) except Exception, e: raise ImageDecodeException( 'PIL cannot read %r: %s' % (filename or file, e)) image = image.transpose(Image.FLIP_TOP_BOTTOM) # Convert bitmap and palette images to component if image.mode in ('1', 'P'): image = image.convert() if image.mode not in ('L', 'LA', 'RGB', 'RGBA'): raise ImageDecodeException('Unsupported mode "%s"' % image.mode) type = GL_UNSIGNED_BYTE width, height = image.size return ImageData(width, height, image.mode, image.tostring()) class PILImageEncoder(ImageEncoder): def get_file_extensions(self): # Most common only return ['.bmp', '.eps', '.gif', '.jpg', '.jpeg', '.pcx', '.png', '.ppm', '.tiff', '.xbm'] def encode(self, image, file, filename): # File format is guessed from filename extension, otherwise defaults # to PNG. pil_format = (filename and os.path.splitext(filename)[1][1:]) or 'png' if pil_format.lower() == 'jpg': pil_format = 'JPEG' image = image.get_image_data() format = image.format if format != 'RGB': # Only save in RGB or RGBA formats. format = 'RGBA' pitch = -(image.width * len(format)) # Note: Don't try and use frombuffer(..); different versions of # PIL will orient the image differently. pil_image = Image.fromstring( format, (image.width, image.height), image.get_data(format, pitch)) try: pil_image.save(file, pil_format) except Exception, e: raise ImageEncodeException(e) def get_decoders(): return [PILImageDecoder()] def get_encoders(): return [PILImageEncoder()]
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ '''Software decoder for S3TC compressed texture (i.e., DDS). http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt ''' import ctypes import re from pyglet.gl import * from pyglet.gl import gl_info from pyglet.image import AbstractImage, Texture split_8byte = re.compile('.' * 8, flags=re.DOTALL) split_16byte = re.compile('.' * 16, flags=re.DOTALL) class PackedImageData(AbstractImage): _current_texture = None def __init__(self, width, height, format, packed_format, data): super(PackedImageData, self).__init__(width, height) self.format = format self.packed_format = packed_format self.data = data def unpack(self): if self.packed_format == GL_UNSIGNED_SHORT_5_6_5: # Unpack to GL_RGB. Assume self.data is already 16-bit i = 0 out = (ctypes.c_ubyte * (self.width * self.height * 3))() for c in self.data: out[i+2] = (c & 0x1f) << 3 out[i+1] = (c & 0x7e0) >> 3 out[i] = (c & 0xf800) >> 8 i += 3 self.data = out self.packed_format = GL_UNSIGNED_BYTE def _get_texture(self): if self._current_texture: return self._current_texture texture = Texture.create_for_size( GL_TEXTURE_2D, self.width, self.height) glBindTexture(texture.target, texture.id) glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR) if not gl_info.have_version(1, 2) or True: self.unpack() glTexImage2D(texture.target, texture.level, self.format, self.width, self.height, 0, self.format, self.packed_format, self.data) self._current_texture = texture return texture texture = property(_get_texture) def get_texture(self, rectangle=False, force_rectangle=False): '''The parameters 'rectangle' and 'force_rectangle' are ignored. See the documentation of the method 'AbstractImage.get_texture' for a more detailed documentation of the method. ''' return self._get_texture() def decode_dxt1_rgb(data, width, height): # Decode to 16-bit RGB UNSIGNED_SHORT_5_6_5 out = (ctypes.c_uint16 * (width * height))() # Read 8 bytes at a time image_offset = 0 for c0_lo, c0_hi, c1_lo, c1_hi, b0, b1, b2, b3 in split_8byte.findall(data): color0 = ord(c0_lo) | ord(c0_hi) << 8 color1 = ord(c1_lo) | ord(c1_hi) << 8 bits = ord(b0) | ord(b1) << 8 | ord(b2) << 16 | ord(b3) << 24 r0 = color0 & 0x1f g0 = (color0 & 0x7e0) >> 5 b0 = (color0 & 0xf800) >> 11 r1 = color1 & 0x1f g1 = (color1 & 0x7e0) >> 5 b1 = (color1 & 0xf800) >> 11 # i is the dest ptr for this block i = image_offset for y in range(4): for x in range(4): code = bits & 0x3 if code == 0: out[i] = color0 elif code == 1: out[i] = color1 elif code == 3 and color0 <= color1: out[i] = 0 else: if code == 2 and color0 > color1: r = (2 * r0 + r1) / 3 g = (2 * g0 + g1) / 3 b = (2 * b0 + b1) / 3 elif code == 3 and color0 > color1: r = (r0 + 2 * r1) / 3 g = (g0 + 2 * g1) / 3 b = (b0 + 2 * b1) / 3 else: assert code == 2 and color0 <= color1 r = (r0 + r1) / 2 g = (g0 + g1) / 2 b = (b0 + b1) / 2 out[i] = r | g << 5 | b << 11 bits >>= 2 i += 1 i += width - 4 # Move dest ptr to next 4x4 block advance_row = (image_offset + 4) % width == 0 image_offset += width * 3 * advance_row + 4 return PackedImageData(width, height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, out) def decode_dxt1_rgba(data, width, height): # Decode to GL_RGBA out = (ctypes.c_ubyte * (width * height * 4))() pitch = width << 2 # Read 8 bytes at a time image_offset = 0 for c0_lo, c0_hi, c1_lo, c1_hi, b0, b1, b2, b3 in split_8byte.findall(data): color0 = ord(c0_lo) | ord(c0_hi) << 8 color1 = ord(c1_lo) | ord(c1_hi) << 8 bits = ord(b0) | ord(b1) << 8 | ord(b2) << 16 | ord(b3) << 24 r0 = color0 & 0x1f g0 = (color0 & 0x7e0) >> 5 b0 = (color0 & 0xf800) >> 11 r1 = color1 & 0x1f g1 = (color1 & 0x7e0) >> 5 b1 = (color1 & 0xf800) >> 11 # i is the dest ptr for this block i = image_offset for y in range(4): for x in range(4): code = bits & 0x3 a = 255 if code == 0: r, g, b = r0, g0, b0 elif code == 1: r, g, b = r1, g1, b1 elif code == 3 and color0 <= color1: r = g = b = a = 0 else: if code == 2 and color0 > color1: r = (2 * r0 + r1) / 3 g = (2 * g0 + g1) / 3 b = (2 * b0 + b1) / 3 elif code == 3 and color0 > color1: r = (r0 + 2 * r1) / 3 g = (g0 + 2 * g1) / 3 b = (b0 + 2 * b1) / 3 else: assert code == 2 and color0 <= color1 r = (r0 + r1) / 2 g = (g0 + g1) / 2 b = (b0 + b1) / 2 out[i] = b << 3 out[i+1] = g << 2 out[i+2] = r << 3 out[i+3] = a << 4 bits >>= 2 i += 4 i += pitch - 16 # Move dest ptr to next 4x4 block advance_row = (image_offset + 16) % pitch == 0 image_offset += pitch * 3 * advance_row + 16 return PackedImageData(width, height, GL_RGBA, GL_UNSIGNED_BYTE, out) def decode_dxt3(data, width, height): # Decode to GL_RGBA out = (ctypes.c_ubyte * (width * height * 4))() pitch = width << 2 # Read 16 bytes at a time image_offset = 0 for (a0, a1, a2, a3, a4, a5, a6, a7, c0_lo, c0_hi, c1_lo, c1_hi, b0, b1, b2, b3) in split_16byte.findall(data): color0 = ord(c0_lo) | ord(c0_hi) << 8 color1 = ord(c1_lo) | ord(c1_hi) << 8 bits = ord(b0) | ord(b1) << 8 | ord(b2) << 16 | ord(b3) << 24 alpha = ord(a0) | ord(a1) << 8 | ord(a2) << 16 | ord(a3) << 24 | \ ord(a4) << 32 | ord(a5) << 40 | ord(a6) << 48 | ord(a7) << 56 r0 = color0 & 0x1f g0 = (color0 & 0x7e0) >> 5 b0 = (color0 & 0xf800) >> 11 r1 = color1 & 0x1f g1 = (color1 & 0x7e0) >> 5 b1 = (color1 & 0xf800) >> 11 # i is the dest ptr for this block i = image_offset for y in range(4): for x in range(4): code = bits & 0x3 a = alpha & 0xf if code == 0: r, g, b = r0, g0, b0 elif code == 1: r, g, b = r1, g1, b1 elif code == 3 and color0 <= color1: r = g = b = 0 else: if code == 2 and color0 > color1: r = (2 * r0 + r1) / 3 g = (2 * g0 + g1) / 3 b = (2 * b0 + b1) / 3 elif code == 3 and color0 > color1: r = (r0 + 2 * r1) / 3 g = (g0 + 2 * g1) / 3 b = (b0 + 2 * b1) / 3 else: assert code == 2 and color0 <= color1 r = (r0 + r1) / 2 g = (g0 + g1) / 2 b = (b0 + b1) / 2 out[i] = b << 3 out[i+1] = g << 2 out[i+2] = r << 3 out[i+3] = a << 4 bits >>= 2 alpha >>= 4 i += 4 i += pitch - 16 # Move dest ptr to next 4x4 block advance_row = (image_offset + 16) % pitch == 0 image_offset += pitch * 3 * advance_row + 16 return PackedImageData(width, height, GL_RGBA, GL_UNSIGNED_BYTE, out) def decode_dxt5(data, width, height): # Decode to GL_RGBA out = (ctypes.c_ubyte * (width * height * 4))() pitch = width << 2 # Read 16 bytes at a time image_offset = 0 for (alpha0, alpha1, ab0, ab1, ab2, ab3, ab4, ab5, c0_lo, c0_hi, c1_lo, c1_hi, b0, b1, b2, b3) in split_16byte.findall(data): color0 = ord(c0_lo) | ord(c0_hi) << 8 color1 = ord(c1_lo) | ord(c1_hi) << 8 alpha0 = ord(alpha0) alpha1 = ord(alpha1) bits = ord(b0) | ord(b1) << 8 | ord(b2) << 16 | ord(b3) << 24 abits = ord(ab0) | ord(ab1) << 8 | ord(ab2) << 16 | ord(ab3) << 24 | \ ord(ab4) << 32 | ord(ab5) << 40 r0 = color0 & 0x1f g0 = (color0 & 0x7e0) >> 5 b0 = (color0 & 0xf800) >> 11 r1 = color1 & 0x1f g1 = (color1 & 0x7e0) >> 5 b1 = (color1 & 0xf800) >> 11 # i is the dest ptr for this block i = image_offset for y in range(4): for x in range(4): code = bits & 0x3 acode = abits & 0x7 if code == 0: r, g, b = r0, g0, b0 elif code == 1: r, g, b = r1, g1, b1 elif code == 3 and color0 <= color1: r = g = b = 0 else: if code == 2 and color0 > color1: r = (2 * r0 + r1) / 3 g = (2 * g0 + g1) / 3 b = (2 * b0 + b1) / 3 elif code == 3 and color0 > color1: r = (r0 + 2 * r1) / 3 g = (g0 + 2 * g1) / 3 b = (b0 + 2 * b1) / 3 else: assert code == 2 and color0 <= color1 r = (r0 + r1) / 2 g = (g0 + g1) / 2 b = (b0 + b1) / 2 if acode == 0: a = alpha0 elif acode == 1: a = alpha1 elif alpha0 > alpha1: if acode == 2: a = (6 * alpha0 + 1 * alpha1) / 7 elif acode == 3: a = (5 * alpha0 + 2 * alpha1) / 7 elif acode == 4: a = (4 * alpha0 + 3 * alpha1) / 7 elif acode == 5: a = (3 * alpha0 + 4 * alpha1) / 7 elif acode == 6: a = (2 * alpha0 + 5 * alpha1) / 7 else: assert acode == 7 a = (1 * alpha0 + 6 * alpha1) / 7 else: if acode == 2: a = (4 * alpha0 + 1 * alpha1) / 5 elif acode == 3: a = (3 * alpha0 + 2 * alpha1) / 5 elif acode == 4: a = (2 * alpha0 + 3 * alpha1) / 5 elif acode == 5: a = (1 * alpha0 + 4 * alpha1) / 5 elif acode == 6: a = 0 else: assert acode == 7 a = 255 out[i] = b << 3 out[i+1] = g << 2 out[i+2] = r << 3 out[i+3] = a bits >>= 2 abits >>= 3 i += 4 i += pitch - 16 # Move dest ptr to next 4x4 block advance_row = (image_offset + 16) % pitch == 0 image_offset += pitch * 3 * advance_row + 16 return PackedImageData(width, height, GL_RGBA, GL_UNSIGNED_BYTE, out)
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Encoder and decoder for PNG files, using PyPNG (pypng.py). ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import array from pyglet.gl import * from pyglet.image import * from pyglet.image.codecs import * import pyglet.image.codecs.pypng class PNGImageDecoder(ImageDecoder): def get_file_extensions(self): return ['.png'] def decode(self, file, filename): try: reader = pyglet.image.codecs.pypng.Reader(file=file) width, height, pixels, metadata = reader.read() except Exception, e: raise ImageDecodeException( 'PyPNG cannot read %r: %s' % (filename or file, e)) if metadata['greyscale']: if metadata['has_alpha']: format = 'LA' else: format = 'L' else: if metadata['has_alpha']: format = 'RGBA' else: format = 'RGB' pitch = len(format) * width return ImageData(width, height, format, pixels.tostring(), -pitch) class PNGImageEncoder(ImageEncoder): def get_file_extensions(self): return ['.png'] def encode(self, image, file, filename): image = image.get_image_data() has_alpha = 'A' in image.format greyscale = len(image.format) < 3 if has_alpha: if greyscale: image.format = 'LA' else: image.format = 'RGBA' else: if greyscale: image.format = 'L' else: image.format = 'RGB' image.pitch = -(image.width * len(image.format)) writer = pyglet.image.codecs.pypng.Writer( image.width, image.height, bytes_per_sample=1, greyscale=greyscale, has_alpha=has_alpha) data = array.array('B') data.fromstring(image.data) writer.write_array(file, data) def get_decoders(): return [PNGImageDecoder()] def get_encoders(): return [PNGImageEncoder()]
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Decoder for BMP files. Currently supports version 3 and 4 bitmaps with BI_RGB and BI_BITFIELDS encoding. Alpha channel is supported for 32-bit BI_RGB only. ''' # Official docs are at # http://msdn2.microsoft.com/en-us/library/ms532311.aspx # # But some details including alignment and bit/byte order are omitted; see # http://www.fileformat.info/format/bmp/egff.htm __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from pyglet.image import ImageData from pyglet.image.codecs import ImageDecoder, ImageDecodeException BYTE = ctypes.c_ubyte WORD = ctypes.c_uint16 DWORD = ctypes.c_uint32 LONG = ctypes.c_int32 FXPT2DOT30 = ctypes.c_uint32 BI_RGB = 0 BI_RLE8 = 1 BI_RLE4 = 2 BI_BITFIELDS = 3 class BITMAPFILEHEADER(ctypes.LittleEndianStructure): _pack_ = 1 _fields_ = [ ('bfType', WORD), ('bfSize', DWORD), ('bfReserved1', WORD), ('bfReserved2', WORD), ('bfOffBits', DWORD) ] class BITMAPINFOHEADER(ctypes.LittleEndianStructure): _pack_ = 1 _fields_ = [ ('biSize', DWORD), ('biWidth', LONG), ('biHeight', LONG), ('biPlanes', WORD), ('biBitCount', WORD), ('biCompression', DWORD), ('biSizeImage', DWORD), ('biXPelsPerMeter', LONG), ('biYPelsPerMeter', LONG), ('biClrUsed', DWORD), ('biClrImportant', DWORD) ] CIEXYZTRIPLE = FXPT2DOT30 * 9 class BITMAPV4HEADER(ctypes.LittleEndianStructure): _pack_ = 1 _fields_ = [ ('biSize', DWORD), ('biWidth', LONG), ('biHeight', LONG), ('biPlanes', WORD), ('biBitCount', WORD), ('biCompression', DWORD), ('biSizeImage', DWORD), ('biXPelsPerMeter', LONG), ('biYPelsPerMeter', LONG), ('biClrUsed', DWORD), ('biClrImportant', DWORD), ('bV4RedMask', DWORD), ('bV4GreenMask', DWORD), ('bV4BlueMask', DWORD), ('bV4AlphaMask', DWORD), ('bV4CSType', DWORD), ('bV4Endpoints', CIEXYZTRIPLE), ('bV4GammaRed', DWORD), ('bV4GammaGreen', DWORD), ('bV4GammaBlue', DWORD), ] class RGBFields(ctypes.LittleEndianStructure): _pack_ = 1 _fields_ = [ ('red', DWORD), ('green', DWORD), ('blue', DWORD), ] class RGBQUAD(ctypes.LittleEndianStructure): _pack_ = 1 _fields_ = [ ('rgbBlue', BYTE), ('rgbGreen', BYTE), ('rgbRed', BYTE), ('rgbReserved', BYTE) ] def __repr__(self): return '<%d, %d, %d>' % (self.rgbRed, self.rgbGreen, self.rgbBlue) def ptr_add(ptr, offset): address = ctypes.addressof(ptr.contents) + offset return ctypes.pointer(type(ptr.contents).from_address(address)) def to_ctypes(buffer, offset, type): if offset + ctypes.sizeof(type) > len(buffer): raise ImageDecodeException('BMP file is truncated') ptr = ptr_add(ctypes.pointer(buffer), offset) return ctypes.cast(ptr, ctypes.POINTER(type)).contents class BMPImageDecoder(ImageDecoder): def get_file_extensions(self): return ['.bmp'] def decode(self, file, filename): if not file: file = open(filename, 'rb') bytes = file.read() buffer = ctypes.c_buffer(bytes) if bytes[:2] != 'BM': raise ImageDecodeException( 'Not a Windows bitmap file: %r' % (filename or file)) file_header = to_ctypes(buffer, 0, BITMAPFILEHEADER) bits_offset = file_header.bfOffBits info_header_offset = ctypes.sizeof(BITMAPFILEHEADER) info_header = to_ctypes(buffer, info_header_offset, BITMAPINFOHEADER) palette_offset = info_header_offset + info_header.biSize if info_header.biSize < ctypes.sizeof(BITMAPINFOHEADER): raise ImageDecodeException( 'Unsupported BMP type: %r' % (filename or file)) width = info_header.biWidth height = info_header.biHeight if width <= 0 or info_header.biPlanes != 1: raise ImageDecodeException( 'BMP file has corrupt parameters: %r' % (filename or file)) pitch_sign = height < 0 and -1 or 1 height = abs(height) compression = info_header.biCompression if compression not in (BI_RGB, BI_BITFIELDS): raise ImageDecodeException( 'Unsupported compression: %r' % (filename or file)) clr_used = 0 bitcount = info_header.biBitCount if bitcount == 1: pitch = (width + 7) // 8 bits_type = ctypes.c_ubyte decoder = decode_1bit elif bitcount == 4: pitch = (width + 1) // 2 bits_type = ctypes.c_ubyte decoder = decode_4bit elif bitcount == 8: bits_type = ctypes.c_ubyte pitch = width decoder = decode_8bit elif bitcount == 16: pitch = width * 2 bits_type = ctypes.c_uint16 decoder = decode_bitfields elif bitcount == 24: pitch = width * 3 bits_type = ctypes.c_ubyte decoder = decode_24bit elif bitcount == 32: pitch = width * 4 if compression == BI_RGB: decoder = decode_32bit_rgb bits_type = ctypes.c_ubyte elif compression == BI_BITFIELDS: decoder = decode_bitfields bits_type = ctypes.c_uint32 else: raise ImageDecodeException( 'Unsupported compression: %r' % (filename or file)) else: raise ImageDecodeException( 'Unsupported bit count %d: %r' % (bitcount, filename or file)) pitch = (pitch + 3) & ~3 packed_width = pitch // ctypes.sizeof(bits_type) if bitcount < 16 and compression == BI_RGB: clr_used = info_header.biClrUsed or (1 << bitcount) palette = to_ctypes(buffer, palette_offset, RGBQUAD * clr_used) bits = to_ctypes(buffer, bits_offset, bits_type * packed_width * height) return decoder(bits, palette, width, height, pitch, pitch_sign) elif bitcount >= 16 and compression == BI_RGB: bits = to_ctypes(buffer, bits_offset, bits_type * (packed_width * height)) return decoder(bits, None, width, height, pitch, pitch_sign) elif compression == BI_BITFIELDS: if info_header.biSize >= ctypes.sizeof(BITMAPV4HEADER): info_header = to_ctypes(buffer, info_header_offset, BITMAPV4HEADER) r_mask = info_header.bV4RedMask g_mask = info_header.bV4GreenMask b_mask = info_header.bV4BlueMask else: fields_offset = info_header_offset + \ ctypes.sizeof(BITMAPINFOHEADER) fields = to_ctypes(buffer, fields_offset, RGBFields) r_mask = fields.red g_mask = fields.green b_mask = fields.blue class _BitsArray(ctypes.LittleEndianStructure): _pack_ = 1 _fields_ = [ ('data', bits_type * packed_width * height), ] bits = to_ctypes(buffer, bits_offset, _BitsArray).data return decoder(bits, r_mask, g_mask, b_mask, width, height, pitch, pitch_sign) def decode_1bit(bits, palette, width, height, pitch, pitch_sign): rgb_pitch = (((pitch << 3) + 7) & ~0x7) * 3 buffer = (ctypes.c_ubyte * (height * rgb_pitch))() i = 0 for row in bits: for packed in row: for _ in range(8): rgb = palette[(packed & 0x80) >> 7] buffer[i] = rgb.rgbRed buffer[i + 1] = rgb.rgbGreen buffer[i + 2] = rgb.rgbBlue i += 3 packed <<= 1 return ImageData(width, height, 'RGB', buffer, pitch_sign * rgb_pitch) def decode_4bit(bits, palette, width, height, pitch, pitch_sign): rgb_pitch = (((pitch << 1) + 1) & ~0x1) * 3 buffer = (ctypes.c_ubyte * (height * rgb_pitch))() i = 0 for row in bits: for packed in row: for index in ((packed & 0xf0) >> 4, packed & 0xf): rgb = palette[index] buffer[i] = rgb.rgbRed buffer[i + 1] = rgb.rgbGreen buffer[i + 2] = rgb.rgbBlue i += 3 return ImageData(width, height, 'RGB', buffer, pitch_sign * rgb_pitch) def decode_8bit(bits, palette, width, height, pitch, pitch_sign): rgb_pitch = pitch * 3 buffer = (ctypes.c_ubyte * (height * rgb_pitch))() i = 0 for row in bits: for index in row: rgb = palette[index] buffer[i] = rgb.rgbRed buffer[i + 1] = rgb.rgbGreen buffer[i + 2] = rgb.rgbBlue i += 3 return ImageData(width, height, 'RGB', buffer, pitch_sign * rgb_pitch) def decode_24bit(bits, palette, width, height, pitch, pitch_sign): buffer = (ctypes.c_ubyte * (height * pitch))() ctypes.memmove(buffer, bits, len(buffer)) return ImageData(width, height, 'BGR', buffer, pitch_sign * pitch) def decode_32bit_rgb(bits, palette, width, height, pitch, pitch_sign): buffer = (ctypes.c_ubyte * (height * pitch))() ctypes.memmove(buffer, bits, len(buffer)) return ImageData(width, height, 'BGRA', buffer, pitch_sign * pitch) def get_shift(mask): if not mask: return 0 # Shift down shift = 0 while not (1 << shift) & mask: shift += 1 # Shift up shift_up = 0 while (mask >> shift) >> shift_up: shift_up += 1 s = shift - (8 - shift_up) if s < 0: return 0, -s else: return s, 0 def decode_bitfields(bits, r_mask, g_mask, b_mask, width, height, pitch, pitch_sign): r_shift1, r_shift2 = get_shift(r_mask) g_shift1, g_shift2 = get_shift(g_mask) b_shift1, b_shift2 = get_shift(b_mask) rgb_pitch = 3 * len(bits[0]) buffer = (ctypes.c_ubyte * (height * rgb_pitch))() i = 0 for row in bits: for packed in row: buffer[i] = (packed & r_mask) >> r_shift1 << r_shift2 buffer[i+1] = (packed & g_mask) >> g_shift1 << g_shift2 buffer[i+2] = (packed & b_mask) >> b_shift1 << b_shift2 i += 3 return ImageData(width, height, 'RGB', buffer, pitch_sign * rgb_pitch) def get_decoders(): return [BMPImageDecoder()] def get_encoders(): return []
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' from ctypes import * from pyglet.gl import * from pyglet.image import * from pyglet.image.codecs import * from pyglet.image.codecs import gif import pyglet.lib import pyglet.window gdk = pyglet.lib.load_library('gdk-x11-2.0') gdkpixbuf = pyglet.lib.load_library('gdk_pixbuf-2.0') GdkPixbufLoader = c_void_p GdkPixbuf = c_void_p gdkpixbuf.gdk_pixbuf_loader_new.restype = GdkPixbufLoader gdkpixbuf.gdk_pixbuf_loader_get_pixbuf.restype = GdkPixbuf gdkpixbuf.gdk_pixbuf_get_pixels.restype = c_void_p gdkpixbuf.gdk_pixbuf_loader_get_animation.restype = c_void_p gdkpixbuf.gdk_pixbuf_animation_get_iter.restype = c_void_p gdkpixbuf.gdk_pixbuf_animation_iter_get_pixbuf.restype = GdkPixbuf class GTimeVal(Structure): _fields_ = [ ('tv_sec', c_long), ('tv_usec', c_long) ] class GdkPixbuf2ImageDecoder(ImageDecoder): def get_file_extensions(self): return ['.png', '.xpm', '.jpg', '.jpeg', '.tif', '.tiff', '.pnm', '.ras', '.bmp', '.gif'] def get_animation_file_extensions(self): return ['.gif', '.ani'] def _load(self, file, filename, load_func): data = file.read() loader = gdkpixbuf.gdk_pixbuf_loader_new() gdkpixbuf.gdk_pixbuf_loader_write(loader, data, len(data), None) if not gdkpixbuf.gdk_pixbuf_loader_close(loader, None): raise ImageDecodeException(filename) result = load_func(loader) if not result: raise ImageDecodeException('Unable to load: %s' % filename) return result def _pixbuf_to_image(self, pixbuf): # Get format and dimensions width = gdkpixbuf.gdk_pixbuf_get_width(pixbuf) height = gdkpixbuf.gdk_pixbuf_get_height(pixbuf) channels = gdkpixbuf.gdk_pixbuf_get_n_channels(pixbuf) rowstride = gdkpixbuf.gdk_pixbuf_get_rowstride(pixbuf) #has_alpha = gdkpixbuf.gdk_pixbuf_get_has_alpha(pixbuf) pixels = gdkpixbuf.gdk_pixbuf_get_pixels(pixbuf) # Copy pixel data. buffer = (c_ubyte * (rowstride * height))() memmove(buffer, pixels, rowstride * (height - 1) + width * channels) # Release pixbuf gdk.g_object_unref(pixbuf) # Determine appropriate GL type if channels == 3: format = 'RGB' else: format = 'RGBA' return ImageData(width, height, format, buffer, -rowstride) def decode(self, file, filename): pixbuf = self._load(file, filename, gdkpixbuf.gdk_pixbuf_loader_get_pixbuf) return self._pixbuf_to_image(pixbuf) def decode_animation(self, file, filename): # Extract GIF control data. If it's not a GIF, this method will # raise. gif_stream = gif.read(file) delays = [image.delay for image in gif_stream.images] # Get GDK animation iterator file.seek(0) anim = self._load(file, filename, gdkpixbuf.gdk_pixbuf_loader_get_animation) time = GTimeVal(0, 0) iter = gdkpixbuf.gdk_pixbuf_animation_get_iter(anim, byref(time)) frames = [] # Extract each image for control_delay in delays: pixbuf = gdkpixbuf.gdk_pixbuf_animation_iter_get_pixbuf(iter) # When attempting to load animated gifs with an alpha channel on # linux gdkpixbuf will normally return a null pixbuf for the final # frame resulting in a segfault: # http://code.google.com/p/pyglet/issues/detail?id=411 # Since it is unclear why exactly this happens, the workaround # below is to start again and extract that frame on its own. if pixbuf == None: file.seek(0) anim = self._load(file, filename, gdkpixbuf.gdk_pixbuf_loader_get_animation) temptime = GTimeVal(0, 0) iter = gdkpixbuf.gdk_pixbuf_animation_get_iter(anim, byref(temptime)) gdkpixbuf.gdk_pixbuf_animation_iter_advance(iter, byref(time)) pixbuf = gdkpixbuf.gdk_pixbuf_animation_iter_get_pixbuf(iter) image = self._pixbuf_to_image(pixbuf) frames.append(AnimationFrame(image, control_delay)) gdk_delay = gdkpixbuf.gdk_pixbuf_animation_iter_get_delay_time(iter) if gdk_delay == -1: break gdk_delay = gdkpixbuf.gdk_pixbuf_animation_iter_get_delay_time(iter) gdk_delay *= 1000 # milliseconds to microseconds # Compare gdk_delay to control_delay for interest only. #print control_delay, gdk_delay / 1000000. us = time.tv_usec + gdk_delay time.tv_sec += us // 1000000 time.tv_usec = us % 1000000 gdkpixbuf.gdk_pixbuf_animation_iter_advance(iter, byref(time)) return Animation(frames) def get_decoders(): return [GdkPixbuf2ImageDecoder()] def get_encoders(): return [] def init(): gdk.g_type_init() init()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # png.py - PNG encoder in pure Python # Copyright (C) 2006 Johann C. Rocholl <johann@browsershots.org> # <ah> Modifications for pyglet by Alex Holkner <alex.holkner@gmail.com> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Contributors (alphabetical): # Nicko van Someren <nicko@nicko.org> # # Changelog (recent first): # 2006-06-17 Nicko: Reworked into a class, faster interlacing. # 2006-06-17 Johann: Very simple prototype PNG decoder. # 2006-06-17 Nicko: Test suite with various image generators. # 2006-06-17 Nicko: Alpha-channel, grey-scale, 16-bit/plane support. # 2006-06-15 Johann: Scanline iterator interface for large input files. # 2006-06-09 Johann: Very simple prototype PNG encoder. """ Pure Python PNG Reader/Writer This is an implementation of a subset of the PNG specification at http://www.w3.org/TR/2003/REC-PNG-20031110 in pure Python. It reads and writes PNG files with 8/16/24/32/48/64 bits per pixel (greyscale, RGB, RGBA, with 8 or 16 bits per layer), with a number of options. For help, type "import png; help(png)" in your python interpreter. This file can also be used as a command-line utility to convert PNM files to PNG. The interface is similar to that of the pnmtopng program from the netpbm package. Type "python png.py --help" at the shell prompt for usage and a list of options. """ __revision__ = '$Rev$' __date__ = '$Date$' __author__ = '$Author$' import sys import zlib import struct import math from array import array from pyglet.compat import asbytes _adam7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)) def interleave_planes(ipixels, apixels, ipsize, apsize): """ Interleave color planes, e.g. RGB + A = RGBA. Return an array of pixels consisting of the ipsize bytes of data from each pixel in ipixels followed by the apsize bytes of data from each pixel in apixels, for an image of size width x height. """ itotal = len(ipixels) atotal = len(apixels) newtotal = itotal + atotal newpsize = ipsize + apsize # Set up the output buffer out = array('B') # It's annoying that there is no cheap way to set the array size :-( out.extend(ipixels) out.extend(apixels) # Interleave in the pixel data for i in range(ipsize): out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize] for i in range(apsize): out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize] return out class Error(Exception): pass class Writer: """ PNG encoder in pure Python. """ def __init__(self, width, height, transparent=None, background=None, gamma=None, greyscale=False, has_alpha=False, bytes_per_sample=1, compression=None, interlaced=False, chunk_limit=2**20): """ Create a PNG encoder object. Arguments: width, height - size of the image in pixels transparent - create a tRNS chunk background - create a bKGD chunk gamma - create a gAMA chunk greyscale - input data is greyscale, not RGB has_alpha - input data has alpha channel (RGBA) bytes_per_sample - 8-bit or 16-bit input data compression - zlib compression level (1-9) chunk_limit - write multiple IDAT chunks to save memory If specified, the transparent and background parameters must be a tuple with three integer values for red, green, blue, or a simple integer (or singleton tuple) for a greyscale image. If specified, the gamma parameter must be a float value. """ if width <= 0 or height <= 0: raise ValueError("width and height must be greater than zero") if has_alpha and transparent is not None: raise ValueError( "transparent color not allowed with alpha channel") if bytes_per_sample < 1 or bytes_per_sample > 2: raise ValueError("bytes per sample must be 1 or 2") if transparent is not None: if greyscale: if type(transparent) is not int: raise ValueError( "transparent color for greyscale must be integer") else: if not (len(transparent) == 3 and type(transparent[0]) is int and type(transparent[1]) is int and type(transparent[2]) is int): raise ValueError( "transparent color must be a triple of integers") if background is not None: if greyscale: if type(background) is not int: raise ValueError( "background color for greyscale must be integer") else: if not (len(background) == 3 and type(background[0]) is int and type(background[1]) is int and type(background[2]) is int): raise ValueError( "background color must be a triple of integers") self.width = width self.height = height self.transparent = transparent self.background = background self.gamma = gamma self.greyscale = greyscale self.has_alpha = has_alpha self.bytes_per_sample = bytes_per_sample self.compression = compression self.chunk_limit = chunk_limit self.interlaced = interlaced if self.greyscale: self.color_depth = 1 if self.has_alpha: self.color_type = 4 self.psize = self.bytes_per_sample * 2 else: self.color_type = 0 self.psize = self.bytes_per_sample else: self.color_depth = 3 if self.has_alpha: self.color_type = 6 self.psize = self.bytes_per_sample * 4 else: self.color_type = 2 self.psize = self.bytes_per_sample * 3 def write_chunk(self, outfile, tag, data): """ Write a PNG chunk to the output file, including length and checksum. """ # http://www.w3.org/TR/PNG/#5Chunk-layout tag = asbytes(tag) data = asbytes(data) outfile.write(struct.pack("!I", len(data))) outfile.write(tag) outfile.write(data) checksum = zlib.crc32(tag) checksum = zlib.crc32(data, checksum) # <ah> Avoid DeprecationWarning: struct integer overflow masking # with Python2.5/Windows. checksum = checksum & 0xffffffff outfile.write(struct.pack("!I", checksum)) def write(self, outfile, scanlines): """ Write a PNG image to the output file. """ # http://www.w3.org/TR/PNG/#5PNG-file-signature outfile.write(struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)) # http://www.w3.org/TR/PNG/#11IHDR if self.interlaced: interlaced = 1 else: interlaced = 0 self.write_chunk(outfile, 'IHDR', struct.pack("!2I5B", self.width, self.height, self.bytes_per_sample * 8, self.color_type, 0, 0, interlaced)) # http://www.w3.org/TR/PNG/#11tRNS if self.transparent is not None: if self.greyscale: self.write_chunk(outfile, 'tRNS', struct.pack("!1H", *self.transparent)) else: self.write_chunk(outfile, 'tRNS', struct.pack("!3H", *self.transparent)) # http://www.w3.org/TR/PNG/#11bKGD if self.background is not None: if self.greyscale: self.write_chunk(outfile, 'bKGD', struct.pack("!1H", *self.background)) else: self.write_chunk(outfile, 'bKGD', struct.pack("!3H", *self.background)) # http://www.w3.org/TR/PNG/#11gAMA if self.gamma is not None: self.write_chunk(outfile, 'gAMA', struct.pack("!L", int(self.gamma * 100000))) # http://www.w3.org/TR/PNG/#11IDAT if self.compression is not None: compressor = zlib.compressobj(self.compression) else: compressor = zlib.compressobj() data = array('B') for scanline in scanlines: data.append(0) data.extend(scanline) if len(data) > self.chunk_limit: compressed = compressor.compress(data.tostring()) if len(compressed): # print >> sys.stderr, len(data), len(compressed) self.write_chunk(outfile, 'IDAT', compressed) data = array('B') if len(data): compressed = compressor.compress(data.tostring()) else: compressed = '' flushed = compressor.flush() if len(compressed) or len(flushed): # print >> sys.stderr, len(data), len(compressed), len(flushed) self.write_chunk(outfile, 'IDAT', compressed + flushed) # http://www.w3.org/TR/PNG/#11IEND self.write_chunk(outfile, 'IEND', '') def write_array(self, outfile, pixels): """ Encode a pixel array to PNG and write output file. """ if self.interlaced: self.write(outfile, self.array_scanlines_interlace(pixels)) else: self.write(outfile, self.array_scanlines(pixels)) def convert_ppm(self, ppmfile, outfile): """ Convert a PPM file containing raw pixel data into a PNG file with the parameters set in the writer object. """ if self.interlaced: pixels = array('B') pixels.fromfile(ppmfile, self.bytes_per_sample * self.color_depth * self.width * self.height) self.write(outfile, self.array_scanlines_interlace(pixels)) else: self.write(outfile, self.file_scanlines(ppmfile)) def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile): """ Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object. """ pixels = array('B') pixels.fromfile(ppmfile, self.bytes_per_sample * self.color_depth * self.width * self.height) apixels = array('B') apixels.fromfile(pgmfile, self.bytes_per_sample * self.width * self.height) pixels = interleave_planes(pixels, apixels, self.bytes_per_sample * self.color_depth, self.bytes_per_sample) if self.interlaced: self.write(outfile, self.array_scanlines_interlace(pixels)) else: self.write(outfile, self.array_scanlines(pixels)) def file_scanlines(self, infile): """ Generator for scanlines from an input file. """ row_bytes = self.psize * self.width for y in range(self.height): scanline = array('B') scanline.fromfile(infile, row_bytes) yield scanline def array_scanlines(self, pixels): """ Generator for scanlines from an array. """ row_bytes = self.width * self.psize stop = 0 for y in range(self.height): start = stop stop = start + row_bytes yield pixels[start:stop] def old_array_scanlines_interlace(self, pixels): """ Generator for interlaced scanlines from an array. http://www.w3.org/TR/PNG/#8InterlaceMethods """ row_bytes = self.psize * self.width for xstart, ystart, xstep, ystep in _adam7: for y in range(ystart, self.height, ystep): if xstart < self.width: if xstep == 1: offset = y*row_bytes yield pixels[offset:offset+row_bytes] else: row = array('B') offset = y*row_bytes + xstart* self.psize skip = self.psize * xstep for x in range(xstart, self.width, xstep): row.extend(pixels[offset:offset + self.psize]) offset += skip yield row def array_scanlines_interlace(self, pixels): """ Generator for interlaced scanlines from an array. http://www.w3.org/TR/PNG/#8InterlaceMethods """ row_bytes = self.psize * self.width for xstart, ystart, xstep, ystep in _adam7: for y in range(ystart, self.height, ystep): if xstart >= self.width: continue if xstep == 1: offset = y * row_bytes yield pixels[offset:offset+row_bytes] else: row = array('B') # Note we want the ceiling of (self.width - xstart) / xtep row_len = self.psize * ( (self.width - xstart + xstep - 1) / xstep) # There's no easier way to set the length of an array row.extend(pixels[0:row_len]) offset = y * row_bytes + xstart * self.psize end_offset = (y+1) * row_bytes skip = self.psize * xstep for i in range(self.psize): row[i:row_len:self.psize] = \ pixels[offset+i:end_offset:skip] yield row class _readable: """ A simple file-like interface for strings and arrays. """ def __init__(self, buf): self.buf = buf self.offset = 0 def read(self, n): r = self.buf[offset:offset+n] if isinstance(r, array): r = r.tostring() self.offset += n return r class Reader: """ PNG decoder in pure Python. """ def __init__(self, _guess=None, **kw): """ Create a PNG decoder object. The constructor expects exactly one keyword argument. If you supply a positional argument instead, it will guess the input type. You can choose among the following arguments: filename - name of PNG input file file - object with a read() method pixels - array or string with PNG data """ if ((_guess is not None and len(kw) != 0) or (_guess is None and len(kw) != 1)): raise TypeError("Reader() takes exactly 1 argument") if _guess is not None: if isinstance(_guess, array): kw["pixels"] = _guess elif isinstance(_guess, str): kw["filename"] = _guess elif isinstance(_guess, file): kw["file"] = _guess if "filename" in kw: self.file = file(kw["filename"]) elif "file" in kw: self.file = kw["file"] elif "pixels" in kw: self.file = _readable(kw["pixels"]) else: raise TypeError("expecting filename, file or pixels array") def read_chunk(self): """ Read a PNG chunk from the input file, return tag name and data. """ # http://www.w3.org/TR/PNG/#5Chunk-layout try: data_bytes, tag = struct.unpack('!I4s', self.file.read(8)) except struct.error: raise ValueError('Chunk too short for header') data = self.file.read(data_bytes) if len(data) != data_bytes: raise ValueError('Chunk %s too short for required %i data octets' % (tag, data_bytes)) checksum = self.file.read(4) if len(checksum) != 4: raise ValueError('Chunk %s too short for checksum', tag) verify = zlib.crc32(tag) verify = zlib.crc32(data, verify) # Whether the output from zlib.crc32 is signed or not varies # according to hideous implementation details, see # http://bugs.python.org/issue1202 . # We coerce it to be positive here (in a way which works on # Python 2.3 and older). verify &= 2**32 - 1 verify = struct.pack('!I', verify) if checksum != verify: # print repr(checksum) (a,) = struct.unpack('!I', checksum) (b,) = struct.unpack('!I', verify) raise ValueError("Checksum error in %s chunk: 0x%X != 0x%X" % (tag, a, b)) return tag, data def _reconstruct_sub(self, offset, xstep, ystep): """ Reverse sub filter. """ pixels = self.pixels a_offset = offset offset += self.psize * xstep if xstep == 1: for index in range(self.psize, self.row_bytes): x = pixels[offset] a = pixels[a_offset] pixels[offset] = (x + a) & 0xff offset += 1 a_offset += 1 else: byte_step = self.psize * xstep for index in range(byte_step, self.row_bytes, byte_step): for i in range(self.psize): x = pixels[offset + i] a = pixels[a_offset + i] pixels[offset + i] = (x + a) & 0xff offset += self.psize * xstep a_offset += self.psize * xstep def _reconstruct_up(self, offset, xstep, ystep): """ Reverse up filter. """ pixels = self.pixels b_offset = offset - (self.row_bytes * ystep) if xstep == 1: for index in range(self.row_bytes): x = pixels[offset] b = pixels[b_offset] pixels[offset] = (x + b) & 0xff offset += 1 b_offset += 1 else: for index in range(0, self.row_bytes, xstep * self.psize): for i in range(self.psize): x = pixels[offset + i] b = pixels[b_offset + i] pixels[offset + i] = (x + b) & 0xff offset += self.psize * xstep b_offset += self.psize * xstep def _reconstruct_average(self, offset, xstep, ystep): """ Reverse average filter. """ pixels = self.pixels a_offset = offset - (self.psize * xstep) b_offset = offset - (self.row_bytes * ystep) if xstep == 1: for index in range(self.row_bytes): x = pixels[offset] if index < self.psize: a = 0 else: a = pixels[a_offset] if b_offset < 0: b = 0 else: b = pixels[b_offset] pixels[offset] = (x + ((a + b) >> 1)) & 0xff offset += 1 a_offset += 1 b_offset += 1 else: for index in range(0, self.row_bytes, self.psize * xstep): for i in range(self.psize): x = pixels[offset+i] if index < self.psize: a = 0 else: a = pixels[a_offset + i] if b_offset < 0: b = 0 else: b = pixels[b_offset + i] pixels[offset + i] = (x + ((a + b) >> 1)) & 0xff offset += self.psize * xstep a_offset += self.psize * xstep b_offset += self.psize * xstep def _reconstruct_paeth(self, offset, xstep, ystep): """ Reverse Paeth filter. """ pixels = self.pixels a_offset = offset - (self.psize * xstep) b_offset = offset - (self.row_bytes * ystep) c_offset = b_offset - (self.psize * xstep) # There's enough inside this loop that it's probably not worth # optimising for xstep == 1 for index in range(0, self.row_bytes, self.psize * xstep): for i in range(self.psize): x = pixels[offset+i] if index < self.psize: a = c = 0 b = pixels[b_offset+i] else: a = pixels[a_offset+i] b = pixels[b_offset+i] c = pixels[c_offset+i] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: pr = a elif pb <= pc: pr = b else: pr = c pixels[offset+i] = (x + pr) & 0xff offset += self.psize * xstep a_offset += self.psize * xstep b_offset += self.psize * xstep c_offset += self.psize * xstep # N.B. PNG files with 'up', 'average' or 'paeth' filters on the # first line of a pass are legal. The code above for 'average' # deals with this case explicitly. For up we map to the null # filter and for paeth we map to the sub filter. def reconstruct_line(self, filter_type, first_line, offset, xstep, ystep): # print >> sys.stderr, "Filter type %s, first_line=%s" % ( # filter_type, first_line) filter_type += (first_line << 8) if filter_type == 1 or filter_type == 0x101 or filter_type == 0x104: self._reconstruct_sub(offset, xstep, ystep) elif filter_type == 2: self._reconstruct_up(offset, xstep, ystep) elif filter_type == 3 or filter_type == 0x103: self._reconstruct_average(offset, xstep, ystep) elif filter_type == 4: self._reconstruct_paeth(offset, xstep, ystep) return def deinterlace(self, scanlines): # print >> sys.stderr, ("Reading interlaced, w=%s, r=%s, planes=%s," + # " bpp=%s") % (self.width, self.height, self.planes, self.bps) a = array('B') self.pixels = a # Make the array big enough temp = scanlines[0:self.width*self.height*self.psize] a.extend(temp) source_offset = 0 for xstart, ystart, xstep, ystep in _adam7: # print >> sys.stderr, "Adam7: start=%s,%s step=%s,%s" % ( # xstart, ystart, xstep, ystep) filter_first_line = 1 for y in range(ystart, self.height, ystep): if xstart >= self.width: continue filter_type = scanlines[source_offset] source_offset += 1 if xstep == 1: offset = y * self.row_bytes a[offset:offset+self.row_bytes] = \ scanlines[source_offset:source_offset + self.row_bytes] source_offset += self.row_bytes else: # Note we want the ceiling of (width - xstart) / xtep row_len = self.psize * ( (self.width - xstart + xstep - 1) / xstep) offset = y * self.row_bytes + xstart * self.psize end_offset = (y+1) * self.row_bytes skip = self.psize * xstep for i in range(self.psize): a[offset+i:end_offset:skip] = \ scanlines[source_offset + i: source_offset + row_len: self.psize] source_offset += row_len if filter_type: self.reconstruct_line(filter_type, filter_first_line, offset, xstep, ystep) filter_first_line = 0 return a def read_flat(self, scanlines): a = array('B') self.pixels = a offset = 0 source_offset = 0 filter_first_line = 1 for y in range(self.height): filter_type = scanlines[source_offset] source_offset += 1 a.extend(scanlines[source_offset: source_offset + self.row_bytes]) if filter_type: self.reconstruct_line(filter_type, filter_first_line, offset, 1, 1) filter_first_line = 0 offset += self.row_bytes source_offset += self.row_bytes return a def read(self): """ Read a simple PNG file, return width, height, pixels and image metadata This function is a very early prototype with limited flexibility and excessive use of memory. """ signature = self.file.read(8) if (signature != struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)): raise Error("PNG file has invalid header") compressed = [] image_metadata = {} while True: try: tag, data = self.read_chunk() except ValueError, e: raise Error('Chunk error: ' + e.args[0]) # print >> sys.stderr, tag, len(data) if tag == asbytes('IHDR'): # http://www.w3.org/TR/PNG/#11IHDR (width, height, bits_per_sample, color_type, compression_method, filter_method, interlaced) = struct.unpack("!2I5B", data) bps = bits_per_sample // 8 if bps == 0: raise Error("unsupported pixel depth") if bps > 2 or bits_per_sample != (bps * 8): raise Error("invalid pixel depth") if color_type == 0: greyscale = True has_alpha = False planes = 1 elif color_type == 2: greyscale = False has_alpha = False planes = 3 elif color_type == 4: greyscale = True has_alpha = True planes = 2 elif color_type == 6: greyscale = False has_alpha = True planes = 4 else: raise Error("unknown PNG colour type %s" % color_type) if compression_method != 0: raise Error("unknown compression method") if filter_method != 0: raise Error("unknown filter method") self.bps = bps self.planes = planes self.psize = bps * planes self.width = width self.height = height self.row_bytes = width * self.psize elif tag == asbytes('IDAT'): # http://www.w3.org/TR/PNG/#11IDAT compressed.append(data) elif tag == asbytes('bKGD'): if greyscale: image_metadata["background"] = struct.unpack("!1H", data) else: image_metadata["background"] = struct.unpack("!3H", data) elif tag == asbytes('tRNS'): if greyscale: image_metadata["transparent"] = struct.unpack("!1H", data) else: image_metadata["transparent"] = struct.unpack("!3H", data) elif tag == asbytes('gAMA'): image_metadata["gamma"] = ( struct.unpack("!L", data)[0]) / 100000.0 elif tag == asbytes('IEND'): # http://www.w3.org/TR/PNG/#11IEND break scanlines = array('B', zlib.decompress(asbytes('').join(compressed))) if interlaced: pixels = self.deinterlace(scanlines) else: pixels = self.read_flat(scanlines) image_metadata["greyscale"] = greyscale image_metadata["has_alpha"] = has_alpha image_metadata["bytes_per_sample"] = bps image_metadata["interlaced"] = interlaced return width, height, pixels, image_metadata def test_suite(options): """ Run regression test and write PNG file to stdout. """ # Below is a big stack of test image generators def test_gradient_horizontal_lr(x, y): return x def test_gradient_horizontal_rl(x, y): return 1-x def test_gradient_vertical_tb(x, y): return y def test_gradient_vertical_bt(x, y): return 1-y def test_radial_tl(x, y): return max(1-math.sqrt(x*x+y*y), 0.0) def test_radial_center(x, y): return test_radial_tl(x-0.5, y-0.5) def test_radial_tr(x, y): return test_radial_tl(1-x, y) def test_radial_bl(x, y): return test_radial_tl(x, 1-y) def test_radial_br(x, y): return test_radial_tl(1-x, 1-y) def test_stripe(x, n): return 1.0*(int(x*n) & 1) def test_stripe_h_2(x, y): return test_stripe(x, 2) def test_stripe_h_4(x, y): return test_stripe(x, 4) def test_stripe_h_10(x, y): return test_stripe(x, 10) def test_stripe_v_2(x, y): return test_stripe(y, 2) def test_stripe_v_4(x, y): return test_stripe(y, 4) def test_stripe_v_10(x, y): return test_stripe(y, 10) def test_stripe_lr_10(x, y): return test_stripe(x+y, 10) def test_stripe_rl_10(x, y): return test_stripe(x-y, 10) def test_checker(x, y, n): return 1.0*((int(x*n) & 1) ^ (int(y*n) & 1)) def test_checker_8(x, y): return test_checker(x, y, 8) def test_checker_15(x, y): return test_checker(x, y, 15) def test_zero(x, y): return 0 def test_one(x, y): return 1 test_patterns = { "GLR": test_gradient_horizontal_lr, "GRL": test_gradient_horizontal_rl, "GTB": test_gradient_vertical_tb, "GBT": test_gradient_vertical_bt, "RTL": test_radial_tl, "RTR": test_radial_tr, "RBL": test_radial_bl, "RBR": test_radial_br, "RCTR": test_radial_center, "HS2": test_stripe_h_2, "HS4": test_stripe_h_4, "HS10": test_stripe_h_10, "VS2": test_stripe_v_2, "VS4": test_stripe_v_4, "VS10": test_stripe_v_10, "LRS": test_stripe_lr_10, "RLS": test_stripe_rl_10, "CK8": test_checker_8, "CK15": test_checker_15, "ZERO": test_zero, "ONE": test_one, } def test_pattern(width, height, depth, pattern): a = array('B') fw = float(width) fh = float(height) pfun = test_patterns[pattern] if depth == 1: for y in range(height): for x in range(width): a.append(int(pfun(float(x)/fw, float(y)/fh) * 255)) elif depth == 2: for y in range(height): for x in range(width): v = int(pfun(float(x)/fw, float(y)/fh) * 65535) a.append(v >> 8) a.append(v & 0xff) return a def test_rgba(size=256, depth=1, red="GTB", green="GLR", blue="RTL", alpha=None): r = test_pattern(size, size, depth, red) g = test_pattern(size, size, depth, green) b = test_pattern(size, size, depth, blue) if alpha: a = test_pattern(size, size, depth, alpha) i = interleave_planes(r, g, depth, depth) i = interleave_planes(i, b, 2 * depth, depth) if alpha: i = interleave_planes(i, a, 3 * depth, depth) return i # The body of test_suite() size = 256 if options.test_size: size = options.test_size depth = 1 if options.test_deep: depth = 2 kwargs = {} if options.test_red: kwargs["red"] = options.test_red if options.test_green: kwargs["green"] = options.test_green if options.test_blue: kwargs["blue"] = options.test_blue if options.test_alpha: kwargs["alpha"] = options.test_alpha pixels = test_rgba(size, depth, **kwargs) writer = Writer(size, size, bytes_per_sample=depth, transparent=options.transparent, background=options.background, gamma=options.gamma, has_alpha=options.test_alpha, compression=options.compression, interlaced=options.interlace) writer.write_array(sys.stdout, pixels) def read_pnm_header(infile, supported='P6'): """ Read a PNM header, return width and height of the image in pixels. """ header = [] while len(header) < 4: line = infile.readline() sharp = line.find('#') if sharp > -1: line = line[:sharp] header.extend(line.split()) if len(header) == 3 and header[0] == 'P4': break # PBM doesn't have maxval if header[0] not in supported: raise NotImplementedError('file format %s not supported' % header[0]) if header[0] != 'P4' and header[3] != '255': raise NotImplementedError('maxval %s not supported' % header[3]) return int(header[1]), int(header[2]) def color_triple(color): """ Convert a command line color value to a RGB triple of integers. FIXME: Somewhere we need support for greyscale backgrounds etc. """ if color.startswith('#') and len(color) == 4: return (int(color[1], 16), int(color[2], 16), int(color[3], 16)) if color.startswith('#') and len(color) == 7: return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)) elif color.startswith('#') and len(color) == 13: return (int(color[1:5], 16), int(color[5:9], 16), int(color[9:13], 16)) def _main(): """ Run the PNG encoder with options from the command line. """ # Parse command line arguments from optparse import OptionParser version = '%prog ' + __revision__.strip('$').replace('Rev: ', 'r') parser = OptionParser(version=version) parser.set_usage("%prog [options] [pnmfile]") parser.add_option("-i", "--interlace", default=False, action="store_true", help="create an interlaced PNG file (Adam7)") parser.add_option("-t", "--transparent", action="store", type="string", metavar="color", help="mark the specified color as transparent") parser.add_option("-b", "--background", action="store", type="string", metavar="color", help="save the specified background color") parser.add_option("-a", "--alpha", action="store", type="string", metavar="pgmfile", help="alpha channel transparency (RGBA)") parser.add_option("-g", "--gamma", action="store", type="float", metavar="value", help="save the specified gamma value") parser.add_option("-c", "--compression", action="store", type="int", metavar="level", help="zlib compression level (0-9)") parser.add_option("-T", "--test", default=False, action="store_true", help="create a test image") parser.add_option("-R", "--test-red", action="store", type="string", metavar="pattern", help="test pattern for the red image layer") parser.add_option("-G", "--test-green", action="store", type="string", metavar="pattern", help="test pattern for the green image layer") parser.add_option("-B", "--test-blue", action="store", type="string", metavar="pattern", help="test pattern for the blue image layer") parser.add_option("-A", "--test-alpha", action="store", type="string", metavar="pattern", help="test pattern for the alpha image layer") parser.add_option("-D", "--test-deep", default=False, action="store_true", help="use test patterns with 16 bits per layer") parser.add_option("-S", "--test-size", action="store", type="int", metavar="size", help="width and height of the test image") (options, args) = parser.parse_args() # Convert options if options.transparent is not None: options.transparent = color_triple(options.transparent) if options.background is not None: options.background = color_triple(options.background) # Run regression tests if options.test: return test_suite(options) # Prepare input and output files if len(args) == 0: ppmfilename = '-' ppmfile = sys.stdin elif len(args) == 1: ppmfilename = args[0] ppmfile = open(ppmfilename, 'rb') else: parser.error("more than one input file") outfile = sys.stdout # Encode PNM to PNG width, height = read_pnm_header(ppmfile) writer = Writer(width, height, transparent=options.transparent, background=options.background, has_alpha=options.alpha is not None, gamma=options.gamma, compression=options.compression) if options.alpha is not None: pgmfile = open(options.alpha, 'rb') awidth, aheight = read_pnm_header(pgmfile, 'P5') if (awidth, aheight) != (width, height): raise ValueError("alpha channel image size mismatch" + " (%s has %sx%s but %s has %sx%s)" % (ppmfilename, width, height, options.alpha, awidth, aheight)) writer.convert_ppm_and_pgm(ppmfile, pgmfile, outfile, interlace=options.interlace) else: writer.convert_ppm(ppmfile, outfile, interlace=options.interlace) if __name__ == '__main__': _main()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Read GIF control data. http://www.w3.org/Graphics/GIF/spec-gif89a.txt ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import struct from pyglet.image.codecs import ImageDecodeException class GIFStream(object): def __init__(self): self.images = [] class GIFImage(object): delay = None class GraphicsScope(object): delay = None # Appendix A. LABEL_EXTENSION_INTRODUCER = 0x21 LABEL_GRAPHIC_CONTROL_EXTENSION = 0xf9 LABEL_IMAGE_DESCRIPTOR = 0x2c LABEL_TRAILER = 0x3b def unpack(format, file): size = struct.calcsize(format) data = file.read(size) if len(data) < size: raise ImageDecodeException('Unexpected EOF') return struct.unpack(format, data) def read_byte(file): data = file.read(1) if not len(data): raise ImageDecodeException('Unexpected EOF') return ord(data) def read(file): '''Read a GIF file stream. :rtype: GIFStream ''' # 17. Header signature = file.read(3) version = file.read(3) if signature != 'GIF': raise ImageDecodeException('Not a GIF stream') stream = GIFStream() # 18. Logical screen descriptor (logical_screen_width, logical_screen_height, fields, background_color_index, pixel_aspect_ratio) = unpack('HHBBB', file) global_color_table_flag = fields & 0x80 global_color_table_size = fields & 0x7 # 19. Global color table if global_color_table_flag: global_color_table = file.read(6 << global_color_table_size) # <Data>* graphics_scope = GraphicsScope() block_type = read_byte(file) while block_type != LABEL_TRAILER: if block_type == LABEL_IMAGE_DESCRIPTOR: read_table_based_image(file, stream, graphics_scope) graphics_scope = GraphicsScope() elif block_type == LABEL_EXTENSION_INTRODUCER: extension_block_type = read_byte(file) if extension_block_type == LABEL_GRAPHIC_CONTROL_EXTENSION: read_graphic_control_extension(file, stream, graphics_scope) else: skip_data_sub_blocks(file) else: # Skip bytes until a valid start character is found print block_type pass block_type = read_byte(file) return stream def skip_data_sub_blocks(file): # 15. Data sub-blocks block_size = read_byte(file) while block_size != 0: data = file.read(block_size) block_size = read_byte(file) def read_table_based_image(file, stream, graphics_scope): gif_image = GIFImage() stream.images.append(gif_image) gif_image.delay = graphics_scope.delay # 20. Image descriptor (image_left_position, image_top_position, image_width, image_height, fields) = unpack('HHHHB', file) local_color_table_flag = fields & 0x80 local_color_table_size = fields & 0x7 # 21. Local color table if local_color_table_flag: local_color_table = file.read(6 << local_color_table_size) # 22. Table based image data lzw_code_size = file.read(1) skip_data_sub_blocks(file) def read_graphic_control_extension(file, stream, graphics_scope): # 23. Graphic control extension (block_size, fields, delay_time, transparent_color_index, terminator) = unpack('BBHBB', file) if block_size != 4: raise ImageDecodeException('Incorrect block size') if delay_time: # Follow Firefox/Mac behaviour: use 100ms delay for any delay # less than 10ms. if delay_time <= 1: delay_time = 10 graphics_scope.delay = float(delay_time) / 100
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' from pyglet.image import ImageData, Animation, AnimationFrame from pyglet.image.codecs import * from pyglet.libs.darwin.cocoapy import * class QuartzImageDecoder(ImageDecoder): def get_file_extensions(self): # Quartz can actually decode many more formats, but these are the most common. return [ '.bmp', '.cur', '.gif', '.ico', '.jp2', '.jpg', '.jpeg', '.pcx', '.png', '.tga', '.tif', '.tiff', '.xbm', '.xpm' ] def get_animation_file_extensions(self): return ['.gif'] def _get_pyglet_ImageData_from_source_at_index(self, sourceRef, index): imageRef = c_void_p(quartz.CGImageSourceCreateImageAtIndex(sourceRef, index, None)) # Regardless of the internal format of the image (L, LA, RGB, RGBA, etc) # we just automatically convert everything to an RGBA format. format = 'RGBA' rgbColorSpace = c_void_p(quartz.CGColorSpaceCreateDeviceRGB()) bitsPerComponent = 8 width = quartz.CGImageGetWidth(imageRef) height = quartz.CGImageGetHeight(imageRef) bytesPerRow = 4 * width # Create a buffer to store the RGBA formatted data. bufferSize = height * bytesPerRow buffer = (c_ubyte * bufferSize)() # Create a bitmap context for the RGBA formatted data. # Note that premultiplied alpha is required: # http://developer.apple.com/library/mac/#qa/qa1037/_index.html bitmap = c_void_p(quartz.CGBitmapContextCreate(buffer, width, height, bitsPerComponent, bytesPerRow, rgbColorSpace, kCGImageAlphaPremultipliedLast)) # Write the image data into the bitmap. quartz.CGContextDrawImage(bitmap, NSMakeRect(0,0,width,height), imageRef) quartz.CGImageRelease(imageRef) quartz.CGContextRelease(bitmap) quartz.CGColorSpaceRelease(rgbColorSpace) pitch = bytesPerRow return ImageData(width, height, format, buffer, -pitch) def decode(self, file, filename): file_bytes = file.read() data = c_void_p(cf.CFDataCreate(None, file_bytes, len(file_bytes))) # Second argument is an options dictionary. It might be a good idea to provide # a value for kCGImageSourceTypeIdentifierHint here using filename extension. sourceRef = c_void_p(quartz.CGImageSourceCreateWithData(data, None)) image = self._get_pyglet_ImageData_from_source_at_index(sourceRef, 0) cf.CFRelease(data) cf.CFRelease(sourceRef) return image def decode_animation(self, file, filename): # If file is not an animated GIF, it will be loaded as a single-frame animation. file_bytes = file.read() data = c_void_p(cf.CFDataCreate(None, file_bytes, len(file_bytes))) sourceRef = c_void_p(quartz.CGImageSourceCreateWithData(data, None)) # Get number of frames in the animation. count = quartz.CGImageSourceGetCount(sourceRef) frames = [] for index in range(count): # Try to determine frame duration from GIF properties dictionary. duration = 0.1 # default duration if none found props = c_void_p(quartz.CGImageSourceCopyPropertiesAtIndex(sourceRef, index, None)) if cf.CFDictionaryContainsKey(props, kCGImagePropertyGIFDictionary): gif_props = c_void_p(cf.CFDictionaryGetValue(props, kCGImagePropertyGIFDictionary)) if cf.CFDictionaryContainsKey(gif_props, kCGImagePropertyGIFDelayTime): duration = cfnumber_to_number(c_void_p(cf.CFDictionaryGetValue(gif_props, kCGImagePropertyGIFDelayTime))) cf.CFRelease(props) image = self._get_pyglet_ImageData_from_source_at_index(sourceRef, index) frames.append( AnimationFrame(image, duration) ) cf.CFRelease(data) cf.CFRelease(sourceRef) return Animation(frames) def get_decoders(): return [ QuartzImageDecoder() ] def get_encoders(): return []
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Collection of image encoders and decoders. Modules must subclass ImageDecoder and ImageEncoder for each method of decoding/encoding they support. Modules must also implement the two functions:: def get_decoders(): # Return a list of ImageDecoder instances or [] return [] def get_encoders(): # Return a list of ImageEncoder instances or [] return [] ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import os.path import sys _decoders = [] # List of registered ImageDecoders _decoder_extensions = {} # Map str -> list of matching ImageDecoders _decoder_animation_extensions = {} # Map str -> list of matching ImageDecoders _encoders = [] # List of registered ImageEncoders _encoder_extensions = {} # Map str -> list of matching ImageEncoders class ImageDecodeException(Exception): exception_priority = 10 class ImageEncodeException(Exception): pass class ImageDecoder(object): def get_file_extensions(self): '''Return a list of accepted file extensions, e.g. ['.png', '.bmp'] Lower-case only. ''' return [] def get_animation_file_extensions(self): '''Return a list of accepted file extensions, e.g. ['.gif', '.flc'] Lower-case only. ''' return [] def decode(self, file, filename): '''Decode the given file object and return an instance of `Image`. Throws ImageDecodeException if there is an error. filename can be a file type hint. ''' raise NotImplementedError() def decode_animation(self, file, filename): '''Decode the given file object and return an instance of `Animation`. Throws ImageDecodeException if there is an error. filename can be a file type hint. ''' raise ImageDecodeException('This decoder cannot decode animations.') class ImageEncoder(object): def get_file_extensions(self): '''Return a list of accepted file extensions, e.g. ['.png', '.bmp'] Lower-case only. ''' return [] def encode(self, image, file, filename, options={}): '''Encode the given image to the given file. filename provides a hint to the file format desired. options are encoder-specific, and unknown options should be ignored or issue warnings. ''' raise NotImplementedError() def get_encoders(filename=None): '''Get an ordered list of encoders to attempt. filename can be used as a hint for the filetype. ''' encoders = [] if filename: extension = os.path.splitext(filename)[1].lower() encoders += _encoder_extensions.get(extension, []) encoders += [e for e in _encoders if e not in encoders] return encoders def get_decoders(filename=None): '''Get an ordered list of decoders to attempt. filename can be used as a hint for the filetype. ''' decoders = [] if filename: extension = os.path.splitext(filename)[1].lower() decoders += _decoder_extensions.get(extension, []) decoders += [e for e in _decoders if e not in decoders] return decoders def get_animation_decoders(filename=None): '''Get an ordered list of decoders to attempt. filename can be used as a hint for the filetype. ''' decoders = [] if filename: extension = os.path.splitext(filename)[1].lower() decoders += _decoder_animation_extensions.get(extension, []) decoders += [e for e in _decoders if e not in decoders] return decoders def add_decoders(module): '''Add a decoder module. The module must define `get_decoders`. Once added, the appropriate decoders defined in the codec will be returned by pyglet.image.codecs.get_decoders. ''' for decoder in module.get_decoders(): _decoders.append(decoder) for extension in decoder.get_file_extensions(): if extension not in _decoder_extensions: _decoder_extensions[extension] = [] _decoder_extensions[extension].append(decoder) for extension in decoder.get_animation_file_extensions(): if extension not in _decoder_animation_extensions: _decoder_animation_extensions[extension] = [] _decoder_animation_extensions[extension].append(decoder) def add_encoders(module): '''Add an encoder module. The module must define `get_encoders`. Once added, the appropriate encoders defined in the codec will be returned by pyglet.image.codecs.get_encoders. ''' for encoder in module.get_encoders(): _encoders.append(encoder) for extension in encoder.get_file_extensions(): if extension not in _encoder_extensions: _encoder_extensions[extension] = [] _encoder_extensions[extension].append(encoder) def add_default_image_codecs(): # Add the codecs we know about. These should be listed in order of # preference. This is called automatically by pyglet.image. # Compressed texture in DDS format try: from pyglet.image.codecs import dds add_encoders(dds) add_decoders(dds) except ImportError: pass # Mac OS X default: Quicktime for Carbon, Quartz for Cocoa. # TODO: Make ctypes Quartz the default for both Carbon & Cocoa. if sys.platform == 'darwin': try: from pyglet import options as pyglet_options if pyglet_options['darwin_cocoa']: import pyglet.image.codecs.quartz add_encoders(quartz) add_decoders(quartz) else: import pyglet.image.codecs.quicktime add_encoders(quicktime) add_decoders(quicktime) except ImportError: pass # Windows XP default: GDI+ if sys.platform in ('win32', 'cygwin'): try: import pyglet.image.codecs.gdiplus add_encoders(gdiplus) add_decoders(gdiplus) except ImportError: pass # Linux default: GdkPixbuf 2.0 if sys.platform.startswith('linux'): try: import pyglet.image.codecs.gdkpixbuf2 add_encoders(gdkpixbuf2) add_decoders(gdkpixbuf2) except ImportError: pass # Fallback: PIL try: import pyglet.image.codecs.pil add_encoders(pil) add_decoders(pil) except ImportError: pass # Fallback: PNG loader (slow) try: import pyglet.image.codecs.png add_encoders(png) add_decoders(png) except ImportError: pass # Fallback: BMP loader (slow) try: import pyglet.image.codecs.bmp add_encoders(bmp) add_decoders(bmp) except ImportError: pass
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Extensible attributed text format for representing pyglet formatted documents. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import operator import parser import re import token import pyglet _pattern = re.compile(r''' (?P<escape_hex>\{\#x(?P<escape_hex_val>[0-9a-fA-F]+)\}) | (?P<escape_dec>\{\#(?P<escape_dec_val>[0-9]+)\}) | (?P<escape_lbrace>\{\{) | (?P<escape_rbrace>\}\}) | (?P<attr>\{ (?P<attr_name>[^ \{\}]+)\s+ (?P<attr_val>[^\}]+)\}) | (?P<nl_hard1>\n(?=[ \t])) | (?P<nl_hard2>\{\}\n) | (?P<nl_soft>\n(?=\S)) | (?P<nl_para>\n\n+) | (?P<text>[^\{\}\n]+) ''', re.VERBOSE | re.DOTALL) class AttributedTextDecoder(pyglet.text.DocumentDecoder): def decode(self, text, location=None): self.doc = pyglet.text.document.FormattedDocument() self.length = 0 self.attributes = {} next_trailing_space = True trailing_newline = True for m in _pattern.finditer(text): group = m.lastgroup trailing_space = True if group == 'text': t = m.group('text') self.append(t) trailing_space = t.endswith(' ') trailing_newline = False elif group == 'nl_soft': if not next_trailing_space: self.append(' ') trailing_newline = False elif group in ('nl_hard1', 'nl_hard2'): self.append('\n') trailing_newline = True elif group == 'nl_para': self.append(m.group('nl_para')) trailing_newline = True elif group == 'attr': try: ast = parser.expr(m.group('attr_val')) if self.safe(ast): val = eval(ast.compile()) else: val = None except (parser.ParserError, SyntaxError): val = None name = m.group('attr_name') if name[0] == '.': if trailing_newline: self.attributes[name[1:]] = val else: self.doc.set_paragraph_style(self.length, self.length, {name[1:]: val}) else: self.attributes[name] = val elif group == 'escape_dec': self.append(unichr(int(m.group('escape_dec_val')))) elif group == 'escape_hex': self.append(unichr(int(m.group('escape_hex_val'), 16))) elif group == 'escape_lbrace': self.append('{') elif group == 'escape_rbrace': self.append('}') next_trailing_space = trailing_space return self.doc def append(self, text): self.doc.insert_text(self.length, text, self.attributes) self.length += len(text) self.attributes.clear() _safe_names = ('True', 'False', 'None') def safe(self, ast): tree = ast.totuple() return self.safe_node(tree) def safe_node(self, node): if token.ISNONTERMINAL(node[0]): return reduce(operator.and_, map(self.safe_node, node[1:])) elif node[0] == token.NAME: return node[1] in self._safe_names else: return True
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Decode HTML into attributed text. A subset of HTML 4.01 Transitional is implemented. The following elements are supported fully:: B BLOCKQUOTE BR CENTER CODE DD DIR DL EM FONT H1 H2 H3 H4 H5 H6 I IMG KBD LI MENU OL P PRE Q SAMP STRONG SUB SUP TT U UL VAR The mark (bullet or number) of a list item is separated from the body of the list item with a tab, as the pyglet document model does not allow out-of-stream text. This means lists display as expected, but behave a little oddly if edited. No CSS styling is supported. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import HTMLParser import htmlentitydefs import re import pyglet from pyglet.text.formats import structured def _hex_color(val): return [(val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff, 255] _color_names = { 'black': _hex_color(0x000000), 'silver': _hex_color(0xc0c0c0), 'gray': _hex_color(0x808080), 'white': _hex_color(0xffffff), 'maroon': _hex_color(0x800000), 'red': _hex_color(0xff0000), 'purple': _hex_color(0x800080), 'fucsia': _hex_color(0x008000), 'green': _hex_color(0x00ff00), 'lime': _hex_color(0xffff00), 'olive': _hex_color(0x808000), 'yellow': _hex_color(0xff0000), 'navy': _hex_color(0x000080), 'blue': _hex_color(0x0000ff), 'teal': _hex_color(0x008080), 'aqua': _hex_color(0x00ffff), } def _parse_color(value): if value.startswith('#'): return _hex_color(int(value[1:], 16)) else: try: return _color_names[value.lower()] except KeyError: raise ValueError() _whitespace_re = re.compile(u'[\u0020\u0009\u000c\u200b\r\n]+', re.DOTALL) _metadata_elements = ['head', 'title'] _block_elements = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'dir', 'menu', 'pre', 'dl', 'div', 'center', 'noscript', 'noframes', 'blockquote', 'form', 'isindex', 'hr', 'table', 'fieldset', 'address', # Incorrect, but we treat list items as blocks: 'li', 'dd', 'dt', ] _block_containers = ['_top_block', 'body', 'div', 'center', 'object', 'applet', 'blockquote', 'ins', 'del', 'dd', 'li', 'form', 'fieldset', 'button', 'th', 'td', 'iframe', 'noscript', 'noframes', # Incorrect, but we treat list items as blocks: 'ul', 'ol', 'dir', 'menu', 'dl'] class HTMLDecoder(HTMLParser.HTMLParser, structured.StructuredTextDecoder): '''Decoder for HTML documents. ''' #: Default style attributes for unstyled text in the HTML document. #: #: :type: dict default_style = { 'font_name': 'Times New Roman', 'font_size': 12, 'margin_bottom': '12pt', } #: Map HTML font sizes to actual font sizes, in points. #: #: :type: dict font_sizes = { 1: 8, 2: 10, 3: 12, 4: 14, 5: 18, 6: 24, 7: 48 } def decode_structured(self, text, location): self.location = location self._font_size_stack = [3] self.list_stack.append(structured.UnorderedListBuilder({})) self.strip_leading_space = True self.block_begin = True self.need_block_begin = False self.element_stack = ['_top_block'] self.in_metadata = False self.in_pre = False self.push_style('_default', self.default_style) self.feed(text) self.close() def get_image(self, filename): return pyglet.image.load(filename, file=self.location.open(filename)) def prepare_for_data(self): if self.need_block_begin: self.add_text('\n') self.block_begin = True self.need_block_begin = False def handle_data(self, data): if self.in_metadata: return if self.in_pre: self.add_text(data) else: data = _whitespace_re.sub(' ', data) if data.strip(): self.prepare_for_data() if self.block_begin or self.strip_leading_space: data = data.lstrip() self.block_begin = False self.add_text(data) self.strip_leading_space = data.endswith(' ') def handle_starttag(self, tag, case_attrs): if self.in_metadata: return element = tag.lower() attrs = {} for key, value in case_attrs: attrs[key.lower()] = value if element in _metadata_elements: self.in_metadata = True elif element in _block_elements: # Pop off elements until we get to a block container. while self.element_stack[-1] not in _block_containers: self.handle_endtag(self.element_stack[-1]) if not self.block_begin: self.add_text('\n') self.block_begin = True self.need_block_begin = False self.element_stack.append(element) style = {} if element in ('b', 'strong'): style['bold'] = True elif element in ('i', 'em', 'var'): style['italic'] = True elif element in ('tt', 'code', 'samp', 'kbd'): style['font_name'] = 'Courier New' elif element == 'u': color = self.current_style.get('color') if color is None: color = [0, 0, 0, 255] style['underline'] = color elif element == 'font': if 'face' in attrs: style['font_name'] = attrs['face'].split(',') if 'size' in attrs: size = attrs['size'] try: if size.startswith('+'): size = self._font_size_stack[-1] + int(size[1:]) elif size.startswith('-'): size = self._font_size_stack[-1] - int(size[1:]) else: size = int(size) except ValueError: size = 3 self._font_size_stack.append(size) if size in self.font_sizes: style['font_size'] = self.font_sizes.get(size, 3) else: self._font_size_stack.append(self._font_size_stack[-1]) if 'color' in attrs: try: style['color'] = _parse_color(attrs['color']) except ValueError: pass elif element == 'sup': size = self._font_size_stack[-1] - 1 style['font_size'] = self.font_sizes.get(size, 1) style['baseline'] = '3pt' elif element == 'sub': size = self._font_size_stack[-1] - 1 style['font_size'] = self.font_sizes.get(size, 1) style['baseline'] = '-3pt' elif element == 'h1': style['font_size'] = 24 style['bold'] = True style['align'] = 'center' elif element == 'h2': style['font_size'] = 18 style['bold'] = True elif element == 'h3': style['font_size'] = 16 style['bold'] = True elif element == 'h4': style['font_size'] = 14 style['bold'] = True elif element == 'h5': style['font_size'] = 12 style['bold'] = True elif element == 'h6': style['font_size'] = 12 style['italic'] = True elif element == 'br': self.add_text(u'\u2028') self.strip_leading_space = True elif element == 'p': if attrs.get('align') in ('left', 'center', 'right'): style['align'] = attrs['align'] elif element == 'center': style['align'] = 'center' elif element == 'pre': style['font_name'] = 'Courier New' style['margin_bottom'] = 0 self.in_pre = True elif element == 'blockquote': left_margin = self.current_style.get('margin_left') or 0 right_margin = self.current_style.get('margin_right') or 0 style['margin_left'] = left_margin + 60 style['margin_right'] = right_margin + 60 elif element == 'q': self.handle_data(u'\u201c') elif element == 'ol': try: start = int(attrs.get('start', 1)) except ValueError: start = 1 format = attrs.get('type', '1') + '.' builder = structured.OrderedListBuilder(start, format) builder.begin(self, style) self.list_stack.append(builder) elif element in ('ul', 'dir', 'menu'): type = attrs.get('type', 'disc').lower() if type == 'circle': mark = u'\u25cb' elif type == 'square': mark = u'\u25a1' else: mark = u'\u25cf' builder = structured.UnorderedListBuilder(mark) builder.begin(self, style) self.list_stack.append(builder) elif element == 'li': self.list_stack[-1].item(self, style) self.strip_leading_space = True elif element == 'dl': style['margin_bottom'] = 0 elif element == 'dd': left_margin = self.current_style.get('margin_left') or 0 style['margin_left'] = left_margin + 30 elif element == 'img': image = self.get_image(attrs.get('src')) if image: width = attrs.get('width') if width: width = int(width) height = attrs.get('height') if height: height = int(height) self.prepare_for_data() self.add_element(structured.ImageElement(image, width, height)) self.strip_leading_space = False self.push_style(element, style) def handle_endtag(self, tag): element = tag.lower() if element not in self.element_stack: return self.pop_style(element) while self.element_stack.pop() != element: pass if element in _metadata_elements: self.in_metadata = False elif element in _block_elements: self.block_begin = False self.need_block_begin = True if element == 'font' and len(self._font_size_stack) > 1: self._font_size_stack.pop() elif element == 'pre': self.in_pre = False elif element == 'q': self.handle_data(u'\u201d') elif element in ('ul', 'ol'): if len(self.list_stack) > 1: self.list_stack.pop() def handle_entityref(self, name): if name in htmlentitydefs.name2codepoint: self.handle_data(unichr(htmlentitydefs.name2codepoint[name])) def handle_charref(self, name): name = name.lower() try: if name.startswith('x'): self.handle_data(unichr(int(name[1:], 16))) else: self.handle_data(unichr(int(name))) except ValueError: pass
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Base class for structured (hierarchical) document formats. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import re import pyglet class ImageElement(pyglet.text.document.InlineElement): def __init__(self, image, width=None, height=None): self.image = image.get_texture() self.width = width is None and image.width or width self.height = height is None and image.height or height self.vertex_lists = {} anchor_y = self.height // image.height * image.anchor_y ascent = max(0, self.height - anchor_y) descent = min(0, -anchor_y) super(ImageElement, self).__init__(ascent, descent, self.width) def place(self, layout, x, y): group = pyglet.graphics.TextureGroup(self.image.texture, layout.top_group) x1 = x y1 = y + self.descent x2 = x + self.width y2 = y + self.height + self.descent vertex_list = layout.batch.add(4, pyglet.gl.GL_QUADS, group, ('v2i', (x1, y1, x2, y1, x2, y2, x1, y2)), ('c3B', (255, 255, 255) * 4), ('t3f', self.image.tex_coords)) self.vertex_lists[layout] = vertex_list def remove(self, layout): self.vertex_lists[layout].delete() del self.vertex_lists[layout] def _int_to_roman(input): # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81611 if not 0 < input < 4000: raise ValueError, "Argument must be between 1 and 3999" ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I') result = "" for i in range(len(ints)): count = int(input / ints[i]) result += nums[i] * count input -= ints[i] * count return result class ListBuilder(object): def begin(self, decoder, style): '''Begin a list. :Parameters: `decoder` : `StructuredTextDecoder` Decoder. `style` : dict Style dictionary that applies over the entire list. ''' left_margin = decoder.current_style.get('margin_left') or 0 tab_stops = decoder.current_style.get('tab_stops') if tab_stops: tab_stops = list(tab_stops) else: tab_stops = [] tab_stops.append(left_margin + 50) style['margin_left'] = left_margin + 50 style['indent'] = -30 style['tab_stops'] = tab_stops def item(self, decoder, style, value=None): '''Begin a list item. :Parameters: `decoder` : `StructuredTextDecoder` Decoder. `style` : dict Style dictionary that applies over the list item. `value` : str Optional value of the list item. The meaning is list-type dependent. ''' mark = self.get_mark(value) if mark: decoder.add_text(mark) decoder.add_text('\t') def get_mark(self, value=None): '''Get the mark text for the next list item. :Parameters: `value` : str Optional value of the list item. The meaning is list-type dependent. :rtype: str ''' return '' class UnorderedListBuilder(ListBuilder): def __init__(self, mark): '''Create an unordered list with constant mark text. :Parameters: `mark` : str Mark to prepend to each list item. ''' self.mark = mark def get_mark(self, value): return self.mark class OrderedListBuilder(ListBuilder): format_re = re.compile('(.*?)([1aAiI])(.*)') def __init__(self, start, format): '''Create an ordered list with sequentially numbered mark text. The format is composed of an optional prefix text, a numbering scheme character followed by suffix text. Valid numbering schemes are: ``1`` Decimal Arabic ``a`` Lowercase alphanumeric ``A`` Uppercase alphanumeric ``i`` Lowercase Roman ``I`` Uppercase Roman Prefix text may typically be ``(`` or ``[`` and suffix text is typically ``.``, ``)`` or empty, but either can be any string. :Parameters: `start` : int First list item number. `format` : str Format style, for example ``"1."``. ''' self.next_value = start self.prefix, self.numbering, self.suffix = self.format_re.match(format).groups() assert self.numbering in '1aAiI' def get_mark(self, value): if value is None: value = self.next_value self.next_value = value + 1 if self.numbering in 'aA': try: mark = 'abcdefghijklmnopqrstuvwxyz'[value - 1] except ValueError: mark = '?' if self.numbering == 'A': mark = mark.upper() return '%s%s%s' % (self.prefix, mark, self.suffix) elif self.numbering in 'iI': try: mark = _int_to_roman(value) except ValueError: mark = '?' if self.numbering == 'i': mark = mark.lower() return '%s%s%s' % (self.prefix, mark, self.suffix) else: return '%s%d%s' % (self.prefix, value, self.suffix) class StructuredTextDecoder(pyglet.text.DocumentDecoder): def decode(self, text, location=None): self.len_text = 0 self.current_style = {} self.next_style = {} self.stack = [] self.list_stack = [] self.document = pyglet.text.document.FormattedDocument() if location is None: location = pyglet.resource.FileLocation('') self.decode_structured(text, location) return self.document def decode_structured(self, text, location): raise NotImplementedError('abstract') def push_style(self, key, styles): old_styles = {} for name in styles.keys(): old_styles[name] = self.current_style.get(name) self.stack.append((key, old_styles)) self.current_style.update(styles) self.next_style.update(styles) def pop_style(self, key): # Don't do anything if key is not in stack for match, _ in self.stack: if key == match: break else: return # Remove all innermost elements until key is closed. while True: match, old_styles = self.stack.pop() self.next_style.update(old_styles) self.current_style.update(old_styles) if match == key: break def add_text(self, text): self.document.insert_text(self.len_text, text, self.next_style) self.next_style.clear() self.len_text += len(text) def add_element(self, element): self.document.insert_element(self.len_text, element, self.next_style) self.next_style.clear() self.len_text += 1
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Plain text decoder. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import pyglet class PlainTextDecoder(pyglet.text.DocumentDecoder): def decode(self, text, location=None): document = pyglet.text.document.UnformattedDocument() document.insert_text(0, text) return document
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Document formats. :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id$'
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id: $ '''Render simple text and formatted documents efficiently. Three layout classes are provided: `TextLayout` The entire document is laid out before it is rendered. The layout will be grouped with other layouts in the same batch (allowing for efficient rendering of multiple layouts). Any change to the layout or document, and even querying some properties, will cause the entire document to be laid out again. `ScrollableTextLayout` Based on `TextLayout`. A separate group is used for layout which crops the contents of the layout to the layout rectangle. Additionally, the contents of the layout can be "scrolled" within that rectangle with the ``view_x`` and ``view_y`` properties. `IncrementalTextLayout` Based on `ScrollableTextLayout`. When the layout or document are modified, only the affected regions are laid out again. This permits efficient interactive editing and styling of text. Only the visible portion of the layout is actually rendered; as the viewport is scrolled additional sections are rendered and discarded as required. This permits efficient viewing and editing of large documents. Additionally, this class provides methods for locating the position of a caret in the document, and for displaying interactive text selections. All three layout classes can be used with either `UnformattedDocument` or `FormattedDocument`, and can be either single-line or ``multiline``. The combinations of these options effectively provides 12 different text display possibilities. Style attributes ================ The following character style attribute names are recognised by the layout classes. Data types and units are as specified. Where an attribute is marked "as a distance" the value is assumed to be in pixels if given as an int or float, otherwise a string of the form ``"0u"`` is required, where ``0`` is the distance and ``u`` is the unit; one of ``"px"`` (pixels), ``"pt"`` (points), ``"pc"`` (picas), ``"cm"`` (centimeters), ``"mm"`` (millimeters) or ``"in"`` (inches). For example, ``"14pt"`` is the distance covering 14 points, which at the default DPI of 96 is 18 pixels. ``font_name`` Font family name, as given to `pyglet.font.load`. ``font_size`` Font size, in points. ``bold`` Boolean. ``italic`` Boolean. ``underline`` 4-tuple of ints in range (0, 255) giving RGBA underline color, or None (default) for no underline. ``kerning`` Additional space to insert between glyphs, as a distance. Defaults to 0. ``baseline`` Offset of glyph baseline from line baseline, as a distance. Positive values give a superscript, negative values give a subscript. Defaults to 0. ``color`` 4-tuple of ints in range (0, 255) giving RGBA text color ``background_color`` 4-tuple of ints in range (0, 255) giving RGBA text background color; or ``None`` for no background fill. The following paragraph style attribute names are recognised. Note that paragraph styles are handled no differently from character styles by the document: it is the application's responsibility to set the style over an entire paragraph, otherwise results are undefined. ``align`` ``left`` (default), ``center`` or ``right``. ``indent`` Additional horizontal space to insert before the first glyph of the first line of a paragraph, as a distance. ``leading`` Additional space to insert between consecutive lines within a paragraph, as a distance. Defaults to 0. ``line_spacing`` Distance between consecutive baselines in a paragraph, as a distance. Defaults to ``None``, which automatically calculates the tightest line spacing for each line based on the font ascent and descent. ``margin_left`` Left paragraph margin, as a distance. ``margin_right`` Right paragraph margin, as a distance. ``margin_top`` Margin above paragraph, as a distance. ``margin_bottom`` Margin below paragraph, as a distance. Adjacent margins do not collapse. ``tab_stops`` List of horizontal tab stops, as distances, measured from the left edge of the text layout. Defaults to the empty list. When the tab stops are exhausted, they implicitly continue at 50 pixel intervals. ``wrap`` ``char``, ``word``, True (default) or False. The boundaries at which to wrap text to prevent it overflowing a line. With ``char``, the line wraps anywhere in the text; with ``word`` or True, the line wraps at appropriate boundaries between words; with False the line does not wrap, and may overflow the layout width. ``char`` and ``word`` styles are since pyglet 1.2. Other attributes can be used to store additional style information within the document; they will be ignored by the built-in text classes. :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import re import sys from pyglet.gl import * from pyglet import event from pyglet import graphics from pyglet.text import runlist from pyglet.font.base import _grapheme_break _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc _distance_re = re.compile(r'([-0-9.]+)([a-zA-Z]+)') def _parse_distance(distance, dpi): '''Parse a distance string and return corresponding distance in pixels as an integer. ''' if isinstance(distance, int): return distance elif isinstance(distance, float): return int(distance) match = _distance_re.match(distance) assert match, 'Could not parse distance %s' % (distance) if not match: return 0 value, unit = match.groups() value = float(value) if unit == 'px': return int(value) elif unit == 'pt': return int(value * dpi / 72.0) elif unit == 'pc': return int(value * dpi / 6.0) elif unit == 'in': return int(value * dpi) elif unit == 'mm': return int(value * dpi * 0.0393700787) elif unit == 'cm': return int(value * dpi * 0.393700787) else: assert False, 'Unknown distance unit %s' % unit class _Line(object): align = 'left' margin_left = 0 margin_right = 0 length = 0 ascent = 0 descent = 0 width = 0 paragraph_begin = False paragraph_end = False x = None y = None def __init__(self, start): self.vertex_lists = [] self.start = start self.boxes = [] def __repr__(self): return '_Line(%r)' % self.boxes def add_box(self, box): self.boxes.append(box) self.length += box.length self.ascent = max(self.ascent, box.ascent) self.descent = min(self.descent, box.descent) self.width += box.advance def delete(self, layout): for vertex_list in self.vertex_lists: vertex_list.delete() self.vertex_lists = [] for box in self.boxes: box.delete(layout) class _LayoutContext(object): def __init__(self, layout, document, colors_iter, background_iter): self.colors_iter = colors_iter underline_iter = document.get_style_runs('underline') self.decoration_iter = runlist.ZipRunIterator( (background_iter, underline_iter)) self.baseline_iter = runlist.FilteredRunIterator( document.get_style_runs('baseline'), lambda value: value is not None, 0) class _StaticLayoutContext(_LayoutContext): def __init__(self, layout, document, colors_iter, background_iter): super(_StaticLayoutContext, self).__init__(layout, document, colors_iter, background_iter) self.vertex_lists = layout._vertex_lists self.boxes = layout._boxes def add_list(self, vertex_list): self.vertex_lists.append(vertex_list) def add_box(self, box): self.boxes.append(box) class _IncrementalLayoutContext(_LayoutContext): line = None def add_list(self, vertex_list): self.line.vertex_lists.append(vertex_list) def add_box(self, box): pass class _AbstractBox(object): owner = None def __init__(self, ascent, descent, advance, length): self.ascent = ascent self.descent = descent self.advance = advance self.length = length def place(self, layout, i, x, y): raise NotImplementedError('abstract') def delete(self, layout): raise NotImplementedError('abstract') def get_position_in_box(self, x): raise NotImplementedError('abstract') def get_point_in_box(self, position): raise NotImplementedError('abstract') class _GlyphBox(_AbstractBox): def __init__(self, owner, font, glyphs, advance): '''Create a run of glyphs sharing the same texture. :Parameters: `owner` : `pyglet.image.Texture` Texture of all glyphs in this run. `font` : `pyglet.font.base.Font` Font of all glyphs in this run. `glyphs` : list of (int, `pyglet.font.base.Glyph`) Pairs of ``(kern, glyph)``, where ``kern`` gives horizontal displacement of the glyph in pixels (typically 0). `advance` : int Width of glyph run; must correspond to the sum of advances and kerns in the glyph list. ''' super(_GlyphBox, self).__init__( font.ascent, font.descent, advance, len(glyphs)) assert owner self.owner = owner self.font = font self.glyphs = glyphs self.advance = advance def place(self, layout, i, x, y, context): assert self.glyphs try: group = layout.groups[self.owner] except KeyError: group = layout.groups[self.owner] = \ TextLayoutTextureGroup(self.owner, layout.foreground_group) n_glyphs = self.length vertices = [] tex_coords = [] x1 = x for start, end, baseline in context.baseline_iter.ranges(i, i+n_glyphs): baseline = layout._parse_distance(baseline) assert len(self.glyphs[start - i:end - i]) == end - start for kern, glyph in self.glyphs[start - i:end - i]: x1 += kern v0, v1, v2, v3 = glyph.vertices v0 += x1 v2 += x1 v1 += y + baseline v3 += y + baseline vertices.extend(map(int, [v0, v1, v2, v1, v2, v3, v0, v3])) t = glyph.tex_coords tex_coords.extend(t) x1 += glyph.advance # Text color colors = [] for start, end, color in context.colors_iter.ranges(i, i+n_glyphs): if color is None: color = (0, 0, 0, 255) colors.extend(color * ((end - start) * 4)) vertex_list = layout.batch.add(n_glyphs * 4, GL_QUADS, group, ('v2f/dynamic', vertices), ('t3f/dynamic', tex_coords), ('c4B/dynamic', colors)) context.add_list(vertex_list) # Decoration (background color and underline) # # Should iterate over baseline too, but in practice any sensible # change in baseline will correspond with a change in font size, # and thus glyph run as well. So we cheat and just use whatever # baseline was seen last. background_vertices = [] background_colors = [] underline_vertices = [] underline_colors = [] y1 = y + self.descent + baseline y2 = y + self.ascent + baseline x1 = x for start, end, decoration in \ context.decoration_iter.ranges(i, i+n_glyphs): bg, underline = decoration x2 = x1 for kern, glyph in self.glyphs[start - i:end - i]: x2 += glyph.advance + kern if bg is not None: background_vertices.extend( [x1, y1, x2, y1, x2, y2, x1, y2]) background_colors.extend(bg * 4) if underline is not None: underline_vertices.extend( [x1, y + baseline - 2, x2, y + baseline - 2]) underline_colors.extend(underline * 2) x1 = x2 if background_vertices: background_list = layout.batch.add( len(background_vertices) // 2, GL_QUADS, layout.background_group, ('v2f/dynamic', background_vertices), ('c4B/dynamic', background_colors)) context.add_list(background_list) if underline_vertices: underline_list = layout.batch.add( len(underline_vertices) // 2, GL_LINES, layout.foreground_decoration_group, ('v2f/dynamic', underline_vertices), ('c4B/dynamic', underline_colors)) context.add_list(underline_list) def delete(self, layout): pass def get_point_in_box(self, position): x = 0 for (kern, glyph) in self.glyphs: if position == 0: break position -= 1 x += glyph.advance + kern return x def get_position_in_box(self, x): position = 0 last_glyph_x = 0 for kern, glyph in self.glyphs: last_glyph_x += kern if last_glyph_x + glyph.advance / 2 > x: return position position += 1 last_glyph_x += glyph.advance return position def __repr__(self): return '_GlyphBox(%r)' % self.glyphs class _InlineElementBox(_AbstractBox): def __init__(self, element): '''Create a glyph run holding a single element. ''' super(_InlineElementBox, self).__init__( element.ascent, element.descent, element.advance, 1) self.element = element self.placed = False def place(self, layout, i, x, y, context): self.element.place(layout, x, y) self.placed = True context.add_box(self) def delete(self, layout): # font == element if self.placed: self.element.remove(layout) self.placed = False def get_point_in_box(self, position): if position == 0: return 0 else: return self.advance def get_position_in_box(self, x): if x < self.advance / 2: return 0 else: return 1 def __repr__(self): return '_InlineElementBox(%r)' % self.element class _InvalidRange(object): def __init__(self): self.start = sys.maxint self.end = 0 def insert(self, start, length): if self.start >= start: self.start += length if self.end >= start: self.end += length self.invalidate(start, start + length) def delete(self, start, end): if self.start > end: self.start -= end - start elif self.start > start: self.start = start if self.end > end: self.end -= end - start elif self.end > start: self.end = start def invalidate(self, start, end): if end <= start: return self.start = min(self.start, start) self.end = max(self.end, end) def validate(self): start, end = self.start, self.end self.start = sys.maxint self.end = 0 return start, end def is_invalid(self): return self.end > self.start # Text group hierarchy # # top_group [Scrollable]TextLayoutGroup(Group) # background_group OrderedGroup(0) # foreground_group TextLayoutForegroundGroup(OrderedGroup(1)) # [font textures] TextLayoutTextureGroup(Group) # [...] TextLayoutTextureGroup(Group) # foreground_decoration_group # TextLayoutForegroundDecorationGroup(OrderedGroup(2)) class TextLayoutGroup(graphics.Group): '''Top-level rendering group for `TextLayout`. The blend function is set for glyph rendering (``GL_SRC_ALPHA`` / ``GL_ONE_MINUS_SRC_ALPHA``). The group is shared by all `TextLayout` instances as it has no internal state. ''' def set_state(self): glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) def unset_state(self): glPopAttrib() class ScrollableTextLayoutGroup(graphics.Group): '''Top-level rendering group for `ScrollableTextLayout`. The group maintains internal state for setting the clipping planes and view transform for scrolling. Because the group has internal state specific to the text layout, the group is never shared. ''' _clip_x = 0 _clip_y = 0 _clip_width = 0 _clip_height = 0 _view_x = 0 _view_y = 0 translate_x = 0 # x - view_x translate_y = 0 # y - view_y def set_state(self): glPushAttrib(GL_ENABLE_BIT | GL_TRANSFORM_BIT | GL_CURRENT_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # Disable clipping planes to check culling. glEnable(GL_CLIP_PLANE0) glEnable(GL_CLIP_PLANE1) glEnable(GL_CLIP_PLANE2) glEnable(GL_CLIP_PLANE3) # Left glClipPlane(GL_CLIP_PLANE0, (GLdouble * 4)( 1, 0, 0, -(self._clip_x - 1))) # Top glClipPlane(GL_CLIP_PLANE1, (GLdouble * 4)( 0, -1, 0, self._clip_y)) # Right glClipPlane(GL_CLIP_PLANE2, (GLdouble * 4)( -1, 0, 0, self._clip_x + self._clip_width + 1)) # Bottom glClipPlane(GL_CLIP_PLANE3, (GLdouble * 4)( 0, 1, 0, -(self._clip_y - self._clip_height))) glTranslatef(self.translate_x, self.translate_y, 0) def unset_state(self): glTranslatef(-self.translate_x, -self.translate_y, 0) glPopAttrib() def _set_top(self, top): self._clip_y = top self.translate_y = self._clip_y - self._view_y top = property(lambda self: self._clip_y, _set_top, doc='''Top edge of the text layout (measured from the bottom of the graphics viewport). :type: int ''') def _set_left(self, left): self._clip_x = left self.translate_x = self._clip_x - self._view_x left = property(lambda self: self._clip_x, _set_left, doc='''Left edge of the text layout. :type: int ''') def _set_width(self, width): self._clip_width = width width = property(lambda self: self._clip_width, _set_width, doc='''Width of the text layout. :type: int ''') def _set_height(self, height): self._clip_height = height height = property(lambda self: self._height, _set_height, doc='''Height of the text layout. :type: int ''') def _set_view_x(self, view_x): self._view_x = view_x self.translate_x = self._clip_x - self._view_x view_x = property(lambda self: self._view_x, _set_view_x, doc='''Horizontal scroll offset. :type: int ''') def _set_view_y(self, view_y): self._view_y = view_y self.translate_y = self._clip_y - self._view_y view_y = property(lambda self: self._view_y, _set_view_y, doc='''Vertical scroll offset. :type: int ''') def __eq__(self, other): return self is other def __hash__(self): return id(self) class TextLayoutForegroundGroup(graphics.OrderedGroup): '''Rendering group for foreground elements (glyphs) in all text layouts. The group enables ``GL_TEXTURE_2D``. ''' def set_state(self): glEnable(GL_TEXTURE_2D) # unset_state not needed, as parent group will pop enable bit class TextLayoutForegroundDecorationGroup(graphics.OrderedGroup): '''Rendering group for decorative elements (e.g., glyph underlines) in all text layouts. The group disables ``GL_TEXTURE_2D``. ''' def set_state(self): glDisable(GL_TEXTURE_2D) # unset_state not needed, as parent group will pop enable bit class TextLayoutTextureGroup(graphics.Group): '''Rendering group for a glyph texture in all text layouts. The group binds its texture to ``GL_TEXTURE_2D``. The group is shared between all other text layout uses of the same texture. ''' def __init__(self, texture, parent): assert texture.target == GL_TEXTURE_2D super(TextLayoutTextureGroup, self).__init__(parent) self.texture = texture def set_state(self): glBindTexture(GL_TEXTURE_2D, self.texture.id) # unset_state not needed, as next group will either bind a new texture or # pop enable bit. def __hash__(self): return hash((self.texture.id, self.parent)) def __eq__(self, other): return (self.__class__ is other.__class__ and self.texture.id == other.texture.id and self.parent is other.parent) def __repr__(self): return '%s(%d, %r)' % (self.__class__.__name__, self.texture.id, self.parent) class TextLayout(object): '''Lay out and display documents. This class is intended for displaying documents that do not change regularly -- any change will cost some time to lay out the complete document again and regenerate all vertex lists. The benefit of this class is that texture state is shared between all layouts of this class. The time to draw one `TextLayout` may be roughly the same as the time to draw one `IncrementalTextLayout`; but drawing ten `TextLayout` objects in one batch is much faster than drawing ten incremental or scrollable text layouts. `Label` and `HTMLLabel` provide a convenient interface to this class. :Ivariables: `content_width` : int Calculated width of the text in the layout. This may overflow the desired width if word-wrapping failed. `content_height` : int Calculated height of the text in the layout. `top_group` : `Group` Top-level rendering group. `background_group` : `Group` Rendering group for background color. `foreground_group` : `Group` Rendering group for glyphs. `foreground_decoration_group` : `Group` Rendering group for glyph underlines. ''' _document = None _vertex_lists = () _boxes = () top_group = TextLayoutGroup() background_group = graphics.OrderedGroup(0, top_group) foreground_group = TextLayoutForegroundGroup(1, top_group) foreground_decoration_group = \ TextLayoutForegroundDecorationGroup(2, top_group) _update_enabled = True _own_batch = False _origin_layout = False # Lay out relative to origin? Otherwise to box. def __init__(self, document, width=None, height=None, multiline=False, dpi=None, batch=None, group=None, wrap_lines=True): '''Create a text layout. :Parameters: `document` : `AbstractDocument` Document to display. `width` : int Width of the layout in pixels, or None `height` : int Height of the layout in pixels, or None `multiline` : bool If False, newline and paragraph characters are ignored, and text is not word-wrapped. If True, text is wrapped only if the `wrap_lines` is True. `dpi` : float Font resolution; defaults to 96. `batch` : `Batch` Optional graphics batch to add this layout to. `group` : `Group` Optional rendering group to parent all groups this text layout uses. Note that layouts with different rendered simultaneously in a batch. `wrap_lines` : bool If True and `multiline` is True, the text is word-wrapped using the specified width. ''' self.content_width = 0 self.content_height = 0 self.groups = {} self._init_groups(group) if batch is None: batch = graphics.Batch() self._own_batch = True self.batch = batch self._width = width if height is not None: self._height = height if multiline: self._multiline = multiline self._wrap_lines_flag = wrap_lines self._wrap_lines_invariant() if dpi is None: dpi = 96 self._dpi = dpi self.document = document def _wrap_lines_invariant(self): self._wrap_lines = self._multiline and self._wrap_lines_flag assert not self._wrap_lines or self._width, "When the parameters "\ "'multiline' and 'wrap_lines' are True, the parameter 'width'"\ "must be a number." def _parse_distance(self, distance): if distance is None: return None return _parse_distance(distance, self._dpi) def begin_update(self): '''Indicate that a number of changes to the layout or document are about to occur. Changes to the layout or document between calls to `begin_update` and `end_update` do not trigger any costly relayout of text. Relayout of all changes is performed when `end_update` is called. Note that between the `begin_update` and `end_update` calls, values such as `content_width` and `content_height` are undefined (i.e., they may or may not be updated to reflect the latest changes). ''' self._update_enabled = False def end_update(self): '''Perform pending layout changes since `begin_update`. See `begin_update`. ''' self._update_enabled = True self._update() dpi = property(lambda self: self._dpi, doc='''Get DPI used by this layout. Read-only. :type: float ''') def delete(self): '''Remove this layout from its batch. ''' for vertex_list in self._vertex_lists: vertex_list.delete() self._vertex_lists = [] for box in self._boxes: box.delete(self) def draw(self): '''Draw this text layout. Note that this method performs very badly if a batch was supplied to the constructor. If you add this layout to a batch, you should ideally use only the batch's draw method. ''' if self._own_batch: self.batch.draw() else: self.batch.draw_subset(self._vertex_lists) def _init_groups(self, group): if group: self.top_group = TextLayoutGroup(group) self.background_group = graphics.OrderedGroup(0, self.top_group) self.foreground_group = TextLayoutForegroundGroup(1, self.top_group) self.foreground_decoration_group = \ TextLayoutForegroundDecorationGroup(2, self.top_group) # Otherwise class groups are (re)used. def _get_document(self): return self._document def _set_document(self, document): if self._document: self._document.remove_handlers(self) self._uninit_document() document.push_handlers(self) self._document = document self._init_document() document = property(_get_document, _set_document, '''Document to display. For `IncrementalTextLayout` it is far more efficient to modify a document in-place than to replace the document instance on the layout. :type: `AbstractDocument` ''') def _get_lines(self): len_text = len(self._document.text) glyphs = self._get_glyphs() owner_runs = runlist.RunList(len_text, None) self._get_owner_runs(owner_runs, glyphs, 0, len_text) lines = [line for line in self._flow_glyphs(glyphs, owner_runs, 0, len_text)] self.content_width = 0 self._flow_lines(lines, 0, len(lines)) return lines def _update(self): if not self._update_enabled: return for _vertex_list in self._vertex_lists: _vertex_list.delete() for box in self._boxes: box.delete(self) self._vertex_lists = [] self._boxes = [] self.groups.clear() if not self._document or not self._document.text: return lines = self._get_lines() colors_iter = self._document.get_style_runs('color') background_iter = self._document.get_style_runs('background_color') if self._origin_layout: left = top = 0 else: left = self._get_left() top = self._get_top(lines) context = _StaticLayoutContext(self, self._document, colors_iter, background_iter) for line in lines: self._create_vertex_lists(left + line.x, top + line.y, line.start, line.boxes, context) def _get_left(self): if self._multiline: width = self._width if self._wrap_lines else self.content_width else: width = self.content_width if self._anchor_x == 'left': return self._x elif self._anchor_x == 'center': return self._x - width // 2 elif self._anchor_x == 'right': return self._x - width else: assert False, 'Invalid anchor_x' def _get_top(self, lines): if self._height is None: height = self.content_height offset = 0 else: height = self._height if self._content_valign == 'top': offset = 0 elif self._content_valign == 'bottom': offset = max(0, self._height - self.content_height) elif self._content_valign == 'center': offset = max(0, self._height - self.content_height) // 2 else: assert False, 'Invalid content_valign' if self._anchor_y == 'top': return self._y - offset elif self._anchor_y == 'baseline': return self._y + lines[0].ascent - offset elif self._anchor_y == 'bottom': return self._y + height - offset elif self._anchor_y == 'center': if len(lines) == 1 and self._height is None: # This "looks" more centered than considering all of the # descent. line = lines[0] return self._y + line.ascent // 2 - line.descent // 4 else: return self._y + height // 2 - offset else: assert False, 'Invalid anchor_y' def _init_document(self): self._update() def _uninit_document(self): pass def on_insert_text(self, start, text): '''Event handler for `AbstractDocument.on_insert_text`. The event handler is bound by the text layout; there is no need for applications to interact with this method. ''' self._init_document() def on_delete_text(self, start, end): '''Event handler for `AbstractDocument.on_delete_text`. The event handler is bound by the text layout; there is no need for applications to interact with this method. ''' self._init_document() def on_style_text(self, start, end, attributes): '''Event handler for `AbstractDocument.on_style_text`. The event handler is bound by the text layout; there is no need for applications to interact with this method. ''' self._init_document() def _get_glyphs(self): glyphs = [] runs = runlist.ZipRunIterator(( self._document.get_font_runs(dpi=self._dpi), self._document.get_element_runs())) text = self._document.text for start, end, (font, element) in runs.ranges(0, len(text)): if element: glyphs.append(_InlineElementBox(element)) else: glyphs.extend(font.get_glyphs(text[start:end])) return glyphs def _get_owner_runs(self, owner_runs, glyphs, start, end): owner = glyphs[start].owner run_start = start # TODO avoid glyph slice on non-incremental for i, glyph in enumerate(glyphs[start:end]): if owner != glyph.owner: owner_runs.set_run(run_start, i + start, owner) owner = glyph.owner run_start = i + start owner_runs.set_run(run_start, end, owner) def _flow_glyphs(self, glyphs, owner_runs, start, end): # TODO change flow generator on self, avoiding this conditional. if not self._multiline: for line in self._flow_glyphs_single_line(glyphs, owner_runs, start, end): yield line else: for line in self._flow_glyphs_wrap(glyphs, owner_runs, start, end): yield line def _flow_glyphs_wrap(self, glyphs, owner_runs, start, end): '''Word-wrap styled text into lines of fixed width. Fits `glyphs` in range `start` to `end` into `_Line` s which are then yielded. ''' owner_iterator = owner_runs.get_run_iterator().ranges(start, end) font_iterator = self._document.get_font_runs(dpi=self._dpi) align_iterator = runlist.FilteredRunIterator( self._document.get_style_runs('align'), lambda value: value in ('left', 'right', 'center'), 'left') if self._width is None: wrap_iterator = runlist.ConstRunIterator( len(self.document.text), False) else: wrap_iterator = runlist.FilteredRunIterator( self._document.get_style_runs('wrap'), lambda value: value in (True, False, 'char', 'word'), True) margin_left_iterator = runlist.FilteredRunIterator( self._document.get_style_runs('margin_left'), lambda value: value is not None, 0) margin_right_iterator = runlist.FilteredRunIterator( self._document.get_style_runs('margin_right'), lambda value: value is not None, 0) indent_iterator = runlist.FilteredRunIterator( self._document.get_style_runs('indent'), lambda value: value is not None, 0) kerning_iterator = runlist.FilteredRunIterator( self._document.get_style_runs('kerning'), lambda value: value is not None, 0) tab_stops_iterator = runlist.FilteredRunIterator( self._document.get_style_runs('tab_stops'), lambda value: value is not None, []) line = _Line(start) line.align = align_iterator[start] line.margin_left = self._parse_distance(margin_left_iterator[start]) line.margin_right = self._parse_distance(margin_right_iterator[start]) if start == 0 or self.document.text[start - 1] in u'\n\u2029': line.paragraph_begin = True line.margin_left += self._parse_distance(indent_iterator[start]) wrap = wrap_iterator[start] if self._wrap_lines: width = self._width - line.margin_left - line.margin_right # Current right-most x position in line being laid out. x = 0 # Boxes accumulated but not yet committed to a line. run_accum = [] run_accum_width = 0 # Amount of whitespace accumulated at end of line eol_ws = 0 # Iterate over glyph owners (texture states); these form GlyphBoxes, # but broken into lines. font = None for start, end, owner in owner_iterator: font = font_iterator[start] # Glyphs accumulated in this owner but not yet committed to a # line. owner_accum = [] owner_accum_width = 0 # Glyphs accumulated in this owner AND also committed to the # current line (some whitespace has followed all of the committed # glyphs). owner_accum_commit = [] owner_accum_commit_width = 0 # Ignore kerning of first glyph on each line nokern = True # Current glyph index index = start # Iterate over glyphs in this owner run. `text` is the # corresponding character data for the glyph, and is used to find # whitespace and newlines. for (text, glyph) in zip(self.document.text[start:end], glyphs[start:end]): if nokern: kern = 0 nokern = False else: kern = self._parse_distance(kerning_iterator[index]) if wrap != 'char' and text in u'\u0020\u200b\t': # Whitespace: commit pending runs to this line. for run in run_accum: line.add_box(run) run_accum = [] run_accum_width = 0 if text == '\t': # Fix up kern for this glyph to align to the next tab # stop for tab_stop in tab_stops_iterator[index]: tab_stop = self._parse_distance(tab_stop) if tab_stop > x + line.margin_left: break else: # No more tab stops, tab to 100 pixels tab = 50. tab_stop = \ (((x + line.margin_left) // tab) + 1) * tab kern = int(tab_stop - x - line.margin_left - glyph.advance) owner_accum.append((kern, glyph)) owner_accum_commit.extend(owner_accum) owner_accum_commit_width += owner_accum_width + \ glyph.advance + kern eol_ws += glyph.advance + kern owner_accum = [] owner_accum_width = 0 x += glyph.advance + kern index += 1 # The index at which the next line will begin (the # current index, because this is the current best # breakpoint). next_start = index else: new_paragraph = text in u'\n\u2029' new_line = (text == u'\u2028') or new_paragraph if (wrap and self._wrap_lines and x + kern + glyph.advance >= width) or new_line: # Either the pending runs have overflowed the allowed # line width or a newline was encountered. Either # way, the current line must be flushed. if new_line or wrap == 'char': # Forced newline or char-level wrapping. Commit # everything pending without exception. for run in run_accum: line.add_box(run) run_accum = [] run_accum_width = 0 owner_accum_commit.extend(owner_accum) owner_accum_commit_width += owner_accum_width owner_accum = [] owner_accum_width = 0 line.length += 1 next_start = index if new_line: next_start += 1 # Create the _GlyphBox for the committed glyphs in the # current owner. if owner_accum_commit: line.add_box( _GlyphBox(owner, font, owner_accum_commit, owner_accum_commit_width)) owner_accum_commit = [] owner_accum_commit_width = 0 if new_line and not line.boxes: # Empty line: give it the current font's default # line-height. line.ascent = font.ascent line.descent = font.descent # Flush the line, unless nothing got committed, in # which case it's a really long string of glyphs # without any breakpoints (in which case it will be # flushed at the earliest breakpoint, not before # something is committed). if line.boxes or new_line: # Trim line width of whitespace on right-side. line.width -= eol_ws if new_paragraph: line.paragraph_end = True yield line line = _Line(next_start) line.align = align_iterator[next_start] line.margin_left = self._parse_distance( margin_left_iterator[next_start]) line.margin_right = self._parse_distance( margin_right_iterator[next_start]) if new_paragraph: line.paragraph_begin = True # Remove kern from first glyph of line if run_accum: k, g = run_accum[0].glyphs[0] run_accum[0].glyphs[0] = (0, g) run_accum_width -= k elif owner_accum: k, g = owner_accum[0] owner_accum[0] = (0, g) owner_accum_width -= k else: nokern = True x = run_accum_width + owner_accum_width if self._wrap_lines: width = (self._width - line.margin_left - line.margin_right) if isinstance(glyph, _AbstractBox): # Glyph is already in a box. XXX Ignore kern? run_accum.append(glyph) run_accum_width += glyph.advance x += glyph.advance elif new_paragraph: # New paragraph started, update wrap style wrap = wrap_iterator[next_start] line.margin_left += \ self._parse_distance(indent_iterator[next_start]) if self._wrap_lines: width = (self._width - line.margin_left - line.margin_right) elif not new_line: # If the glyph was any non-whitespace, non-newline # character, add it to the pending run. owner_accum.append((kern, glyph)) owner_accum_width += glyph.advance + kern x += glyph.advance + kern index += 1 eol_ws = 0 # The owner run is finished; create GlyphBoxes for the committed # and pending glyphs. if owner_accum_commit: line.add_box(_GlyphBox(owner, font, owner_accum_commit, owner_accum_commit_width)) if owner_accum: run_accum.append(_GlyphBox(owner, font, owner_accum, owner_accum_width)) run_accum_width += owner_accum_width # All glyphs have been processed: commit everything pending and flush # the final line. for run in run_accum: line.add_box(run) if not line.boxes: # Empty line gets font's line-height if font is None: font = self._document.get_font(0, dpi=self._dpi) line.ascent = font.ascent line.descent = font.descent yield line def _flow_glyphs_single_line(self, glyphs, owner_runs, start, end): owner_iterator = owner_runs.get_run_iterator().ranges(start, end) font_iterator = self.document.get_font_runs(dpi=self._dpi) kern_iterator = runlist.FilteredRunIterator( self.document.get_style_runs('kerning'), lambda value: value is not None, 0) line = _Line(start) font = font_iterator[0] for start, end, owner in owner_iterator: font = font_iterator[start] width = 0 owner_glyphs = [] for kern_start, kern_end, kern in kern_iterator.ranges(start, end): gs = glyphs[kern_start:kern_end] width += sum([g.advance for g in gs]) width += kern * (kern_end - kern_start) owner_glyphs.extend(zip([kern] * (kern_end - kern_start), gs)) if owner is None: # Assume glyphs are already boxes. for kern, glyph in owner_glyphs: line.add_box(glyph) else: line.add_box(_GlyphBox(owner, font, owner_glyphs, width)) if not line.boxes: line.ascent = font.ascent line.descent = font.descent line.paragraph_begin = line.paragraph_end = True yield line def _flow_lines(self, lines, start, end): margin_top_iterator = runlist.FilteredRunIterator( self._document.get_style_runs('margin_top'), lambda value: value is not None, 0) margin_bottom_iterator = runlist.FilteredRunIterator( self._document.get_style_runs('margin_bottom'), lambda value: value is not None, 0) line_spacing_iterator = self._document.get_style_runs('line_spacing') leading_iterator = runlist.FilteredRunIterator( self._document.get_style_runs('leading'), lambda value: value is not None, 0) if start == 0: y = 0 else: line = lines[start - 1] line_spacing = \ self._parse_distance(line_spacing_iterator[line.start]) leading = \ self._parse_distance(leading_iterator[line.start]) y = line.y if line_spacing is None: y += line.descent if line.paragraph_end: y -= self._parse_distance(margin_bottom_iterator[line.start]) line_index = start for line in lines[start:]: if line.paragraph_begin: y -= self._parse_distance(margin_top_iterator[line.start]) line_spacing = \ self._parse_distance(line_spacing_iterator[line.start]) leading = self._parse_distance(leading_iterator[line.start]) else: y -= leading if line_spacing is None: y -= line.ascent else: y -= line_spacing if line.align == 'left' or line.width > self.width: line.x = line.margin_left elif line.align == 'center': line.x = (self.width - line.margin_left - line.margin_right - line.width) // 2 + line.margin_left elif line.align == 'right': line.x = self.width - line.margin_right - line.width self.content_width = max(self.content_width, line.width + line.margin_left) if line.y == y and line_index >= end: # Early exit: all invalidated lines have been reflowed and the # next line has no change (therefore subsequent lines do not # need to be changed). break line.y = y if line_spacing is None: y += line.descent if line.paragraph_end: y -= self._parse_distance(margin_bottom_iterator[line.start]) line_index += 1 else: self.content_height = -y return line_index def _create_vertex_lists(self, x, y, i, boxes, context): for box in boxes: box.place(self, i, x, y, context) x += box.advance i += box.length _x = 0 def _set_x(self, x): if self._boxes: self._x = x self._update() else: dx = x - self._x l_dx = lambda x: int(x + dx) for vertex_list in self._vertex_lists: vertices = vertex_list.vertices[:] vertices[::2] = map(l_dx, vertices[::2]) vertex_list.vertices[:] = vertices self._x = x def _get_x(self): return self._x x = property(_get_x, _set_x, doc='''X coordinate of the layout. See also `anchor_x`. :type: int ''') _y = 0 def _set_y(self, y): if self._boxes: self._y = y self._update() else: dy = y - self._y l_dy = lambda y: int(y + dy) for vertex_list in self._vertex_lists: vertices = vertex_list.vertices[:] vertices[1::2] = map(l_dy, vertices[1::2]) vertex_list.vertices[:] = vertices self._y = y def _get_y(self): return self._y y = property(_get_y, _set_y, doc='''Y coordinate of the layout. See also `anchor_y`. :type: int ''') _width = None def _set_width(self, width): self._width = width self._wrap_lines_invariant() self._update() def _get_width(self): return self._width width = property(_get_width, _set_width, doc='''Width of the layout. This property has no effect if `multiline` is False or `wrap_lines` is False. :type: int ''') _height = None def _set_height(self, height): self._height = height self._update() def _get_height(self): return self._height height = property(_get_height, _set_height, doc='''Height of the layout. :type: int ''') _multiline = False def _set_multiline(self, multiline): self._multiline = multiline self._wrap_lines_invariant() self._update() def _get_multiline(self): return self._multiline multiline = property(_get_multiline, _set_multiline, doc='''Set if multiline layout is enabled. If multiline is False, newline and paragraph characters are ignored and text is not word-wrapped. If True, the text is word-wrapped only if the `wrap_lines` is True. :type: bool ''') _anchor_x = 'left' def _set_anchor_x(self, anchor_x): self._anchor_x = anchor_x self._update() def _get_anchor_x(self): return self._anchor_x anchor_x = property(_get_anchor_x, _set_anchor_x, doc='''Horizontal anchor alignment. This property determines the meaning of the `x` coordinate. It is one of the enumerants: ``"left"`` (default) The X coordinate gives the position of the left edge of the layout. ``"center"`` The X coordinate gives the position of the center of the layout. ``"right"`` The X coordinate gives the position of the right edge of the layout. For the purposes of calculating the position resulting from this alignment, the width of the layout is taken to be `width` if `multiline` is True and `wrap_lines` is True, otherwise `content_width`. :type: str ''') _anchor_y = 'bottom' def _set_anchor_y(self, anchor_y): self._anchor_y = anchor_y self._update() def _get_anchor_y(self): return self._anchor_y anchor_y = property(_get_anchor_y, _set_anchor_y, doc='''Vertical anchor alignment. This property determines the meaning of the `y` coordinate. It is one of the enumerants: ``"top"`` The Y coordinate gives the position of the top edge of the layout. ``"center"`` The Y coordinate gives the position of the center of the layout. ``"baseline"`` The Y coordinate gives the position of the baseline of the first line of text in the layout. ``"bottom"`` (default) The Y coordinate gives the position of the bottom edge of the layout. For the purposes of calculating the position resulting from this alignment, the height of the layout is taken to be the smaller of `height` and `content_height`. See also `content_valign`. :type: str ''') _content_valign = 'top' def _set_content_valign(self, content_valign): self._content_valign = content_valign self._update() def _get_content_valign(self): return self._content_valign content_valign = property(_get_content_valign, _set_content_valign, doc='''Vertical alignment of content within larger layout box. This property determines how content is positioned within the layout box when ``content_height`` is less than ``height``. It is one of the enumerants: ``top`` (default) Content is aligned to the top of the layout box. ``center`` Content is centered vertically within the layout box. ``bottom`` Content is aligned to the bottom of the layout box. This property has no effect when ``content_height`` is greater than ``height`` (in which case the content is aligned to the top) or when ``height`` is ``None`` (in which case there is no vertical layout box dimension). :type: str ''') class ScrollableTextLayout(TextLayout): '''Display text in a scrollable viewport. This class does not display a scrollbar or handle scroll events; it merely clips the text that would be drawn in `TextLayout` to the bounds of the layout given by `x`, `y`, `width` and `height`; and offsets the text by a scroll offset. Use `view_x` and `view_y` to scroll the text within the viewport. ''' _origin_layout = True def __init__(self, document, width, height, multiline=False, dpi=None, batch=None, group=None, wrap_lines=True): super(ScrollableTextLayout, self).__init__( document, width, height, multiline, dpi, batch, group, wrap_lines) self.top_group.width = self._width self.top_group.height = self._height def _init_groups(self, group): # Scrollable layout never shares group becauase of translation. self.top_group = ScrollableTextLayoutGroup(group) self.background_group = graphics.OrderedGroup(0, self.top_group) self.foreground_group = TextLayoutForegroundGroup(1, self.top_group) self.foreground_decoration_group = \ TextLayoutForegroundDecorationGroup(2, self.top_group) def _set_x(self, x): self._x = x self.top_group.left = self._get_left() def _get_x(self): return self._x x = property(_get_x, _set_x) def _set_y(self, y): self._y = y self.top_group.top = self._get_top(self._get_lines()) def _get_y(self): return self._y y = property(_get_y, _set_y) def _set_width(self, width): super(ScrollableTextLayout, self)._set_width(width) self.top_group.left = self._get_left() self.top_group.width = self._width def _get_width(self): return self._width width = property(_get_width, _set_width) def _set_height(self, height): super(ScrollableTextLayout, self)._set_height(height) self.top_group.top = self._get_top(self._get_lines()) self.top_group.height = self._height def _get_height(self): return self._height height = property(_get_height, _set_height) def _set_anchor_x(self, anchor_x): self._anchor_x = anchor_x self.top_group.left = self._get_left() def _get_anchor_x(self): return self._anchor_x anchor_x = property(_get_anchor_x, _set_anchor_x) def _set_anchor_y(self, anchor_y): self._anchor_y = anchor_y self.top_group.top = self._get_top(self._get_lines()) def _get_anchor_y(self): return self._anchor_y anchor_y = property(_get_anchor_y, _set_anchor_y) # Offset of content within viewport def _set_view_x(self, view_x): view_x = max(0, min(self.content_width - self.width, view_x)) self.top_group.view_x = view_x def _get_view_x(self): return self.top_group.view_x view_x = property(_get_view_x, _set_view_x, doc='''Horizontal scroll offset. The initial value is 0, and the left edge of the text will touch the left side of the layout bounds. A positive value causes the text to "scroll" to the right. Values are automatically clipped into the range ``[0, content_width - width]`` :type: int ''') def _set_view_y(self, view_y): # view_y must be negative. view_y = min(0, max(self.height - self.content_height, view_y)) self.top_group.view_y = view_y def _get_view_y(self): return self.top_group.view_y view_y = property(_get_view_y, _set_view_y, doc='''Vertical scroll offset. The initial value is 0, and the top of the text will touch the top of the layout bounds (unless the content height is less than the layout height, in which case `content_valign` is used). A negative value causes the text to "scroll" upwards. Values outside of the range ``[height - content_height, 0]`` are automatically clipped in range. :type: int ''') class IncrementalTextLayout(ScrollableTextLayout, event.EventDispatcher): '''Displayed text suitable for interactive editing and/or scrolling large documents. Unlike `TextLayout` and `ScrollableTextLayout`, this class generates vertex lists only for lines of text that are visible. As the document is scrolled, vertex lists are deleted and created as appropriate to keep video memory usage to a minimum and improve rendering speed. Changes to the document are quickly reflected in this layout, as only the affected line(s) are reflowed. Use `begin_update` and `end_update` to further reduce the amount of processing required. The layout can also display a text selection (text with a different background color). The `Caret` class implements a visible text cursor and provides event handlers for scrolling, selecting and editing text in an incremental text layout. ''' _selection_start = 0 _selection_end = 0 _selection_color = [255, 255, 255, 255] _selection_background_color = [46, 106, 197, 255] def __init__(self, document, width, height, multiline=False, dpi=None, batch=None, group=None, wrap_lines=True): event.EventDispatcher.__init__(self) self.glyphs = [] self.lines = [] self.invalid_glyphs = _InvalidRange() self.invalid_flow = _InvalidRange() self.invalid_lines = _InvalidRange() self.invalid_style = _InvalidRange() self.invalid_vertex_lines = _InvalidRange() self.visible_lines = _InvalidRange() self.owner_runs = runlist.RunList(0, None) ScrollableTextLayout.__init__(self, document, width, height, multiline, dpi, batch, group, wrap_lines) self.top_group.width = width self.top_group.left = self._get_left() self.top_group.height = height self.top_group.top = self._get_top(self._get_lines()) def _init_document(self): assert self._document, \ 'Cannot remove document from IncrementalTextLayout' self.on_insert_text(0, self._document.text) def _uninit_document(self): self.on_delete_text(0, len(self._document.text)) def _get_lines(self): return self.lines def delete(self): for line in self.lines: line.delete(self) self.batch = None if self._document: self._document.remove_handlers(self) self._document = None def on_insert_text(self, start, text): len_text = len(text) self.glyphs[start:start] = [None] * len_text self.invalid_glyphs.insert(start, len_text) self.invalid_flow.insert(start, len_text) self.invalid_style.insert(start, len_text) self.owner_runs.insert(start, len_text) for line in self.lines: if line.start >= start: line.start += len_text self._update() def on_delete_text(self, start, end): self.glyphs[start:end] = [] self.invalid_glyphs.delete(start, end) self.invalid_flow.delete(start, end) self.invalid_style.delete(start, end) self.owner_runs.delete(start, end) size = end - start for line in self.lines: if line.start > start: line.start = max(line.start - size, start) if start == 0: self.invalid_flow.invalidate(0, 1) else: self.invalid_flow.invalidate(start - 1, start) self._update() def on_style_text(self, start, end, attributes): if ('font_name' in attributes or 'font_size' in attributes or 'bold' in attributes or 'italic' in attributes): self.invalid_glyphs.invalidate(start, end) elif False: # Attributes that change flow self.invalid_flow.invalidate(start, end) elif ('color' in attributes or 'background_color' in attributes): self.invalid_style.invalidate(start, end) self._update() def _update(self): if not self._update_enabled: return trigger_update_event = (self.invalid_glyphs.is_invalid() or self.invalid_flow.is_invalid() or self.invalid_lines.is_invalid()) # Special care if there is no text: if not self.glyphs: for line in self.lines: line.delete(self) del self.lines[:] self.lines.append(_Line(0)) font = self.document.get_font(0, dpi=self._dpi) self.lines[0].ascent = font.ascent self.lines[0].descent = font.descent self.lines[0].paragraph_begin = self.lines[0].paragraph_end = True self.invalid_lines.invalidate(0, 1) self._update_glyphs() self._update_flow_glyphs() self._update_flow_lines() self._update_visible_lines() self._update_vertex_lists() self.top_group.top = self._get_top(self.lines) # Reclamp view_y in case content height has changed and reset top of # content. self.view_y = self.view_y self.top_group.top = self._get_top(self._get_lines()) if trigger_update_event: self.dispatch_event('on_layout_update') def _update_glyphs(self): invalid_start, invalid_end = self.invalid_glyphs.validate() if invalid_end - invalid_start <= 0: return # Find grapheme breaks and extend glyph range to encompass. text = self.document.text while invalid_start > 0: if _grapheme_break(text[invalid_start - 1], text[invalid_start]): break invalid_start -= 1 len_text = len(text) while invalid_end < len_text: if _grapheme_break(text[invalid_end - 1], text[invalid_end]): break invalid_end += 1 # Update glyphs runs = runlist.ZipRunIterator(( self._document.get_font_runs(dpi=self._dpi), self._document.get_element_runs())) for start, end, (font, element) in \ runs.ranges(invalid_start, invalid_end): if element: self.glyphs[start] = _InlineElementBox(element) else: text = self.document.text[start:end] self.glyphs[start:end] = font.get_glyphs(text) # Update owner runs self._get_owner_runs( self.owner_runs, self.glyphs, invalid_start, invalid_end) # Updated glyphs need flowing self.invalid_flow.invalidate(invalid_start, invalid_end) def _update_flow_glyphs(self): invalid_start, invalid_end = self.invalid_flow.validate() if invalid_end - invalid_start <= 0: return # Find first invalid line line_index = 0 for i, line in enumerate(self.lines): if line.start >= invalid_start: break line_index = i # Flow from previous line; fixes issue with adding a space into # overlong line (glyphs before space would then flow back onto # previous line). TODO Could optimise this by keeping track of where # the overlong lines are. line_index = max(0, line_index - 1) # (No need to find last invalid line; the update loop below stops # calling the flow generator when no more changes are necessary.) try: line = self.lines[line_index] invalid_start = min(invalid_start, line.start) line.delete(self) line = self.lines[line_index] = _Line(invalid_start) self.invalid_lines.invalidate(line_index, line_index + 1) except IndexError: line_index = 0 invalid_start = 0 line = _Line(0) self.lines.append(line) self.invalid_lines.insert(0, 1) content_width_invalid = False next_start = invalid_start for line in self._flow_glyphs(self.glyphs, self.owner_runs, invalid_start, len(self._document.text)): try: old_line = self.lines[line_index] old_line.delete(self) old_line_width = old_line.width + old_line.margin_left new_line_width = line.width + line.margin_left if (old_line_width == self.content_width and new_line_width < old_line_width): content_width_invalid = True self.lines[line_index] = line self.invalid_lines.invalidate(line_index, line_index + 1) except IndexError: self.lines.append(line) self.invalid_lines.insert(line_index, 1) next_start = line.start + line.length line_index += 1 try: next_line = self.lines[line_index] if next_start == next_line.start and next_start > invalid_end: # No more lines need to be modified, early exit. break except IndexError: pass else: # The last line is at line_index - 1, if there are any more lines # after that they are stale and need to be deleted. if next_start == len(self._document.text) and line_index > 0: for line in self.lines[line_index:]: old_line_width = old_line.width + old_line.margin_left if old_line_width == self.content_width: content_width_invalid = True line.delete(self) del self.lines[line_index:] if content_width_invalid: # Rescan all lines to look for the new maximum content width content_width = 0 for line in self.lines: content_width = max(line.width + line.margin_left, content_width) self.content_width = content_width def _update_flow_lines(self): invalid_start, invalid_end = self.invalid_lines.validate() if invalid_end - invalid_start <= 0: return invalid_end = self._flow_lines(self.lines, invalid_start, invalid_end) # Invalidate lines that need new vertex lists. self.invalid_vertex_lines.invalidate(invalid_start, invalid_end) def _update_visible_lines(self): start = sys.maxint end = 0 for i, line in enumerate(self.lines): if line.y + line.descent < self.view_y: start = min(start, i) if line.y + line.ascent > self.view_y - self.height: end = max(end, i) + 1 # Delete newly invisible lines for i in range(self.visible_lines.start, min(start, len(self.lines))): self.lines[i].delete(self) for i in range(end, min(self.visible_lines.end, len(self.lines))): self.lines[i].delete(self) # Invalidate newly visible lines self.invalid_vertex_lines.invalidate(start, self.visible_lines.start) self.invalid_vertex_lines.invalidate(self.visible_lines.end, end) self.visible_lines.start = start self.visible_lines.end = end def _update_vertex_lists(self): # Find lines that have been affected by style changes style_invalid_start, style_invalid_end = self.invalid_style.validate() self.invalid_vertex_lines.invalidate( self.get_line_from_position(style_invalid_start), self.get_line_from_position(style_invalid_end) + 1) invalid_start, invalid_end = self.invalid_vertex_lines.validate() if invalid_end - invalid_start <= 0: return colors_iter = self.document.get_style_runs('color') background_iter = self.document.get_style_runs('background_color') if self._selection_end - self._selection_start > 0: colors_iter = runlist.OverriddenRunIterator( colors_iter, self._selection_start, self._selection_end, self._selection_color) background_iter = runlist.OverriddenRunIterator( background_iter, self._selection_start, self._selection_end, self._selection_background_color) context = _IncrementalLayoutContext(self, self._document, colors_iter, background_iter) for line in self.lines[invalid_start:invalid_end]: line.delete(self) context.line = line y = line.y # Early out if not visible if y + line.descent > self.view_y: continue elif y + line.ascent < self.view_y - self.height: break self._create_vertex_lists(line.x, y, line.start, line.boxes, context) # Invalidate everything when width changes def _set_width(self, width): if width == self._width: return self.invalid_flow.invalidate(0, len(self.document.text)) super(IncrementalTextLayout, self)._set_width(width) def _get_width(self): return self._width width = property(_get_width, _set_width) # Recalculate visible lines when height changes def _set_height(self, height): if height == self._height: return super(IncrementalTextLayout, self)._set_height(height) if self._update_enabled: self._update_visible_lines() self._update_vertex_lists() def _get_height(self): return self._height height = property(_get_height, _set_height) def _set_multiline(self, multiline): self.invalid_flow.invalidate(0, len(self.document.text)) super(IncrementalTextLayout, self)._set_multiline(multiline) def _get_multiline(self): return self._multiline multiline = property(_get_multiline, _set_multiline) # Invalidate invisible/visible lines when y scrolls def _set_view_y(self, view_y): # view_y must be negative. super(IncrementalTextLayout, self)._set_view_y(view_y) self._update_visible_lines() self._update_vertex_lists() def _get_view_y(self): return self.top_group.view_y view_y = property(_get_view_y, _set_view_y) # Visible selection def set_selection(self, start, end): '''Set the text selection range. If ``start`` equals ``end`` no selection will be visible. :Parameters: `start` : int Starting character position of selection. `end` : int End of selection, exclusive. ''' start = max(0, start) end = min(end, len(self.document.text)) if start == self._selection_start and end == self._selection_end: return if end > self._selection_start and start < self._selection_end: # Overlapping, only invalidate difference self.invalid_style.invalidate(min(start, self._selection_start), max(start, self._selection_start)) self.invalid_style.invalidate(min(end, self._selection_end), max(end, self._selection_end)) else: # Non-overlapping, invalidate both ranges self.invalid_style.invalidate(self._selection_start, self._selection_end) self.invalid_style.invalidate(start, end) self._selection_start = start self._selection_end = end self._update() selection_start = property( lambda self: self._selection_start, lambda self, v: self.set_selection(v, self._selection_end), doc='''Starting position of the active selection. :see: `set_selection` :type: int ''') selection_end = property( lambda self: self._selection_end, lambda self, v: self.set_selection(self._selection_start, v), doc='''End position of the active selection (exclusive). :see: `set_selection` :type: int ''') def _get_selection_color(self): return self._selection_color def _set_selection_color(self, color): self._selection_color = color self.invalid_style.invalidate(self._selection_start, self._selection_end) selection_color = property(_get_selection_color, _set_selection_color, doc='''Text color of active selection. The color is an RGBA tuple with components in range [0, 255]. :type: (int, int, int, int) ''') def _get_selection_background_color(self): return self._selection_background_color def _set_selection_background_color(self, background_color): self._selection_background_color = background_color self.invalid_style.invalidate(self._selection_start, self._selection_end) selection_background_color = property(_get_selection_background_color, _set_selection_background_color, doc='''Background color of active selection. The color is an RGBA tuple with components in range [0, 255]. :type: (int, int, int, int) ''') # Coordinate translation def get_position_from_point(self, x, y): '''Get the closest document position to a point. :Parameters: `x` : int X coordinate `y` : int Y coordinate ''' line = self.get_line_from_point(x, y) return self.get_position_on_line(line, x) def get_point_from_position(self, position, line=None): '''Get the X, Y coordinates of a position in the document. The position that ends a line has an ambiguous point: it can be either the end of the line, or the beginning of the next line. You may optionally specify a line index to disambiguate the case. The resulting Y coordinate gives the baseline of the line. :Parameters: `position` : int Character position within document. `line` : int Line index. :rtype: (int, int) :return: (x, y) ''' if line is None: line = self.lines[0] for next_line in self.lines: if next_line.start > position: break line = next_line else: line = self.lines[line] x = line.x baseline = self._document.get_style('baseline', max(0, position - 1)) if baseline is None: baseline = 0 else: baseline = self._parse_distance(baseline) position -= line.start for box in line.boxes: if position - box.length <= 0: x += box.get_point_in_box(position) break position -= box.length x += box.advance return (x + self.top_group.translate_x, line.y + self.top_group.translate_y + baseline) def get_line_from_point(self, x, y): '''Get the closest line index to a point. :Parameters: `x` : int X coordinate. `y` : int Y coordinate. :rtype: int ''' x -= self.top_group.translate_x y -= self.top_group.translate_y line_index = 0 for line in self.lines: if y > line.y + line.descent: break line_index += 1 if line_index >= len(self.lines): line_index = len(self.lines) - 1 return line_index def get_point_from_line(self, line): '''Get the X, Y coordinates of a line index. :Parameters: `line` : int Line index. :rtype: (int, int) :return: (x, y) ''' line = self.lines[line] return (line.x + self.top_group.translate_x, line.y + self.top_group.translate_y) def get_line_from_position(self, position): '''Get the line index of a character position in the document. :Parameters: `position` : int Document position. :rtype: int ''' line = -1 for next_line in self.lines: if next_line.start > position: break line += 1 return line def get_position_from_line(self, line): '''Get the first document character position of a given line index. :Parameters: `line` : int Line index. :rtype: int ''' return self.lines[line].start def get_position_on_line(self, line, x): '''Get the closest document position for a given line index and X coordinate. :Parameters: `line` : int Line index. `x` : int X coordinate. :rtype: int ''' line = self.lines[line] x -= self.top_group.translate_x position = line.start last_glyph_x = line.x for box in line.boxes: if 0 <= x - last_glyph_x < box.advance: position += box.get_position_in_box(x - last_glyph_x) break last_glyph_x += box.advance position += box.length return position def get_line_count(self): '''Get the number of lines in the text layout. :rtype: int ''' return len(self.lines) def ensure_line_visible(self, line): '''Adjust `view_y` so that the line with the given index is visible. :Parameters: `line` : int Line index. ''' line = self.lines[line] y1 = line.y + line.ascent y2 = line.y + line.descent if y1 > self.view_y: self.view_y = y1 elif y2 < self.view_y - self.height: self.view_y = y2 + self.height def ensure_x_visible(self, x): '''Adjust `view_x` so that the given X coordinate is visible. The X coordinate is given relative to the current `view_x`. :Parameters: `x` : int X coordinate ''' if x <= self.view_x + 10: self.view_x = x - 10 elif x >= self.view_x + self.width: self.view_x = x - self.width + 10 elif (x >= self.view_x + self.width - 10 and self.content_width > self.width): self.view_x = x - self.width + 10 if _is_epydoc: def on_layout_update(self): '''Some or all of the layout text was reflowed. Text reflow is caused by document edits or changes to the layout's size. Changes to the layout's position or active selection, and certain document edits such as text color, do not cause a reflow. Handle this event to update the position of a graphical element that depends on the laid out position of a glyph or line. :event: ''' IncrementalTextLayout.register_event_type('on_layout_update')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id: $ '''Text formatting, layout and display. This module provides classes for loading styled documents from text files, HTML files and a pyglet-specific markup format. Documents can be styled with multiple fonts, colours, styles, text sizes, margins, paragraph alignments, and so on. Using the layout classes, documents can be laid out on a single line or word-wrapped to fit a rectangle. A layout can then be efficiently drawn in a window or updated incrementally (for example, to support interactive text editing). The label classes provide a simple interface for the common case where an application simply needs to display some text in a window. A plain text label can be created with:: label = pyglet.text.Label('Hello, world', font_name='Times New Roman', font_size=36, x=10, y=10) Alternatively, a styled text label using HTML can be created with:: label = pyglet.text.HTMLLabel('<b>Hello</b>, <i>world</i>', x=10, y=10) Either label can then be drawn at any time with:: label.draw() For details on the subset of HTML supported, see `pyglet.text.formats.html`. Refer to the Programming Guide for advanced usage of the document and layout classes, including interactive editing, embedding objects within documents and creating scrollable layouts. :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import os.path import pyglet from pyglet.text import layout, document, caret class DocumentDecodeException(Exception): '''An error occurred decoding document text.''' pass class DocumentDecoder(object): '''Abstract document decoder. ''' def decode(self, text, location=None): '''Decode document text. :Parameters: `text` : str Text to decode `location` : `Location` Location to use as base path for additional resources referenced within the document (for example, HTML images). :rtype: `AbstractDocument` ''' raise NotImplementedError('abstract') def get_decoder(filename, mimetype=None): '''Get a document decoder for the given filename and MIME type. If `mimetype` is omitted it is guessed from the filename extension. The following MIME types are supported: ``text/plain`` Plain text ``text/html`` HTML 4 Transitional ``text/vnd.pyglet-attributed`` Attributed text; see `pyglet.text.formats.attributed` `DocumentDecodeException` is raised if another MIME type is given. :Parameters: `filename` : str Filename to guess the MIME type from. If a MIME type is given, the filename is ignored. `mimetype` : str MIME type to lookup, or ``None`` to guess the type from the filename. :rtype: `DocumentDecoder` ''' if mimetype is None: _, ext = os.path.splitext(filename) if ext.lower() in ('.htm', '.html', '.xhtml'): mimetype = 'text/html' else: mimetype = 'text/plain' if mimetype == 'text/plain': from pyglet.text.formats import plaintext return plaintext.PlainTextDecoder() elif mimetype == 'text/html': from pyglet.text.formats import html return html.HTMLDecoder() elif mimetype == 'text/vnd.pyglet-attributed': from pyglet.text.formats import attributed return attributed.AttributedTextDecoder() else: raise DocumentDecodeException('Unknown format "%s"' % mimetype) def load(filename, file=None, mimetype=None): '''Load a document from a file. :Parameters: `filename` : str Filename of document to load. `file` : file-like object File object containing encoded data. If omitted, `filename` is loaded from disk. `mimetype` : str MIME type of the document. If omitted, the filename extension is used to guess a MIME type. See `get_decoder` for a list of supported MIME types. :rtype: `AbstractDocument` ''' decoder = get_decoder(filename, mimetype) if file is None: file = open(filename) location = pyglet.resource.FileLocation(os.path.dirname(filename)) return decoder.decode(file.read(), location) def decode_html(text, location=None): '''Create a document directly from some HTML formatted text. :Parameters: `text` : str HTML data to decode. `location` : str Location giving the base path for additional resources referenced from the document (e.g., images). :rtype: `FormattedDocument` ''' decoder = get_decoder(None, 'text/html') return decoder.decode(text, location) def decode_attributed(text): '''Create a document directly from some attributed text. See `pyglet.text.formats.attributed` for a description of attributed text. :Parameters: `text` : str Attributed text to decode. :rtype: `FormattedDocument` ''' decoder = get_decoder(None, 'text/vnd.pyglet-attributed') return decoder.decode(text) def decode_text(text): '''Create a document directly from some plain text. :Parameters: `text` : str Plain text to initialise the document with. :rtype: `UnformattedDocument` ''' decoder = get_decoder(None, 'text/plain') return decoder.decode(text) class DocumentLabel(layout.TextLayout): '''Base label class. A label is a layout that exposes convenience methods for manipulating the associated document. ''' def __init__(self, document=None, x=0, y=0, width=None, height=None, anchor_x='left', anchor_y='baseline', multiline=False, dpi=None, batch=None, group=None): '''Create a label for a given document. :Parameters: `document` : `AbstractDocument` Document to attach to the layout. `x` : int X coordinate of the label. `y` : int Y coordinate of the label. `width` : int Width of the label in pixels, or None `height` : int Height of the label in pixels, or None `anchor_x` : str Anchor point of the X coordinate: one of ``"left"``, ``"center"`` or ``"right"``. `anchor_y` : str Anchor point of the Y coordinate: one of ``"bottom"``, ``"baseline"``, ``"center"`` or ``"top"``. `multiline` : bool If True, the label will be word-wrapped and accept newline characters. You must also set the width of the label. `dpi` : float Resolution of the fonts in this layout. Defaults to 96. `batch` : `Batch` Optional graphics batch to add the label to. `group` : `Group` Optional graphics group to use. ''' super(DocumentLabel, self).__init__(document, width=width, height=height, multiline=multiline, dpi=dpi, batch=batch, group=group) self._x = x self._y = y self._anchor_x = anchor_x self._anchor_y = anchor_y self._update() def _get_text(self): return self.document.text def _set_text(self, text): self.document.text = text text = property(_get_text, _set_text, doc='''The text of the label. :type: str ''') def _get_color(self): return self.document.get_style('color') def _set_color(self, color): self.document.set_style(0, len(self.document.text), {'color': color}) color = property(_get_color, _set_color, doc='''Text color. Color is a 4-tuple of RGBA components, each in range [0, 255]. :type: (int, int, int, int) ''') def _get_font_name(self): return self.document.get_style('font_name') def _set_font_name(self, font_name): self.document.set_style(0, len(self.document.text), {'font_name': font_name}) font_name = property(_get_font_name, _set_font_name, doc='''Font family name. The font name, as passed to `pyglet.font.load`. A list of names can optionally be given: the first matching font will be used. :type: str or list ''') def _get_font_size(self): return self.document.get_style('font_size') def _set_font_size(self, font_size): self.document.set_style(0, len(self.document.text), {'font_size': font_size}) font_size = property(_get_font_size, _set_font_size, doc='''Font size, in points. :type: float ''') def _get_bold(self): return self.document.get_style('bold') def _set_bold(self, bold): self.document.set_style(0, len(self.document.text), {'bold': bold}) bold = property(_get_bold, _set_bold, doc='''Bold font style. :type: bool ''') def _get_italic(self): return self.document.get_style('italic') def _set_italic(self, italic): self.document.set_style(0, len(self.document.text), {'italic': italic}) italic = property(_get_italic, _set_italic, doc='''Italic font style. :type: bool ''') def get_style(self, name): '''Get a document style value by name. If the document has more than one value of the named style, `pyglet.text.document.STYLE_INDETERMINATE` is returned. :Parameters: `name` : str Style name to query. See documentation for `pyglet.text.layout` for known style names. :rtype: object ''' return self.document.get_style_range(name, 0, len(self.document.text)) def set_style(self, name, value): '''Set a document style value by name over the whole document. :Parameters: `name` : str Name of the style to set. See documentation for `pyglet.text.layout` for known style names. `value` : object Value of the style. ''' self.document.set_style(0, len(self.document.text), {name: value}) class Label(DocumentLabel): '''Plain text label. ''' def __init__(self, text='', font_name=None, font_size=None, bold=False, italic=False, color=(255, 255, 255, 255), x=0, y=0, width=None, height=None, anchor_x='left', anchor_y='baseline', align='left', multiline=False, dpi=None, batch=None, group=None): '''Create a plain text label. :Parameters: `text` : str Text to display. `font_name` : str or list Font family name(s). If more than one name is given, the first matching name is used. `font_size` : float Font size, in points. `bold` : bool Bold font style. `italic` : bool Italic font style. `color` : (int, int, int, int) Font colour, as RGBA components in range [0, 255]. `x` : int X coordinate of the label. `y` : int Y coordinate of the label. `width` : int Width of the label in pixels, or None `height` : int Height of the label in pixels, or None `anchor_x` : str Anchor point of the X coordinate: one of ``"left"``, ``"center"`` or ``"right"``. `anchor_y` : str Anchor point of the Y coordinate: one of ``"bottom"``, ``"baseline"``, ``"center"`` or ``"top"``. `align` : str Horizontal alignment of text on a line, only applies if a width is supplied. One of ``"left"``, ``"center"`` or ``"right"``. `multiline` : bool If True, the label will be word-wrapped and accept newline characters. You must also set the width of the label. `dpi` : float Resolution of the fonts in this layout. Defaults to 96. `batch` : `Batch` Optional graphics batch to add the label to. `group` : `Group` Optional graphics group to use. ''' document = decode_text(text) super(Label, self).__init__(document, x, y, width, height, anchor_x, anchor_y, multiline, dpi, batch, group) self.document.set_style(0, len(self.document.text), { 'font_name': font_name, 'font_size': font_size, 'bold': bold, 'italic': italic, 'color': color, 'align': align, }) class HTMLLabel(DocumentLabel): '''HTML formatted text label. A subset of HTML 4.01 is supported. See `pyglet.text.formats.html` for details. ''' def __init__(self, text='', location=None, x=0, y=0, width=None, height=None, anchor_x='left', anchor_y='baseline', multiline=False, dpi=None, batch=None, group=None): '''Create a label with an HTML string. :Parameters: `text` : str HTML formatted text to display. `location` : `Location` Location object for loading images referred to in the document. By default, the working directory is used. `x` : int X coordinate of the label. `y` : int Y coordinate of the label. `width` : int Width of the label in pixels, or None `height` : int Height of the label in pixels, or None `anchor_x` : str Anchor point of the X coordinate: one of ``"left"``, ``"center"`` or ``"right"``. `anchor_y` : str Anchor point of the Y coordinate: one of ``"bottom"``, ``"baseline"``, ``"center"`` or ``"top"``. `multiline` : bool If True, the label will be word-wrapped and render paragraph and line breaks. You must also set the width of the label. `dpi` : float Resolution of the fonts in this layout. Defaults to 96. `batch` : `Batch` Optional graphics batch to add the label to. `group` : `Group` Optional graphics group to use. ''' self._text = text self._location = location document = decode_html(text, location) super(HTMLLabel, self).__init__(document, x, y, width, height, anchor_x, anchor_y, multiline, dpi, batch, group) def _set_text(self, text): self._text = text self.document = decode_html(text, self._location) def _get_text(self): return self._text text = property(_get_text, _set_text, doc='''HTML formatted text of the label. :type: str ''')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Run list encoding utilities. :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' class _Run(object): def __init__(self, value, count): self.value = value self.count = count def __repr__(self): return 'Run(%r, %d)' % (self.value, self.count) class RunList(object): '''List of contiguous runs of values. A `RunList` is an efficient encoding of a sequence of values. For example, the sequence ``aaaabbccccc`` is encoded as ``(4, a), (2, b), (5, c)``. The class provides methods for modifying and querying the run list without needing to deal with the tricky cases of splitting and merging the run list entries. Run lists are used to represent formatted character data in pyglet. A separate run list is maintained for each style attribute, for example, bold, italic, font size, and so on. Unless you are overriding the document interfaces, the only interaction with run lists is via `RunIterator`. The length and ranges of a run list always refer to the character positions in the decoded list. For example, in the above sequence, ``set_run(2, 5, 'x')`` would change the sequence to ``aaxxxbccccc``. ''' def __init__(self, size, initial): '''Create a run list of the given size and a default value. :Parameters: `size` : int Number of characters to represent initially. `initial` : object The value of all characters in the run list. ''' self.runs = [_Run(initial, size)] def insert(self, pos, length): '''Insert characters into the run list. The inserted characters will take on the value immediately preceding the insertion point (or the value of the first character, if `pos` is 0). :Parameters: `pos` : int Insertion index `length` : int Number of characters to insert. ''' i = 0 for run in self.runs: if i <= pos <= i + run.count: run.count += length i += run.count def delete(self, start, end): '''Remove characters from the run list. :Parameters: `start` : int Starting index to remove from. `end` : int End index, exclusive. ''' i = 0 for run in self.runs: if end - start == 0: break if i <= start <= i + run.count: trim = min(end - start, i + run.count - start) run.count -= trim end -= trim i += run.count self.runs = [r for r in self.runs if r.count > 0] # Don't leave an empty list if not self.runs: self.runs = [_Run(run.value, 0)] def set_run(self, start, end, value): '''Set the value of a range of characters. :Parameters: `start` : int Start index of range. `end` : int End of range, exclusive. `value` : object Value to set over the range. ''' if end - start <= 0: return # Find runs that need to be split i = 0 start_i = None start_trim = 0 end_i = None end_trim = 0 for run_i, run in enumerate(self.runs): count = run.count if i < start < i + count: start_i = run_i start_trim = start - i if i < end < i + count: end_i = run_i end_trim = end - i i += count # Split runs if start_i is not None: run = self.runs[start_i] self.runs.insert(start_i, _Run(run.value, start_trim)) run.count -= start_trim if end_i is not None: if end_i == start_i: end_trim -= start_trim end_i += 1 if end_i is not None: run = self.runs[end_i] self.runs.insert(end_i, _Run(run.value, end_trim)) run.count -= end_trim # Set new value on runs i = 0 for run in self.runs: if start <= i and i + run.count <= end: run.value = value i += run.count # Merge adjacent runs last_run = self.runs[0] for run in self.runs[1:]: if run.value == last_run.value: run.count += last_run.count last_run.count = 0 last_run = run # Delete collapsed runs self.runs = [r for r in self.runs if r.count > 0] def __iter__(self): i = 0 for run in self.runs: yield i, i + run.count, run.value i += run.count def get_run_iterator(self): '''Get an extended iterator over the run list. :rtype: `RunIterator` ''' return RunIterator(self) def __getitem__(self, index): '''Get the value at a character position. :Parameters: `index` : int Index of character. Must be within range and non-negative. :rtype: object ''' i = 0 for run in self.runs: if i <= index < i + run.count: return run.value i += run.count # Append insertion point if index == i: return self.runs[-1].value assert False, 'Index not in range' def __repr__(self): return str(list(self)) class AbstractRunIterator(object): '''Range iteration over `RunList`. `AbstractRunIterator` objects allow any monotonically non-decreasing access of the iteration, including repeated iteration over the same index. Use the ``[index]`` operator to get the value at a particular index within the document. For example:: run_iter = iter(run_list) value = run_iter[0] value = run_iter[0] # non-decreasing access is OK value = run_iter[15] value = run_iter[17] value = run_iter[16] # this is illegal, the index decreased. Using `AbstractRunIterator` to access increasing indices of the value runs is more efficient than calling `RunList.__getitem__` repeatedly. You can also iterate over monotonically non-decreasing ranges over the iteration. For example:: run_iter = iter(run_list) for start, end, value in run_iter.ranges(0, 20): pass for start, end, value in run_iter.ranges(25, 30): pass for start, end, value in run_iter.ranges(30, 40): pass Both start and end indices of the slice are required and must be positive. ''' def __getitem__(self, index): '''Get the value at a given index. See the class documentation for examples of valid usage. :Parameters: `index` : int Document position to query. :rtype: object ''' def ranges(self, start, end): '''Iterate over a subrange of the run list. See the class documentation for examples of valid usage. :Parameters: `start` : int Start index to iterate from. `end` : int End index, exclusive. :rtype: iterator :return: Iterator over (start, end, value) tuples. ''' class RunIterator(AbstractRunIterator): def __init__(self, run_list): self._run_list_iter = iter(run_list) self.start, self.end, self.value = self.next() def next(self): return self._run_list_iter.next() def __getitem__(self, index): while index >= self.end and index > self.start: # condition has special case for 0-length run (fixes issue 471) self.start, self.end, self.value = self.next() return self.value def ranges(self, start, end): while start >= self.end: self.start, self.end, self.value = self.next() yield start, min(self.end, end), self.value while end > self.end: self.start, self.end, self.value = self.next() yield self.start, min(self.end, end), self.value class OverriddenRunIterator(AbstractRunIterator): '''Iterator over a `RunIterator`, with a value temporarily replacing a given range. ''' def __init__(self, base_iterator, start, end, value): '''Create a derived iterator. :Parameters: `start` : int Start of range to override `end` : int End of range to override, exclusive `value` : object Value to replace over the range ''' self.iter = base_iterator self.override_start = start self.override_end = end self.override_value = value def ranges(self, start, end): if end <= self.override_start or start >= self.override_end: # No overlap for r in self.iter.ranges(start, end): yield r else: # Overlap: before, override, after if start < self.override_start < end: for r in self.iter.ranges(start, self.override_start): yield r yield (max(self.override_start, start), min(self.override_end, end), self.override_value) if start < self.override_end < end: for r in self.iter.ranges(self.override_end, end): yield r def __getitem__(self, index): if self.override_start <= index < self.override_end: return self.override_value else: return self.iter[index] class FilteredRunIterator(AbstractRunIterator): '''Iterate over an `AbstractRunIterator` with filtered values replaced by a default value. ''' def __init__(self, base_iterator, filter, default): '''Create a filtered run iterator. :Parameters: `base_iterator` : `AbstractRunIterator` Source of runs. `filter` : ``lambda object: bool`` Function taking a value as parameter, and returning ``True`` if the value is acceptable, and ``False`` if the default value should be substituted. `default` : object Default value to replace filtered values. ''' self.iter = base_iterator self.filter = filter self.default = default def ranges(self, start, end): for start, end, value in self.iter.ranges(start, end): if self.filter(value): yield start, end, value else: yield start, end, self.default def __getitem__(self, index): value = self.iter[index] if self.filter(value): return value return self.default class ZipRunIterator(AbstractRunIterator): '''Iterate over multiple run iterators concurrently.''' def __init__(self, range_iterators): self.range_iterators = range_iterators def ranges(self, start, end): iterators = [i.ranges(start, end) for i in self.range_iterators] starts, ends, values = zip(*[i.next() for i in iterators]) starts = list(starts) ends = list(ends) values = list(values) while start < end: min_end = min(ends) yield start, min_end, values start = min_end for i, iterator in enumerate(iterators): if ends[i] == min_end: starts[i], ends[i], values[i] = iterator.next() def __getitem__(self, index): return [i[index] for i in self.range_iterators] class ConstRunIterator(AbstractRunIterator): '''Iterate over a constant value without creating a RunList.''' def __init__(self, length, value): self.length = length self.value = value def next(self): yield 0, self.length, self.value def ranges(self, start, end): yield start, end, self.value def __getitem__(self, index): return self.value
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ '''Provides keyboard and mouse editing procedures for text layout. Example usage:: from pyglet import window from pyglet.text import layout, caret my_window = window.Window(...) my_layout = layout.IncrementalTextLayout(...) my_caret = caret.Caret(my_layout) my_window.push_handlers(my_caret) :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import re import time from pyglet import clock from pyglet import event from pyglet.window import key class Caret(object): '''Visible text insertion marker for `pyglet.text.layout.IncrementalTextLayout`. The caret is drawn as a single vertical bar at the document `position` on a text layout object. If `mark` is not None, it gives the unmoving end of the current text selection. The visible text selection on the layout is updated along with `mark` and `position`. By default the layout's graphics batch is used, so the caret does not need to be drawn explicitly. Even if a different graphics batch is supplied, the caret will be correctly positioned and clipped within the layout. Updates to the document (and so the layout) are automatically propagated to the caret. The caret object can be pushed onto a window event handler stack with `Window.push_handlers`. The caret will respond correctly to keyboard, text, mouse and activation events, including double- and triple-clicks. If the text layout is being used alongside other graphical widgets, a GUI toolkit will be needed to delegate keyboard and mouse events to the appropriate widget. pyglet does not provide such a toolkit at this stage. ''' _next_word_re = re.compile(r'(?<=\W)\w') _previous_word_re = re.compile(r'(?<=\W)\w+\W*$') _next_para_re = re.compile(r'\n', flags=re.DOTALL) _previous_para_re = re.compile(r'\n', flags=re.DOTALL) _position = 0 _active = True _visible = True _blink_visible = True _click_count = 0 _click_time = 0 #: Blink period, in seconds. PERIOD = 0.5 #: Pixels to scroll viewport per mouse scroll wheel movement. Defaults #: to 12pt at 96dpi. SCROLL_INCREMENT= 12 * 96 // 72 def __init__(self, layout, batch=None, color=(0, 0, 0)): '''Create a caret for a layout. By default the layout's batch is used, so the caret does not need to be drawn explicitly. :Parameters: `layout` : `TextLayout` Layout to control. `batch` : `Batch` Graphics batch to add vertices to. `color` : (int, int, int) RGB tuple with components in range [0, 255]. ''' from pyglet import gl self._layout = layout if batch is None: batch = layout.batch r, g, b = color colors = (r, g, b, 255, r, g, b, 255) self._list = batch.add(2, gl.GL_LINES, layout.background_group, 'v2f', ('c4B', colors)) self._ideal_x = None self._ideal_line = None self._next_attributes = {} self.visible = True layout.push_handlers(self) def delete(self): '''Remove the caret from its batch. Also disconnects the caret from further layout events. ''' self._list.delete() self._layout.remove_handlers(self) def _blink(self, dt): if self.PERIOD: self._blink_visible = not self._blink_visible if self._visible and self._active and self._blink_visible: alpha = 255 else: alpha = 0 self._list.colors[3] = alpha self._list.colors[7] = alpha def _nudge(self): self.visible = True def _set_visible(self, visible): self._visible = visible clock.unschedule(self._blink) if visible and self._active and self.PERIOD: clock.schedule_interval(self._blink, self.PERIOD) self._blink_visible = False # flipped immediately by next blink self._blink(0) def _get_visible(self): return self._visible visible = property(_get_visible, _set_visible, doc='''Caret visibility. The caret may be hidden despite this property due to the periodic blinking or by `on_deactivate` if the event handler is attached to a window. :type: bool ''') def _set_color(self, color): self._list.colors[:3] = color self._list.colors[4:7] = color def _get_color(self): return self._list.colors[:3] color = property(_get_color, _set_color, doc='''Caret color. The default caret color is ``[0, 0, 0]`` (black). Each RGB color component is in the range 0 to 255. :type: (int, int, int) ''') def _set_position(self, index): self._position = index self._next_attributes.clear() self._update() def _get_position(self): return self._position position = property(_get_position, _set_position, doc='''Position of caret within document. :type: int ''') _mark = None def _set_mark(self, mark): self._mark = mark self._update(line=self._ideal_line) if mark is None: self._layout.set_selection(0, 0) def _get_mark(self): return self._mark mark = property(_get_mark, _set_mark, doc='''Position of immovable end of text selection within document. An interactive text selection is determined by its immovable end (the caret's position when a mouse drag begins) and the caret's position, which moves interactively by mouse and keyboard input. This property is ``None`` when there is no selection. :type: int ''') def _set_line(self, line): if self._ideal_x is None: self._ideal_x, _ = \ self._layout.get_point_from_position(self._position) self._position = \ self._layout.get_position_on_line(line, self._ideal_x) self._update(line=line, update_ideal_x=False) def _get_line(self): if self._ideal_line is not None: return self._ideal_line else: return self._layout.get_line_from_position(self._position) line = property(_get_line, _set_line, doc='''Index of line containing the caret's position. When set, `position` is modified to place the caret on requested line while maintaining the closest possible X offset. :type: int ''') def get_style(self, attribute): '''Get the document's named style at the caret's current position. If there is a text selection and the style varies over the selection, `pyglet.text.document.STYLE_INDETERMINATE` is returned. :Parameters: `attribute` : str Name of style attribute to retrieve. See `pyglet.text.document` for a list of recognised attribute names. :rtype: object ''' if self._mark is None or self._mark == self._position: try: return self._next_attributes[attribute] except KeyError: return self._layout.document.get_style(attribute, self._position) start = min(self._position, self._mark) end = max(self._position, self._mark) return self._layout.document.get_style_range(attribute, start, end) def set_style(self, attributes): '''Set the document style at the caret's current position. If there is a text selection the style is modified immediately. Otherwise, the next text that is entered before the position is modified will take on the given style. :Parameters: `attributes` : dict Dict mapping attribute names to style values. See `pyglet.text.document` for a list of recognised attribute names. ''' if self._mark is None or self._mark == self._position: self._next_attributes.update(attributes) return start = min(self._position, self._mark) end = max(self._position, self._mark) self._layout.document.set_style(start, end, attributes) def _delete_selection(self): start = min(self._mark, self._position) end = max(self._mark, self._position) self._position = start self._mark = None self._layout.document.delete_text(start, end) self._layout.set_selection(0, 0) def move_to_point(self, x, y): '''Move the caret close to the given window coordinate. The `mark` will be reset to ``None``. :Parameters: `x` : int X coordinate. `y` : int Y coordinate. ''' line = self._layout.get_line_from_point(x, y) self._mark = None self._layout.set_selection(0, 0) self._position = self._layout.get_position_on_line(line, x) self._update(line=line) self._next_attributes.clear() def select_to_point(self, x, y): '''Move the caret close to the given window coordinate while maintaining the `mark`. :Parameters: `x` : int X coordinate. `y` : int Y coordinate. ''' line = self._layout.get_line_from_point(x, y) self._position = self._layout.get_position_on_line(line, x) self._update(line=line) self._next_attributes.clear() def select_word(self, x, y): '''Select the word at the given window coordinate. :Parameters: `x` : int X coordinate. `y` : int Y coordinate. ''' line = self._layout.get_line_from_point(x, y) p = self._layout.get_position_on_line(line, x) m1 = self._previous_word_re.search(self._layout.document.text, 0, p+1) if not m1: m1 = 0 else: m1 = m1.start() self.mark = m1 m2 = self._next_word_re.search(self._layout.document.text, p) if not m2: m2 = len(self._layout.document.text) else: m2 = m2.start() self._position = m2 self._update(line=line) self._next_attributes.clear() def select_paragraph(self, x, y): '''Select the paragraph at the given window coordinate. :Parameters: `x` : int X coordinate. `y` : int Y coordinate. ''' line = self._layout.get_line_from_point(x, y) p = self._layout.get_position_on_line(line, x) self.mark = self._layout.document.get_paragraph_start(p) self._position = self._layout.document.get_paragraph_end(p) self._update(line=line) self._next_attributes.clear() def _update(self, line=None, update_ideal_x=True): if line is None: line = self._layout.get_line_from_position(self._position) self._ideal_line = None else: self._ideal_line = line x, y = self._layout.get_point_from_position(self._position, line) if update_ideal_x: self._ideal_x = x x -= self._layout.top_group.translate_x y -= self._layout.top_group.translate_y font = self._layout.document.get_font(max(0, self._position - 1)) self._list.vertices[:] = [x, y + font.descent, x, y + font.ascent] if self._mark is not None: self._layout.set_selection(min(self._position, self._mark), max(self._position, self._mark)) self._layout.ensure_line_visible(line) self._layout.ensure_x_visible(x) def on_layout_update(self): if self.position > len(self._layout.document.text): self.position = len(self._layout.document.text) self._update() def on_text(self, text): '''Handler for the `pyglet.window.Window.on_text` event. Caret keyboard handlers assume the layout always has keyboard focus. GUI toolkits should filter keyboard and text events by widget focus before invoking this handler. ''' if self._mark is not None: self._delete_selection() text = text.replace('\r', '\n') pos = self._position self._position += len(text) self._layout.document.insert_text(pos, text, self._next_attributes) self._nudge() return event.EVENT_HANDLED def on_text_motion(self, motion, select=False): '''Handler for the `pyglet.window.Window.on_text_motion` event. Caret keyboard handlers assume the layout always has keyboard focus. GUI toolkits should filter keyboard and text events by widget focus before invoking this handler. ''' if motion == key.MOTION_BACKSPACE: if self.mark is not None: self._delete_selection() elif self._position > 0: self._position -= 1 self._layout.document.delete_text( self._position, self._position + 1) elif motion == key.MOTION_DELETE: if self.mark is not None: self._delete_selection() elif self._position < len(self._layout.document.text): self._layout.document.delete_text( self._position, self._position + 1) elif self._mark is not None and not select: self._mark = None self._layout.set_selection(0, 0) if motion == key.MOTION_LEFT: self.position = max(0, self.position - 1) elif motion == key.MOTION_RIGHT: self.position = min(len(self._layout.document.text), self.position + 1) elif motion == key.MOTION_UP: self.line = max(0, self.line - 1) elif motion == key.MOTION_DOWN: line = self.line if line < self._layout.get_line_count() - 1: self.line = line + 1 elif motion == key.MOTION_BEGINNING_OF_LINE: self.position = self._layout.get_position_from_line(self.line) elif motion == key.MOTION_END_OF_LINE: line = self.line if line < self._layout.get_line_count() - 1: self._position = \ self._layout.get_position_from_line(line + 1) - 1 self._update(line) else: self.position = len(self._layout.document.text) elif motion == key.MOTION_BEGINNING_OF_FILE: self.position = 0 elif motion == key.MOTION_END_OF_FILE: self.position = len(self._layout.document.text) elif motion == key.MOTION_NEXT_WORD: pos = self._position + 1 m = self._next_word_re.search(self._layout.document.text, pos) if not m: self.position = len(self._layout.document.text) else: self.position = m.start() elif motion == key.MOTION_PREVIOUS_WORD: pos = self._position m = self._previous_word_re.search(self._layout.document.text, 0, pos) if not m: self.position = 0 else: self.position = m.start() self._next_attributes.clear() self._nudge() return event.EVENT_HANDLED def on_text_motion_select(self, motion): '''Handler for the `pyglet.window.Window.on_text_motion_select` event. Caret keyboard handlers assume the layout always has keyboard focus. GUI toolkits should filter keyboard and text events by widget focus before invoking this handler. ''' if self.mark is None: self.mark = self.position self.on_text_motion(motion, True) return event.EVENT_HANDLED def on_mouse_scroll(self, x, y, scroll_x, scroll_y): '''Handler for the `pyglet.window.Window.on_mouse_scroll` event. Mouse handlers do not check the bounds of the coordinates: GUI toolkits should filter events that do not intersect the layout before invoking this handler. The layout viewport is scrolled by `SCROLL_INCREMENT` pixels per "click". ''' self._layout.view_x -= scroll_x * self.SCROLL_INCREMENT self._layout.view_y += scroll_y * self.SCROLL_INCREMENT return event.EVENT_HANDLED def on_mouse_press(self, x, y, button, modifiers): '''Handler for the `pyglet.window.Window.on_mouse_press` event. Mouse handlers do not check the bounds of the coordinates: GUI toolkits should filter events that do not intersect the layout before invoking this handler. This handler keeps track of the number of mouse presses within a short span of time and uses this to reconstruct double- and triple-click events for selecting words and paragraphs. This technique is not suitable when a GUI toolkit is in use, as the active widget must also be tracked. Do not use this mouse handler if a GUI toolkit is being used. ''' t = time.time() if t - self._click_time < 0.25: self._click_count += 1 else: self._click_count = 1 self._click_time = time.time() if self._click_count == 1: self.move_to_point(x, y) elif self._click_count == 2: self.select_word(x, y) elif self._click_count == 3: self.select_paragraph(x, y) self._click_count = 0 self._nudge() return event.EVENT_HANDLED def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): '''Handler for the `pyglet.window.Window.on_mouse_drag` event. Mouse handlers do not check the bounds of the coordinates: GUI toolkits should filter events that do not intersect the layout before invoking this handler. ''' if self.mark is None: self.mark = self.position self.select_to_point(x, y) self._nudge() return event.EVENT_HANDLED def on_activate(self): '''Handler for the `pyglet.window.Window.on_activate` event. The caret is hidden when the window is not active. ''' self._active = True self.visible = self._active return event.EVENT_HANDLED def on_deactivate(self): '''Handler for the `pyglet.window.Window.on_deactivate` event. The caret is hidden when the window is not active. ''' self._active = False self.visible = self._active return event.EVENT_HANDLED
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ '''Formatted and unformatted document interfaces used by text layout. Abstract representation ======================= Styled text in pyglet is represented by one of the `AbstractDocument` classes, which manage the state representation of text and style independently of how it is loaded or rendered. A document consists of the document text (a Unicode string) and a set of named style ranges. For example, consider the following (artificial) example:: 0 5 10 15 20 The cat sat on the mat. +++++++ +++++++ "bold" ++++++ "italic" If this example were to be rendered, "The cat" and "the mat" would be in bold, and "on the" in italics. Note that the second "the" is both bold and italic. The document styles recorded for this example would be ``"bold"`` over ranges (0-7, 15-22) and ``"italic"`` over range (12-18). Overlapping styles are permitted; unlike HTML and other structured markup, the ranges need not be nested. The document has no knowledge of the semantics of ``"bold"`` or ``"italic"``, it stores only the style names. The pyglet layout classes give meaning to these style names in the way they are rendered; but you are also free to invent your own style names (which will be ignored by the layout classes). This can be useful to tag areas of interest in a document, or maintain references back to the source material. As well as text, the document can contain arbitrary elements represented by `InlineElement`. An inline element behaves like a single character in the documented, but can be rendered by the application. Paragraph breaks ================ Paragraph breaks are marked with a "newline" character (U+0010). The Unicode paragraph break (U+2029) can also be used. Line breaks (U+2028) can be used to force a line break within a paragraph. See Unicode recommendation UTR #13 for more information: http://unicode.org/reports/tr13/tr13-5.html. Document classes ================ Any class implementing `AbstractDocument` provides an interface to a document model as described above. In theory a structured document such as HTML or XML could export this model, though the classes provided by pyglet implement only unstructured documents. The `UnformattedDocument` class assumes any styles set are set over the entire document. So, regardless of the range specified when setting a ``"bold"`` style attribute, for example, the entire document will receive that style. The `FormattedDocument` class implements the document model directly, using the `RunList` class to represent style runs efficiently. Style attributes ================ The following character style attribute names are recognised by pyglet: ``font_name`` Font family name, as given to `pyglet.font.load`. ``font_size`` Font size, in points. ``bold`` Boolean. ``italic`` Boolean. ``underline`` 4-tuple of ints in range (0, 255) giving RGBA underline color, or None (default) for no underline. ``kerning`` Additional space to insert between glyphs, in points. Defaults to 0. ``baseline`` Offset of glyph baseline from line baseline, in points. Positive values give a superscript, negative values give a subscript. Defaults to 0. ``color`` 4-tuple of ints in range (0, 255) giving RGBA text color ``background_color`` 4-tuple of ints in range (0, 255) giving RGBA text background color; or ``None`` for no background fill. The following paragraph style attribute names are recognised by pyglet. Note that paragraph styles are handled no differently from character styles by the document: it is the application's responsibility to set the style over an entire paragraph, otherwise results are undefined. ``align`` ``left`` (default), ``center`` or ``right``. ``indent`` Additional horizontal space to insert before the first ``leading`` Additional space to insert between consecutive lines within a paragraph, in points. Defaults to 0. ``line_spacing`` Distance between consecutive baselines in a paragraph, in points. Defaults to ``None``, which automatically calculates the tightest line spacing for each line based on the font ascent and descent. ``margin_left`` Left paragraph margin, in pixels. ``margin_right`` Right paragraph margin, in pixels. ``margin_top`` Margin above paragraph, in pixels. ``margin_bottom`` Margin below paragraph, in pixels. Adjacent margins do not collapse. ``tab_stops`` List of horizontal tab stops, in pixels, measured from the left edge of the text layout. Defaults to the empty list. When the tab stops are exhausted, they implicitly continue at 50 pixel intervals. ``wrap`` Boolean. If True (the default), text wraps within the width of the layout. Other attributes can be used to store additional style information within the document; it will be ignored by the built-in text classes. All style attributes (including those not present in a document) default to ``None`` (including the so-called "boolean" styles listed above). The meaning of a ``None`` style is style- and application-dependent. :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import re import sys from pyglet import event from pyglet.text import runlist _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc #: The style attribute takes on multiple values in the document. STYLE_INDETERMINATE = 'indeterminate' class InlineElement(object): '''Arbitrary inline element positioned within a formatted document. Elements behave like a single glyph in the document. They are measured by their horizontal advance, ascent above the baseline, and descent below the baseline. The pyglet layout classes reserve space in the layout for elements and call the element's methods to ensure they are rendered at the appropriate position. If the size of a element (any of the `advance`, `ascent`, or `descent` instance variables) is modified it is the application's responsibility to trigger a reflow of the appropriate area in the affected layouts. This can be done by forcing a style change over the element's position. :Ivariables: `ascent` : int Ascent of the element above the baseline, in pixels. `descent` : int Descent of the element below the baseline, in pixels. Typically negative. `advance` : int Width of the element, in pixels. ''' def __init__(self, ascent, descent, advance): self.ascent = ascent self.descent = descent self.advance = advance self._position = None position = property(lambda self: self._position, doc='''Position of the element within the document. Read-only. :type: int ''') def place(self, layout, x, y): '''Construct an instance of the element at the given coordinates. Called when the element's position within a layout changes, either due to the initial condition, changes in the document or changes in the layout size. It is the responsibility of the element to clip itself against the layout boundaries, and position itself appropriately with respect to the layout's position and viewport offset. The `TextLayout.top_state` graphics state implements this transform and clipping into window space. :Parameters: `layout` : `pyglet.text.layout.TextLayout` The layout the element moved within. `x` : int Position of the left edge of the element, relative to the left edge of the document, in pixels. `y` : int Position of the baseline, relative to the top edge of the document, in pixels. Note that this is typically negative. ''' raise NotImplementedError('abstract') def remove(self, layout): '''Remove this element from a layout. The counterpart of `place`; called when the element is no longer visible in the given layout. :Parameters: `layout` : `pyglet.text.layout.TextLayout` The layout the element was removed from. ''' raise NotImplementedError('abstract') class AbstractDocument(event.EventDispatcher): '''Abstract document interface used by all `pyglet.text` classes. This class can be overridden to interface pyglet with a third-party document format. It may be easier to implement the document format in terms of one of the supplied concrete classes `FormattedDocument` or `UnformattedDocument`. ''' _previous_paragraph_re = re.compile(u'\n[^\n\u2029]*$') _next_paragraph_re = re.compile(u'[\n\u2029]') def __init__(self, text=''): super(AbstractDocument, self).__init__() self._text = u'' self._elements = [] if text: self.insert_text(0, text) def _get_text(self): return self._text def _set_text(self, text): if text == self._text: return self.delete_text(0, len(self._text)) self.insert_text(0, text) text = property(_get_text, _set_text, doc='''Document text. For efficient incremental updates, use the `insert_text` and `delete_text` methods instead of replacing this property. :type: str ''') def get_paragraph_start(self, pos): '''Get the starting position of a paragraph. :Parameters: `pos` : int Character position within paragraph. :rtype: int ''' # Tricky special case where the $ in pattern matches before the \n at # the end of the string instead of the end of the string. if (self._text[:pos + 1].endswith('\n') or self._text[:pos + 1].endswith(u'\u2029')): return pos m = self._previous_paragraph_re.search(self._text, 0, pos + 1) if not m: return 0 return m.start() + 1 def get_paragraph_end(self, pos): '''Get the end position of a paragraph. :Parameters: `pos` : int Character position within paragraph. :rtype: int ''' m = self._next_paragraph_re.search(self._text, pos) if not m: return len(self._text) return m.start() + 1 def get_style_runs(self, attribute): '''Get a style iterator over the given style attribute. :Parameters: `attribute` : str Name of style attribute to query. :rtype: `AbstractRunIterator` ''' raise NotImplementedError('abstract') def get_style(self, attribute, position=0): '''Get an attribute style at the given position. :Parameters: `attribute` : str Name of style attribute to query. `position` : int Character position of document to query. :return: The style set for the attribute at the given position. ''' raise NotImplementedError('abstract') def get_style_range(self, attribute, start, end): '''Get an attribute style over the given range. If the style varies over the range, `STYLE_INDETERMINATE` is returned. :Parameters: `attribute` : str Name of style attribute to query. `start` : int Starting character position. `end` : int Ending character position (exclusive). :return: The style set for the attribute over the given range, or `STYLE_INDETERMINATE` if more than one value is set. ''' iter = self.get_style_runs(attribute) _, value_end, value = iter.ranges(start, end).next() if value_end < end: return STYLE_INDETERMINATE else: return value def get_font_runs(self, dpi=None): '''Get a style iterator over the `pyglet.font.Font` instances used in the document. The font instances are created on-demand by inspection of the ``font_name``, ``font_size``, ``bold`` and ``italic`` style attributes. :Parameters: `dpi` : float Optional resolution to construct fonts at. See `pyglet.font.load`. :rtype: `AbstractRunIterator` ''' raise NotImplementedError('abstract') def get_font(self, position, dpi=None): '''Get the font instance used at the given position. :see: `get_font_runs` :Parameters: `position` : int Character position of document to query. `dpi` : float Optional resolution to construct fonts at. See `pyglet.font.load`. :rtype: `pyglet.font.Font` :return: The font at the given position. ''' raise NotImplementedError('abstract') def insert_text(self, start, text, attributes=None): '''Insert text into the document. :Parameters: `start` : int Character insertion point within document. `text` : str Text to insert. `attributes` : dict Optional dictionary giving named style attributes of the inserted text. ''' self._insert_text(start, text, attributes) self.dispatch_event('on_insert_text', start, text) def _insert_text(self, start, text, attributes): self._text = u''.join((self._text[:start], text, self._text[start:])) len_text = len(text) for element in self._elements: if element._position >= start: element._position += len_text def delete_text(self, start, end): '''Delete text from the document. :Parameters: `start` : int Starting character position to delete from. `end` : int Ending character position to delete to (exclusive). ''' self._delete_text(start, end) self.dispatch_event('on_delete_text', start, end) def _delete_text(self, start, end): for element in list(self._elements): if start <= element._position < end: self._elements.remove(element) elif element._position >= end: # fix bug 538 element._position -= (end - start) self._text = self._text[:start] + self._text[end:] def insert_element(self, position, element, attributes=None): '''Insert a element into the document. See the `InlineElement` class documentation for details of usage. :Parameters: `position` : int Character insertion point within document. `element` : `InlineElement` Element to insert. `attributes` : dict Optional dictionary giving named style attributes of the inserted text. ''' assert element._position is None, \ 'Element is already in a document.' self.insert_text(position, '\0', attributes) element._position = position self._elements.append(element) self._elements.sort(key=lambda d:d.position) def get_element(self, position): '''Get the element at a specified position. :Parameters: `position` : int Position in the document of the element. :rtype: `InlineElement` ''' for element in self._elements: if element._position == position: return element raise RuntimeError('No element at position %d' % position) def set_style(self, start, end, attributes): '''Set text style of some or all of the document. :Parameters: `start` : int Starting character position. `end` : int Ending character position (exclusive). `attributes` : dict Dictionary giving named style attributes of the text. ''' self._set_style(start, end, attributes) self.dispatch_event('on_style_text', start, end, attributes) def _set_style(self, start, end, attributes): raise NotImplementedError('abstract') def set_paragraph_style(self, start, end, attributes): '''Set the style for a range of paragraphs. This is a convenience method for `set_style` that aligns the character range to the enclosing paragraph(s). :Parameters: `start` : int Starting character position. `end` : int Ending character position (exclusive). `attributes` : dict Dictionary giving named style attributes of the paragraphs. ''' start = self.get_paragraph_start(start) end = self.get_paragraph_end(end) self._set_style(start, end, attributes) self.dispatch_event('on_style_text', start, end, attributes) if _is_epydoc: def on_insert_text(self, start, text): '''Text was inserted into the document. :Parameters: `start` : int Character insertion point within document. `text` : str The text that was inserted. :event: ''' def on_delete_text(self, start, end): '''Text was deleted from the document. :Parameters: `start` : int Starting character position of deleted text. `end` : int Ending character position of deleted text (exclusive). :event: ''' def on_style_text(self, start, end, attributes): '''Text character style was modified. :Parameters: `start` : int Starting character position of modified text. `end` : int Ending character position of modified text (exclusive). `attributes` : dict Dictionary giving updated named style attributes of the text. :event: ''' AbstractDocument.register_event_type('on_insert_text') AbstractDocument.register_event_type('on_delete_text') AbstractDocument.register_event_type('on_style_text') class UnformattedDocument(AbstractDocument): '''A document having uniform style over all text. Changes to the style of text within the document affects the entire document. For convenience, the ``position`` parameters of the style methods may therefore be omitted. ''' def __init__(self, text=''): super(UnformattedDocument, self).__init__(text) self.styles = {} def get_style_runs(self, attribute): value = self.styles.get(attribute) return runlist.ConstRunIterator(len(self.text), value) def get_style(self, attribute, position=None): return self.styles.get(attribute) def set_style(self, start, end, attributes): return super(UnformattedDocument, self).set_style( 0, len(self.text), attributes) def _set_style(self, start, end, attributes): self.styles.update(attributes) def set_paragraph_style(self, start, end, attributes): return super(UnformattedDocument, self).set_paragraph_style( 0, len(self.text), attributes) def get_font_runs(self, dpi=None): ft = self.get_font(dpi=dpi) return runlist.ConstRunIterator(len(self.text), ft) def get_font(self, position=None, dpi=None): from pyglet import font font_name = self.styles.get('font_name') font_size = self.styles.get('font_size') bold = self.styles.get('bold', False) italic = self.styles.get('italic', False) return font.load(font_name, font_size, bold=bool(bold), italic=bool(italic), dpi=dpi) def get_element_runs(self): return runlist.ConstRunIterator(len(self._text), None) class FormattedDocument(AbstractDocument): '''Simple implementation of a document that maintains text formatting. Changes to text style are applied according to the description in `AbstractDocument`. All styles default to ``None``. ''' def __init__(self, text=''): self._style_runs = {} super(FormattedDocument, self).__init__(text) def get_style_runs(self, attribute): try: return self._style_runs[attribute].get_run_iterator() except KeyError: return _no_style_range_iterator def get_style(self, attribute, position=0): try: return self._style_runs[attribute][position] except KeyError: return None def _set_style(self, start, end, attributes): for attribute, value in attributes.items(): try: runs = self._style_runs[attribute] except KeyError: runs = self._style_runs[attribute] = runlist.RunList(0, None) runs.insert(0, len(self._text)) runs.set_run(start, end, value) def get_font_runs(self, dpi=None): return _FontStyleRunsRangeIterator( self.get_style_runs('font_name'), self.get_style_runs('font_size'), self.get_style_runs('bold'), self.get_style_runs('italic'), dpi) def get_font(self, position, dpi=None): iter = self.get_font_runs(dpi) return iter[position] def get_element_runs(self): return _ElementIterator(self._elements, len(self._text)) def _insert_text(self, start, text, attributes): super(FormattedDocument, self)._insert_text(start, text, attributes) len_text = len(text) for runs in self._style_runs.values(): runs.insert(start, len_text) if attributes is not None: for attribute, value in attributes.items(): try: runs = self._style_runs[attribute] except KeyError: runs = self._style_runs[attribute] = \ runlist.RunList(0, None) runs.insert(0, len(self.text)) runs.set_run(start, start + len_text, value) def _delete_text(self, start, end): super(FormattedDocument, self)._delete_text(start, end) for runs in self._style_runs.values(): runs.delete(start, end) def _iter_elements(elements, length): last = 0 for element in elements: p = element.position yield last, p, None yield p, p + 1, element last = p + 1 yield last, length, None class _ElementIterator(runlist.RunIterator): def __init__(self, elements, length): self._run_list_iter = _iter_elements(elements, length) self.start, self.end, self.value = self.next() class _FontStyleRunsRangeIterator(object): # XXX subclass runlist def __init__(self, font_names, font_sizes, bolds, italics, dpi): self.zip_iter = runlist.ZipRunIterator( (font_names, font_sizes, bolds, italics)) self.dpi = dpi def ranges(self, start, end): from pyglet import font for start, end, styles in self.zip_iter.ranges(start, end): font_name, font_size, bold, italic = styles ft = font.load(font_name, font_size, bold=bool(bold), italic=bool(italic), dpi=self.dpi) yield start, end, ft def __getitem__(self, index): from pyglet import font font_name, font_size, bold, italic = self.zip_iter[index] return font.load(font_name, font_size, bold=bool(bold), italic=bool(italic), dpi=self.dpi) class _NoStyleRangeIterator(object): # XXX subclass runlist def ranges(self, start, end): yield start, end, None def __getitem__(self, index): return None _no_style_range_iterator = _NoStyleRangeIterator()
Python
# Note: The display mode API used here is Mac OS 10.6 only. ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * from ctypes import util from pyglet import app from base import Display, Screen, ScreenMode, Canvas from pyglet.libs.darwin.cocoapy import * class CocoaDisplay(Display): def get_screens(self): maxDisplays = 256 activeDisplays = (CGDirectDisplayID * maxDisplays)() count = c_uint32() quartz.CGGetActiveDisplayList(maxDisplays, activeDisplays, byref(count)) return [CocoaScreen(self, displayID) for displayID in list(activeDisplays)[:count.value]] class CocoaScreen(Screen): def __init__(self, display, displayID): bounds = quartz.CGDisplayBounds(displayID) # FIX ME: # Probably need to convert the origin coordinates depending on context: # http://www.cocoabuilder.com/archive/cocoa/233492-ns-cg-rect-conversion-and-screen-coordinates.html x, y = bounds.origin.x, bounds.origin.y width, height = bounds.size.width, bounds.size.height super(CocoaScreen, self).__init__(display, int(x), int(y), int(width), int(height)) self._cg_display_id = displayID # Save the default mode so we can restore to it. self._default_mode = self.get_mode() # FIX ME: # This method is needed to get multi-monitor support working properly. # However the NSScreens.screens() message currently sends out a warning: # "*** -[NSLock unlock]: lock (<NSLock: 0x...> '(null)') unlocked when not locked" # on Snow Leopard and apparently causes python to crash on Lion. # # def get_nsscreen(self): # """Returns the NSScreen instance that matches our CGDirectDisplayID.""" # NSScreen = ObjCClass('NSScreen') # # Get a list of all currently active NSScreens and then search through # # them until we find one that matches our CGDisplayID. # screen_array = NSScreen.screens() # count = screen_array.count() # for i in range(count): # nsscreen = screen_array.objectAtIndex_(i) # screenInfo = nsscreen.deviceDescription() # displayID = screenInfo.objectForKey_(get_NSString('NSScreenNumber')) # displayID = displayID.intValue() # if displayID == self._cg_display_id: # return nsscreen # return None def get_matching_configs(self, template): canvas = CocoaCanvas(self.display, self, None) return template.match(canvas) def get_modes(self): cgmodes = c_void_p(quartz.CGDisplayCopyAllDisplayModes(self._cg_display_id, None)) modes = [ CocoaScreenMode(self, cgmode) for cgmode in cfarray_to_list(cgmodes) ] cf.CFRelease(cgmodes) return modes def get_mode(self): cgmode = c_void_p(quartz.CGDisplayCopyDisplayMode(self._cg_display_id)) mode = CocoaScreenMode(self, cgmode) quartz.CGDisplayModeRelease(cgmode) return mode def set_mode(self, mode): assert mode.screen is self quartz.CGDisplayCapture(self._cg_display_id) quartz.CGDisplaySetDisplayMode(self._cg_display_id, mode.cgmode, None) self.width = mode.width self.height = mode.height def restore_mode(self): quartz.CGDisplaySetDisplayMode(self._cg_display_id, self._default_mode.cgmode, None) quartz.CGDisplayRelease(self._cg_display_id) def capture_display(self): quartz.CGDisplayCapture(self._cg_display_id) def release_display(self): quartz.CGDisplayRelease(self._cg_display_id) class CocoaScreenMode(ScreenMode): def __init__(self, screen, cgmode): super(CocoaScreenMode, self).__init__(screen) quartz.CGDisplayModeRetain(cgmode) self.cgmode = cgmode self.width = int(quartz.CGDisplayModeGetWidth(cgmode)) self.height = int(quartz.CGDisplayModeGetHeight(cgmode)) self.depth = self.getBitsPerPixel(cgmode) self.rate = quartz.CGDisplayModeGetRefreshRate(cgmode) def __del__(self): quartz.CGDisplayModeRelease(self.cgmode) self.cgmode = None def getBitsPerPixel(self, cgmode): # from /System/Library/Frameworks/IOKit.framework/Headers/graphics/IOGraphicsTypes.h IO8BitIndexedPixels = "PPPPPPPP" IO16BitDirectPixels = "-RRRRRGGGGGBBBBB" IO32BitDirectPixels = "--------RRRRRRRRGGGGGGGGBBBBBBBB" cfstring = c_void_p(quartz.CGDisplayModeCopyPixelEncoding(cgmode)) pixelEncoding = cfstring_to_string(cfstring) cf.CFRelease(cfstring) if pixelEncoding == IO8BitIndexedPixels: return 8 if pixelEncoding == IO16BitDirectPixels: return 16 if pixelEncoding == IO32BitDirectPixels: return 32 return 0 class CocoaCanvas(Canvas): def __init__(self, display, screen, nsview): super(CocoaCanvas, self).__init__(display) self.screen = screen self.nsview = nsview
Python
#!/usr/bin/python # $Id:$ from base import Display, Screen, ScreenMode, Canvas from pyglet.libs.win32 import _kernel32, _user32, types, constants from pyglet.libs.win32.constants import * from pyglet.libs.win32.types import * class Win32Display(Display): def get_screens(self): screens = [] def enum_proc(hMonitor, hdcMonitor, lprcMonitor, dwData): r = lprcMonitor.contents width = r.right - r.left height = r.bottom - r.top screens.append( Win32Screen(self, hMonitor, r.left, r.top, width, height)) return True enum_proc_ptr = MONITORENUMPROC(enum_proc) _user32.EnumDisplayMonitors(None, None, enum_proc_ptr, 0) return screens class Win32Screen(Screen): _initial_mode = None def __init__(self, display, handle, x, y, width, height): super(Win32Screen, self).__init__(display, x, y, width, height) self._handle = handle def get_matching_configs(self, template): canvas = Win32Canvas(self.display, 0, _user32.GetDC(0)) configs = template.match(canvas) # XXX deprecate config's being screen-specific for config in configs: config.screen = self return configs def get_device_name(self): info = MONITORINFOEX() info.cbSize = sizeof(MONITORINFOEX) _user32.GetMonitorInfoW(self._handle, byref(info)) return info.szDevice def get_modes(self): device_name = self.get_device_name() i = 0 modes = [] while True: mode = DEVMODE() mode.dmSize = sizeof(DEVMODE) r = _user32.EnumDisplaySettingsW(device_name, i, byref(mode)) if not r: break modes.append(Win32ScreenMode(self, mode)) i += 1 return modes def get_mode(self): mode = DEVMODE() mode.dmSize = sizeof(DEVMODE) _user32.EnumDisplaySettingsW(self.get_device_name(), ENUM_CURRENT_SETTINGS, byref(mode)) return Win32ScreenMode(self, mode) def set_mode(self, mode): assert mode.screen is self if not self._initial_mode: self._initial_mode = self.get_mode() r = _user32.ChangeDisplaySettingsExW(self.get_device_name(), byref(mode._mode), None, CDS_FULLSCREEN, None) if r == DISP_CHANGE_SUCCESSFUL: self.width = mode.width self.height = mode.height def restore_mode(self): if self._initial_mode: self.set_mode(self._initial_mode) class Win32ScreenMode(ScreenMode): def __init__(self, screen, mode): super(Win32ScreenMode, self).__init__(screen) self._mode = mode self.width = mode.dmPelsWidth self.height = mode.dmPelsHeight self.depth = mode.dmBitsPerPel self.rate = mode.dmDisplayFrequency class Win32Canvas(Canvas): def __init__(self, display, hwnd, hdc): super(Win32Canvas, self).__init__(display) self.hwnd = hwnd self.hdc = hdc
Python
#!/usr/bin/python # $Id: $ '''Fork a child process and inform it of mode changes to each screen. The child waits until the parent process dies, and then connects to each X server with a mode change and restores the mode. This emulates the behaviour of Windows and Mac, so that resolution changes made by an application are not permanent after the program exits, even if the process is terminated uncleanly. The child process is communicated to via a pipe, and watches for parent death with a Linux extension signal handler. ''' import ctypes import os import signal import struct import threading from pyglet.libs.x11 import xlib from pyglet.compat import asbytes try: from pyglet.libs.x11 import xf86vmode except: # No xf86vmode... should not be switching modes. pass _restore_mode_child_installed = False _restorable_screens = set() _mode_write_pipe = None # Mode packets tell the child process how to restore a given display and # screen. Only one packet should be sent per display/screen (more would # indicate redundancy or incorrect restoration). Packet format is: # display (max 256 chars), # screen # width # height # rate class ModePacket(object): format = '256siHHI' size = struct.calcsize(format) def __init__(self, display, screen, width, height, rate): self.display = display self.screen = screen self.width = width self.height = height self.rate = rate def encode(self): return struct.pack(self.format, self.display, self.screen, self.width, self.height, self.rate) @classmethod def decode(cls, data): display, screen, width, height, rate = \ struct.unpack(cls.format, data) return cls(display.strip(asbytes('\0')), screen, width, height, rate) def __repr__(self): return '%s(%r, %r, %r, %r, %r)' % ( self.__class__.__name__, self.display, self.screen, self.width, self.height, self.rate) def set(self): display = xlib.XOpenDisplay(self.display) modes, n_modes = get_modes_array(display, self.screen) mode = get_matching_mode(modes, n_modes, self.width, self.height, self.rate) if mode is not None: xf86vmode.XF86VidModeSwitchToMode(display, self.screen, mode) free_modes_array(modes, n_modes) xlib.XCloseDisplay(display) def get_modes_array(display, screen): count = ctypes.c_int() modes = ctypes.POINTER(ctypes.POINTER(xf86vmode.XF86VidModeModeInfo))() xf86vmode.XF86VidModeGetAllModeLines(display, screen, count, modes) return modes, count.value def get_matching_mode(modes, n_modes, width, height, rate): # Copy modes out of list and free list for i in range(n_modes): mode = modes.contents[i] if (mode.hdisplay == width and mode.vdisplay == height and mode.dotclock == rate): return mode return None def free_modes_array(modes, n_modes): for i in range(n_modes): mode = modes.contents[i] if mode.privsize: xlib.XFree(mode.private) xlib.XFree(modes) def _install_restore_mode_child(): global _mode_write_pipe global _restore_mode_child_installed if _restore_mode_child_installed: return # Parent communicates to child by sending "mode packets" through a pipe: mode_read_pipe, _mode_write_pipe = os.pipe() if os.fork() == 0: # Child process (watches for parent to die then restores video mode(s). os.close(_mode_write_pipe) # Set up SIGHUP to be the signal for when the parent dies. PR_SET_PDEATHSIG = 1 libc = ctypes.cdll.LoadLibrary('libc.so.6') libc.prctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong) libc.prctl(PR_SET_PDEATHSIG, signal.SIGHUP, 0, 0, 0) # SIGHUP indicates the parent has died. The child lock is unlocked, it # stops reading from the mode packet pipe and restores video modes on # all displays/screens it knows about. def _sighup(signum, frame): parent_wait_lock.release(); parent_wait_lock = threading.Lock(); parent_wait_lock.acquire() signal.signal(signal.SIGHUP, _sighup) # Wait for parent to die and read packets from parent pipe packets = [] buffer = asbytes('') while parent_wait_lock.locked(): try: data = os.read(mode_read_pipe, ModePacket.size) buffer += data # Decode packets while len(buffer) >= ModePacket.size: packet = ModePacket.decode(buffer[:ModePacket.size]) packets.append(packet) buffer = buffer[ModePacket.size:] except OSError: pass # Interrupted system call for packet in packets: packet.set() os._exit(0) else: # Parent process. Clean up pipe then continue running program as # normal. Send mode packets through pipe as additional # displays/screens are mode switched. os.close(mode_read_pipe) _restore_mode_child_installed = True def set_initial_mode(mode): _install_restore_mode_child() display = xlib.XDisplayString(mode.screen.display._display) screen = mode.screen.display.x_screen # Only store one mode per screen. if (display, screen) in _restorable_screens: return packet = ModePacket(display, screen, mode.width, mode.height, mode.rate) os.write(_mode_write_pipe, packet.encode()) _restorable_screens.add((display, screen))
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * import ctypes from pyglet import app from pyglet.app.xlib import XlibSelectDevice from base import Display, Screen, ScreenMode, Canvas import xlib_vidmoderestore # XXX #from pyglet.window import NoSuchDisplayException class NoSuchDisplayException(Exception): pass from pyglet.libs.x11 import xlib try: from pyglet.libs.x11 import xinerama _have_xinerama = True except: _have_xinerama = False try: from pyglet.libs.x11 import xsync _have_xsync = True except: _have_xsync = False try: from pyglet.libs.x11 import xf86vmode _have_xf86vmode = True except: _have_xf86vmode = False # Set up error handler def _error_handler(display, event): # By default, all errors are silently ignored: this has a better chance # of working than the default behaviour of quitting ;-) # # We've actually never seen an error that was our fault; they're always # driver bugs (and so the reports are useless). Nevertheless, set # environment variable PYGLET_DEBUG_X11 to 1 to get dumps of the error # and a traceback (execution will continue). import pyglet if pyglet.options['debug_x11']: event = event.contents buf = c_buffer(1024) xlib.XGetErrorText(display, event.error_code, buf, len(buf)) print 'X11 error:', buf.value print ' serial:', event.serial print ' request:', event.request_code print ' minor:', event.minor_code print ' resource:', event.resourceid import traceback print 'Python stack trace (innermost last):' traceback.print_stack() return 0 _error_handler_ptr = xlib.XErrorHandler(_error_handler) xlib.XSetErrorHandler(_error_handler_ptr) class XlibDisplay(XlibSelectDevice, Display): _display = None # POINTER(xlib.Display) _x_im = None # X input method # TODO close _x_im when display connection closed. _enable_xsync = False _screens = None # Cache of get_screens() def __init__(self, name=None, x_screen=None): if x_screen is None: x_screen = 0 self._display = xlib.XOpenDisplay(name) if not self._display: raise NoSuchDisplayException('Cannot connect to "%s"' % name) screen_count = xlib.XScreenCount(self._display) if x_screen >= screen_count: raise NoSuchDisplayException( 'Display "%s" has no screen %d' % (name, x_screen)) super(XlibDisplay, self).__init__() self.name = name self.x_screen = x_screen self._fileno = xlib.XConnectionNumber(self._display) self._window_map = {} # Initialise XSync if _have_xsync: event_base = c_int() error_base = c_int() if xsync.XSyncQueryExtension(self._display, byref(event_base), byref(error_base)): major_version = c_int() minor_version = c_int() if xsync.XSyncInitialize(self._display, byref(major_version), byref(minor_version)): self._enable_xsync = True # Add to event loop select list. Assume we never go away. app.platform_event_loop._select_devices.add(self) def get_screens(self): if self._screens: return self._screens if _have_xinerama and xinerama.XineramaIsActive(self._display): number = c_int() infos = xinerama.XineramaQueryScreens(self._display, byref(number)) infos = cast(infos, POINTER(xinerama.XineramaScreenInfo * number.value)).contents self._screens = [] using_xinerama = number.value > 1 for info in infos: self._screens.append(XlibScreen(self, info.x_org, info.y_org, info.width, info.height, using_xinerama)) xlib.XFree(infos) else: # No xinerama screen_info = xlib.XScreenOfDisplay(self._display, self.x_screen) screen = XlibScreen(self, 0, 0, screen_info.contents.width, screen_info.contents.height, False) self._screens = [screen] return self._screens # XlibSelectDevice interface def fileno(self): return self._fileno def select(self): e = xlib.XEvent() while xlib.XPending(self._display): xlib.XNextEvent(self._display, e) # Key events are filtered by the xlib window event # handler so they get a shot at the prefiltered event. if e.xany.type not in (xlib.KeyPress, xlib.KeyRelease): if xlib.XFilterEvent(e, e.xany.window): continue try: dispatch = self._window_map[e.xany.window] except KeyError: continue dispatch(e) def poll(self): return xlib.XPending(self._display) class XlibScreen(Screen): _initial_mode = None def __init__(self, display, x, y, width, height, xinerama): super(XlibScreen, self).__init__(display, x, y, width, height) self._xinerama = xinerama def get_matching_configs(self, template): canvas = XlibCanvas(self.display, None) configs = template.match(canvas) # XXX deprecate for config in configs: config.screen = self return configs def get_modes(self): if not _have_xf86vmode: return [] if self._xinerama: # If Xinerama/TwinView is enabled, xf86vidmode's modelines # correspond to metamodes, which don't distinguish one screen from # another. XRandR (broken) or NV (complicated) extensions needed. return [] count = ctypes.c_int() info_array = \ ctypes.POINTER(ctypes.POINTER(xf86vmode.XF86VidModeModeInfo))() xf86vmode.XF86VidModeGetAllModeLines( self.display._display, self.display.x_screen, count, info_array) # Copy modes out of list and free list modes = [] for i in range(count.value): info = xf86vmode.XF86VidModeModeInfo() ctypes.memmove(ctypes.byref(info), ctypes.byref(info_array.contents[i]), ctypes.sizeof(info)) modes.append(XlibScreenMode(self, info)) if info.privsize: xlib.XFree(info.private) xlib.XFree(info_array) return modes def get_mode(self): modes = self.get_modes() if modes: return modes[0] return None def set_mode(self, mode): assert mode.screen is self if not self._initial_mode: self._initial_mode = self.get_mode() xlib_vidmoderestore.set_initial_mode(self._initial_mode) xf86vmode.XF86VidModeSwitchToMode(self.display._display, self.display.x_screen, mode.info) xlib.XFlush(self.display._display) xf86vmode.XF86VidModeSetViewPort(self.display._display, self.display.x_screen, 0, 0) xlib.XFlush(self.display._display) self.width = mode.width self.height = mode.height def restore_mode(self): if self._initial_mode: self.set_mode(self._initial_mode) def __repr__(self): return 'XlibScreen(display=%r, x=%d, y=%d, ' \ 'width=%d, height=%d, xinerama=%d)' % \ (self.display, self.x, self.y, self.width, self.height, self._xinerama) class XlibScreenMode(ScreenMode): def __init__(self, screen, info): super(XlibScreenMode, self).__init__(screen) self.info = info self.width = info.hdisplay self.height = info.vdisplay self.rate = info.dotclock self.depth = None class XlibCanvas(Canvas): def __init__(self, display, x_window): super(XlibCanvas, self).__init__(display) self.x_window = x_window
Python
#!/usr/bin/python # $Id: $ '''Fork a child process and inform it of mode changes to each screen. The child waits until the parent process dies, and then connects to each X server with a mode change and restores the mode. This emulates the behaviour of Windows and Mac, so that resolution changes made by an application are not permanent after the program exits, even if the process is terminated uncleanly. The child process is communicated to via a pipe, and watches for parent death with a Linux extension signal handler. ''' import ctypes import os import signal import struct import threading from pyglet.libs.x11 import xlib from pyglet.compat import asbytes try: from pyglet.libs.x11 import xf86vmode except: # No xf86vmode... should not be switching modes. pass _restore_mode_child_installed = False _restorable_screens = set() _mode_write_pipe = None # Mode packets tell the child process how to restore a given display and # screen. Only one packet should be sent per display/screen (more would # indicate redundancy or incorrect restoration). Packet format is: # display (max 256 chars), # screen # width # height # rate class ModePacket(object): format = '256siHHI' size = struct.calcsize(format) def __init__(self, display, screen, width, height, rate): self.display = display self.screen = screen self.width = width self.height = height self.rate = rate def encode(self): return struct.pack(self.format, self.display, self.screen, self.width, self.height, self.rate) @classmethod def decode(cls, data): display, screen, width, height, rate = \ struct.unpack(cls.format, data) return cls(display.strip(asbytes('\0')), screen, width, height, rate) def __repr__(self): return '%s(%r, %r, %r, %r, %r)' % ( self.__class__.__name__, self.display, self.screen, self.width, self.height, self.rate) def set(self): display = xlib.XOpenDisplay(self.display) modes, n_modes = get_modes_array(display, self.screen) mode = get_matching_mode(modes, n_modes, self.width, self.height, self.rate) if mode is not None: xf86vmode.XF86VidModeSwitchToMode(display, self.screen, mode) free_modes_array(modes, n_modes) xlib.XCloseDisplay(display) def get_modes_array(display, screen): count = ctypes.c_int() modes = ctypes.POINTER(ctypes.POINTER(xf86vmode.XF86VidModeModeInfo))() xf86vmode.XF86VidModeGetAllModeLines(display, screen, count, modes) return modes, count.value def get_matching_mode(modes, n_modes, width, height, rate): # Copy modes out of list and free list for i in range(n_modes): mode = modes.contents[i] if (mode.hdisplay == width and mode.vdisplay == height and mode.dotclock == rate): return mode return None def free_modes_array(modes, n_modes): for i in range(n_modes): mode = modes.contents[i] if mode.privsize: xlib.XFree(mode.private) xlib.XFree(modes) def _install_restore_mode_child(): global _mode_write_pipe global _restore_mode_child_installed if _restore_mode_child_installed: return # Parent communicates to child by sending "mode packets" through a pipe: mode_read_pipe, _mode_write_pipe = os.pipe() if os.fork() == 0: # Child process (watches for parent to die then restores video mode(s). os.close(_mode_write_pipe) # Set up SIGHUP to be the signal for when the parent dies. PR_SET_PDEATHSIG = 1 libc = ctypes.cdll.LoadLibrary('libc.so.6') libc.prctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong) libc.prctl(PR_SET_PDEATHSIG, signal.SIGHUP, 0, 0, 0) # SIGHUP indicates the parent has died. The child lock is unlocked, it # stops reading from the mode packet pipe and restores video modes on # all displays/screens it knows about. def _sighup(signum, frame): parent_wait_lock.release(); parent_wait_lock = threading.Lock(); parent_wait_lock.acquire() signal.signal(signal.SIGHUP, _sighup) # Wait for parent to die and read packets from parent pipe packets = [] buffer = asbytes('') while parent_wait_lock.locked(): try: data = os.read(mode_read_pipe, ModePacket.size) buffer += data # Decode packets while len(buffer) >= ModePacket.size: packet = ModePacket.decode(buffer[:ModePacket.size]) packets.append(packet) buffer = buffer[ModePacket.size:] except OSError: pass # Interrupted system call for packet in packets: packet.set() os._exit(0) else: # Parent process. Clean up pipe then continue running program as # normal. Send mode packets through pipe as additional # displays/screens are mode switched. os.close(mode_read_pipe) _restore_mode_child_installed = True def set_initial_mode(mode): _install_restore_mode_child() display = xlib.XDisplayString(mode.screen.display._display) screen = mode.screen.display.x_screen # Only store one mode per screen. if (display, screen) in _restorable_screens: return packet = ModePacket(display, screen, mode.width, mode.height, mode.rate) os.write(_mode_write_pipe, packet.encode()) _restorable_screens.add((display, screen))
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * import ctypes from pyglet import app from pyglet.app.xlib import XlibSelectDevice from base import Display, Screen, ScreenMode, Canvas import xlib_vidmoderestore # XXX #from pyglet.window import NoSuchDisplayException class NoSuchDisplayException(Exception): pass from pyglet.libs.x11 import xlib try: from pyglet.libs.x11 import xinerama _have_xinerama = True except: _have_xinerama = False try: from pyglet.libs.x11 import xsync _have_xsync = True except: _have_xsync = False try: from pyglet.libs.x11 import xf86vmode _have_xf86vmode = True except: _have_xf86vmode = False # Set up error handler def _error_handler(display, event): # By default, all errors are silently ignored: this has a better chance # of working than the default behaviour of quitting ;-) # # We've actually never seen an error that was our fault; they're always # driver bugs (and so the reports are useless). Nevertheless, set # environment variable PYGLET_DEBUG_X11 to 1 to get dumps of the error # and a traceback (execution will continue). import pyglet if pyglet.options['debug_x11']: event = event.contents buf = c_buffer(1024) xlib.XGetErrorText(display, event.error_code, buf, len(buf)) print 'X11 error:', buf.value print ' serial:', event.serial print ' request:', event.request_code print ' minor:', event.minor_code print ' resource:', event.resourceid import traceback print 'Python stack trace (innermost last):' traceback.print_stack() return 0 _error_handler_ptr = xlib.XErrorHandler(_error_handler) xlib.XSetErrorHandler(_error_handler_ptr) class XlibDisplay(XlibSelectDevice, Display): _display = None # POINTER(xlib.Display) _x_im = None # X input method # TODO close _x_im when display connection closed. _enable_xsync = False _screens = None # Cache of get_screens() def __init__(self, name=None, x_screen=None): if x_screen is None: x_screen = 0 self._display = xlib.XOpenDisplay(name) if not self._display: raise NoSuchDisplayException('Cannot connect to "%s"' % name) screen_count = xlib.XScreenCount(self._display) if x_screen >= screen_count: raise NoSuchDisplayException( 'Display "%s" has no screen %d' % (name, x_screen)) super(XlibDisplay, self).__init__() self.name = name self.x_screen = x_screen self._fileno = xlib.XConnectionNumber(self._display) self._window_map = {} # Initialise XSync if _have_xsync: event_base = c_int() error_base = c_int() if xsync.XSyncQueryExtension(self._display, byref(event_base), byref(error_base)): major_version = c_int() minor_version = c_int() if xsync.XSyncInitialize(self._display, byref(major_version), byref(minor_version)): self._enable_xsync = True # Add to event loop select list. Assume we never go away. app.platform_event_loop._select_devices.add(self) def get_screens(self): if self._screens: return self._screens if _have_xinerama and xinerama.XineramaIsActive(self._display): number = c_int() infos = xinerama.XineramaQueryScreens(self._display, byref(number)) infos = cast(infos, POINTER(xinerama.XineramaScreenInfo * number.value)).contents self._screens = [] using_xinerama = number.value > 1 for info in infos: self._screens.append(XlibScreen(self, info.x_org, info.y_org, info.width, info.height, using_xinerama)) xlib.XFree(infos) else: # No xinerama screen_info = xlib.XScreenOfDisplay(self._display, self.x_screen) screen = XlibScreen(self, 0, 0, screen_info.contents.width, screen_info.contents.height, False) self._screens = [screen] return self._screens # XlibSelectDevice interface def fileno(self): return self._fileno def select(self): e = xlib.XEvent() while xlib.XPending(self._display): xlib.XNextEvent(self._display, e) # Key events are filtered by the xlib window event # handler so they get a shot at the prefiltered event. if e.xany.type not in (xlib.KeyPress, xlib.KeyRelease): if xlib.XFilterEvent(e, e.xany.window): continue try: dispatch = self._window_map[e.xany.window] except KeyError: continue dispatch(e) def poll(self): return xlib.XPending(self._display) class XlibScreen(Screen): _initial_mode = None def __init__(self, display, x, y, width, height, xinerama): super(XlibScreen, self).__init__(display, x, y, width, height) self._xinerama = xinerama def get_matching_configs(self, template): canvas = XlibCanvas(self.display, None) configs = template.match(canvas) # XXX deprecate for config in configs: config.screen = self return configs def get_modes(self): if not _have_xf86vmode: return [] if self._xinerama: # If Xinerama/TwinView is enabled, xf86vidmode's modelines # correspond to metamodes, which don't distinguish one screen from # another. XRandR (broken) or NV (complicated) extensions needed. return [] count = ctypes.c_int() info_array = \ ctypes.POINTER(ctypes.POINTER(xf86vmode.XF86VidModeModeInfo))() xf86vmode.XF86VidModeGetAllModeLines( self.display._display, self.display.x_screen, count, info_array) # Copy modes out of list and free list modes = [] for i in range(count.value): info = xf86vmode.XF86VidModeModeInfo() ctypes.memmove(ctypes.byref(info), ctypes.byref(info_array.contents[i]), ctypes.sizeof(info)) modes.append(XlibScreenMode(self, info)) if info.privsize: xlib.XFree(info.private) xlib.XFree(info_array) return modes def get_mode(self): modes = self.get_modes() if modes: return modes[0] return None def set_mode(self, mode): assert mode.screen is self if not self._initial_mode: self._initial_mode = self.get_mode() xlib_vidmoderestore.set_initial_mode(self._initial_mode) xf86vmode.XF86VidModeSwitchToMode(self.display._display, self.display.x_screen, mode.info) xlib.XFlush(self.display._display) xf86vmode.XF86VidModeSetViewPort(self.display._display, self.display.x_screen, 0, 0) xlib.XFlush(self.display._display) self.width = mode.width self.height = mode.height def restore_mode(self): if self._initial_mode: self.set_mode(self._initial_mode) def __repr__(self): return 'XlibScreen(display=%r, x=%d, y=%d, ' \ 'width=%d, height=%d, xinerama=%d)' % \ (self.display, self.x, self.y, self.width, self.height, self._xinerama) class XlibScreenMode(ScreenMode): def __init__(self, screen, info): super(XlibScreenMode, self).__init__(screen) self.info = info self.width = info.hdisplay self.height = info.vdisplay self.rate = info.dotclock self.depth = None class XlibCanvas(Canvas): def __init__(self, display, x_window): super(XlibCanvas, self).__init__(display) self.x_window = x_window
Python
#!/usr/bin/python # $Id:$ from base import Display, Screen, ScreenMode, Canvas from pyglet.libs.win32 import _kernel32, _user32, types, constants from pyglet.libs.win32.constants import * from pyglet.libs.win32.types import * class Win32Display(Display): def get_screens(self): screens = [] def enum_proc(hMonitor, hdcMonitor, lprcMonitor, dwData): r = lprcMonitor.contents width = r.right - r.left height = r.bottom - r.top screens.append( Win32Screen(self, hMonitor, r.left, r.top, width, height)) return True enum_proc_ptr = MONITORENUMPROC(enum_proc) _user32.EnumDisplayMonitors(None, None, enum_proc_ptr, 0) return screens class Win32Screen(Screen): _initial_mode = None def __init__(self, display, handle, x, y, width, height): super(Win32Screen, self).__init__(display, x, y, width, height) self._handle = handle def get_matching_configs(self, template): canvas = Win32Canvas(self.display, 0, _user32.GetDC(0)) configs = template.match(canvas) # XXX deprecate config's being screen-specific for config in configs: config.screen = self return configs def get_device_name(self): info = MONITORINFOEX() info.cbSize = sizeof(MONITORINFOEX) _user32.GetMonitorInfoW(self._handle, byref(info)) return info.szDevice def get_modes(self): device_name = self.get_device_name() i = 0 modes = [] while True: mode = DEVMODE() mode.dmSize = sizeof(DEVMODE) r = _user32.EnumDisplaySettingsW(device_name, i, byref(mode)) if not r: break modes.append(Win32ScreenMode(self, mode)) i += 1 return modes def get_mode(self): mode = DEVMODE() mode.dmSize = sizeof(DEVMODE) _user32.EnumDisplaySettingsW(self.get_device_name(), ENUM_CURRENT_SETTINGS, byref(mode)) return Win32ScreenMode(self, mode) def set_mode(self, mode): assert mode.screen is self if not self._initial_mode: self._initial_mode = self.get_mode() r = _user32.ChangeDisplaySettingsExW(self.get_device_name(), byref(mode._mode), None, CDS_FULLSCREEN, None) if r == DISP_CHANGE_SUCCESSFUL: self.width = mode.width self.height = mode.height def restore_mode(self): if self._initial_mode: self.set_mode(self._initial_mode) class Win32ScreenMode(ScreenMode): def __init__(self, screen, mode): super(Win32ScreenMode, self).__init__(screen) self._mode = mode self.width = mode.dmPelsWidth self.height = mode.dmPelsHeight self.depth = mode.dmBitsPerPel self.rate = mode.dmDisplayFrequency class Win32Canvas(Canvas): def __init__(self, display, hwnd, hdc): super(Win32Canvas, self).__init__(display) self.hwnd = hwnd self.hdc = hdc
Python
#!/usr/bin/python # $Id:$ from pyglet import app from pyglet import gl from pyglet import window class Display(object): '''A display device supporting one or more screens. :Ivariables: `name` : str Name of this display, if applicable. `x_screen` : int The X11 screen number of this display, if applicable. :since: pyglet 1.2 ''' name = None x_screen = None def __init__(self, name=None, x_screen=None): '''Create a display connection for the given name and screen. On X11, `name` is of the form ``"hostname:display"``, where the default is usually ``":1"``. On X11, `x_screen` gives the X screen number to use with this display. A pyglet display can only be used with one X screen; open multiple display connections to access multiple X screens. Note that TwinView, Xinerama, xrandr and other extensions present multiple monitors on a single X screen; this is usually the preferred mechanism for working with multiple monitors under X11 and allows each screen to be accessed through a single pyglet `Display`. On platforms other than X11, `name` and `x_screen` are ignored; there is only a single display device on these systems. :Parameters: `name` : str The name of the display to connect to. `x_screen` : int The X11 screen number to use. ''' app.displays.add(self) def get_screens(self): '''Get the available screens. A typical multi-monitor workstation comprises one `Display` with multiple `Screen` s. This method returns a list of screens which can be enumerated to select one for full-screen display. For the purposes of creating an OpenGL config, the default screen will suffice. :rtype: list of `Screen` ''' raise NotImplementedError('abstract') def get_default_screen(self): '''Get the default screen as specified by the user's operating system preferences. :rtype: `Screen` ''' return self.get_screens()[0] def get_windows(self): '''Get the windows currently attached to this display. :rtype: sequence of `Window` ''' return [window for window in app.windows if window.display is self] class Screen(object): '''A virtual monitor that supports fullscreen windows. Screens typically map onto a physical display such as a monitor, television or projector. Selecting a screen for a window has no effect unless the window is made fullscreen, in which case the window will fill only that particular virtual screen. The `width` and `height` attributes of a screen give the current resolution of the screen. The `x` and `y` attributes give the global location of the top-left corner of the screen. This is useful for determining if screens arranged above or next to one another. Use `Display.get_screens` or `Display.get_default_screen` to obtain an instance of this class. :Ivariables: `display` : `Display` Display this screen belongs to. `x` : int Left edge of the screen on the virtual desktop. `y` : int Top edge of the screen on the virtual desktop. `width` : int Width of the screen, in pixels. `height` : int Height of the screen, in pixels. ''' def __init__(self, display, x, y, width, height): self.display = display self.x = x self.y = y self.width = width self.height = height def __repr__(self): return '%s(x=%d, y=%d, width=%d, height=%d)' % \ (self.__class__.__name__, self.x, self.y, self.width, self.height) def get_best_config(self, template=None): '''Get the best available GL config. Any required attributes can be specified in `template`. If no configuration matches the template, `NoSuchConfigException` will be raised. :deprecated: Use `pyglet.gl.Config.match`. :Parameters: `template` : `pyglet.gl.Config` A configuration with desired attributes filled in. :rtype: `pyglet.gl.Config` :return: A configuration supported by the platform that best fulfils the needs described by the template. ''' configs = None if template is None: for template_config in [ gl.Config(double_buffer=True, depth_size=24), gl.Config(double_buffer=True, depth_size=16), None]: try: configs = self.get_matching_configs(template_config) break except NoSuchConfigException: pass else: configs = self.get_matching_configs(template) if not configs: raise window.NoSuchConfigException() return configs[0] def get_matching_configs(self, template): '''Get a list of configs that match a specification. Any attributes specified in `template` will have values equal to or greater in each returned config. If no configs satisfy the template, an empty list is returned. :deprecated: Use `pyglet.gl.Config.match`. :Parameters: `template` : `pyglet.gl.Config` A configuration with desired attributes filled in. :rtype: list of `pyglet.gl.Config` :return: A list of matching configs. ''' raise NotImplementedError('abstract') def get_modes(self): '''Get a list of screen modes supported by this screen. :rtype: list of `ScreenMode` :since: pyglet 1.2 ''' raise NotImplementedError('abstract') def get_mode(self): '''Get the current display mode for this screen. :rtype: `ScreenMode` :since: pyglet 1.2 ''' raise NotImplementedError('abstract') def get_closest_mode(self, width, height): '''Get the screen mode that best matches a given size. If no supported mode exactly equals the requested size, a larger one is returned; or ``None`` if no mode is large enough. :Parameters: `width` : int Requested screen width. `height` : int Requested screen height. :rtype: `ScreenMode` :since: pyglet 1.2 ''' # Best mode is one with smallest resolution larger than width/height, # with depth and refresh rate equal to current mode. current = self.get_mode() best = None for mode in self.get_modes(): # Reject resolutions that are too small if mode.width < width or mode.height < height: continue if best is None: best = mode # Must strictly dominate dimensions if (mode.width <= best.width and mode.height <= best.height and (mode.width < best.width or mode.height < best.height)): best = mode # Preferably match rate, then depth. if mode.width == best.width and mode.height == best.height: points = 0 if mode.rate == current.rate: points += 2 if best.rate == current.rate: points -= 2 if mode.depth == current.depth: points += 1 if best.depth == current.depth: points -= 1 if points > 0: best = mode return best def set_mode(self, mode): '''Set the display mode for this screen. The mode must be one previously returned by `get_mode` or `get_modes`. :Parameters: `mode` : `ScreenMode` Screen mode to switch this screen to. ''' raise NotImplementedError('abstract') def restore_mode(self): '''Restore the screen mode to the user's default. ''' raise NotImplementedError('abstract') class ScreenMode(object): '''Screen resolution and display settings. Applications should not construct `ScreenMode` instances themselves; see `Screen.get_modes`. The `depth` and `rate` variables may be ``None`` if the operating system does not provide relevant data. :Ivariables: `width` : int Width of screen, in pixels. `height` : int Height of screen, in pixels. `depth` : int Pixel color depth, in bits per pixel. `rate` : int Screen refresh rate in Hz. :since: pyglet 1.2 ''' width = None height = None depth = None rate = None def __init__(self, screen): self.screen = screen def __repr__(self): return '%s(width=%r, height=%r, depth=%r, rate=%r)' % ( self.__class__.__name__, self.width, self.height, self.depth, self.rate) class Canvas(object): '''Abstract drawing area. Canvases are used internally by pyglet to represent drawing areas -- either within a window or full-screen. :Ivariables: `display` : `Display` Display this canvas was created on. :since: pyglet 1.2 ''' def __init__(self, display): self.display = display
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from pyglet import app from base import Display, Screen, ScreenMode, Canvas from pyglet.libs.darwin import * from pyglet.libs.darwin import _oscheck class CarbonDisplay(Display): # TODO: CarbonDisplay could be per display device, which would make # reporting of screens and available configs more accurate. The number of # Macs with more than one video card is probably small, though. def __init__(self): super(CarbonDisplay, self).__init__() import MacOS if not MacOS.WMAvailable(): raise app.AppException('Window manager is not available. ' \ 'Ensure you run "pythonw", not "python"') self._install_application_event_handlers() def get_screens(self): count = CGDisplayCount() carbon.CGGetActiveDisplayList(0, None, byref(count)) displays = (CGDirectDisplayID * count.value)() carbon.CGGetActiveDisplayList(count.value, displays, byref(count)) return [CarbonScreen(self, id) for id in displays] def _install_application_event_handlers(self): self._carbon_event_handlers = [] self._carbon_event_handler_refs = [] target = carbon.GetApplicationEventTarget() # TODO something with a metaclass or hacky like CarbonWindow # to make this list extensible handlers = [ (self._on_mouse_down, kEventClassMouse, kEventMouseDown), (self._on_apple_event, kEventClassAppleEvent, kEventAppleEvent), (self._on_command, kEventClassCommand, kEventProcessCommand), ] ae_handlers = [ (self._on_ae_quit, kCoreEventClass, kAEQuitApplication), ] # Install the application-wide handlers for method, cls, event in handlers: proc = EventHandlerProcPtr(method) self._carbon_event_handlers.append(proc) upp = carbon.NewEventHandlerUPP(proc) types = EventTypeSpec() types.eventClass = cls types.eventKind = event handler_ref = EventHandlerRef() carbon.InstallEventHandler( target, upp, 1, byref(types), c_void_p(), byref(handler_ref)) self._carbon_event_handler_refs.append(handler_ref) # Install Apple event handlers for method, cls, event in ae_handlers: proc = EventHandlerProcPtr(method) self._carbon_event_handlers.append(proc) upp = carbon.NewAEEventHandlerUPP(proc) carbon.AEInstallEventHandler( cls, event, upp, 0, False) def _on_command(self, next_handler, ev, data): command = HICommand() carbon.GetEventParameter(ev, kEventParamDirectObject, typeHICommand, c_void_p(), sizeof(command), c_void_p(), byref(command)) if command.commandID == kHICommandQuit: self._on_quit() return noErr def _on_mouse_down(self, next_handler, ev, data): # Check for menubar hit position = Point() carbon.GetEventParameter(ev, kEventParamMouseLocation, typeQDPoint, c_void_p(), sizeof(position), c_void_p(), byref(position)) if carbon.FindWindow(position, None) == inMenuBar: # Mouse down in menu bar. MenuSelect() takes care of all # menu tracking and blocks until the menu is dismissed. # Use command events to handle actual menu item invokations. # This function blocks, so tell the event loop it needs to install # a timer. app.event_loop.enter_blocking() carbon.MenuSelect(position) app.event_loop.exit_blocking() # Menu selection has now returned. Remove highlight from the # menubar. carbon.HiliteMenu(0) carbon.CallNextEventHandler(next_handler, ev) return noErr def _on_apple_event(self, next_handler, ev, data): # Somewhat involved way of redispatching Apple event contained # within a Carbon event, described in # http://developer.apple.com/documentation/AppleScript/ # Conceptual/AppleEvents/dispatch_aes_aepg/chapter_4_section_3.html release = False if carbon.IsEventInQueue(carbon.GetMainEventQueue(), ev): carbon.RetainEvent(ev) release = True carbon.RemoveEventFromQueue(carbon.GetMainEventQueue(), ev) ev_record = EventRecord() carbon.ConvertEventRefToEventRecord(ev, byref(ev_record)) carbon.AEProcessAppleEvent(byref(ev_record)) if release: carbon.ReleaseEvent(ev) return noErr def _on_ae_quit(self, ae, reply, refcon): self._on_quit() return noErr def _on_quit(self): '''Called when the user tries to quit the application. This is not an actual event handler, it is called in response to Command+Q, the Quit menu item, and the Dock context menu's Quit item. The default implementation calls `EventLoop.exit` on `pyglet.app.event_loop`. ''' app.event_loop.exit() class CarbonScreen(Screen): _initial_mode = None def __init__(self, display, id): self.display = display rect = carbon.CGDisplayBounds(id) super(CarbonScreen, self).__init__(display, int(rect.origin.x), int(rect.origin.y), int(rect.size.width), int(rect.size.height)) self.id = id mode = carbon.CGDisplayCurrentMode(id) kCGDisplayRefreshRate = create_cfstring('RefreshRate') number = carbon.CFDictionaryGetValue(mode, kCGDisplayRefreshRate) refresh = c_long() kCFNumberLongType = 10 carbon.CFNumberGetValue(number, kCFNumberLongType, byref(refresh)) self._refresh_rate = refresh.value def get_gdevice(self): gdevice = POINTER(None)() _oscheck(carbon.DMGetGDeviceByDisplayID(self.id, byref(gdevice), False)) return gdevice def get_matching_configs(self, template): canvas = CarbonCanvas(self.display, self, None) configs = template.match(canvas) # XXX deprecate for config in configs: config.screen = self return configs def get_modes(self): modes_array = carbon.CGDisplayAvailableModes(self.id) n_modes_array = carbon.CFArrayGetCount(modes_array) modes = [] for i in range(n_modes_array): mode = carbon.CFArrayGetValueAtIndex(modes_array, i) modes.append(CarbonScreenMode(self, mode)) return modes def get_mode(self): mode = carbon.CGDisplayCurrentMode(self.id) return CarbonScreenMode(self, mode) def set_mode(self, mode): assert mode.screen is self if not self._initial_mode: self._initial_mode = self.get_mode() _oscheck(carbon.CGDisplayCapture(self.id)) _oscheck(carbon.CGDisplaySwitchToMode(self.id, mode.mode)) self.width = mode.width self.height = mode.height def restore_mode(self): if self._initial_mode: _oscheck(carbon.CGDisplaySwitchToMode(self.id, self._initial_mode.mode)) _oscheck(carbon.CGDisplayRelease(self.id)) class CarbonScreenMode(ScreenMode): def __init__(self, screen, mode): super(CarbonScreenMode, self).__init__(screen) self.mode = mode self.width = self._get_long('Width') self.height = self._get_long('Height') self.depth = self._get_long('BitsPerPixel') self.rate = self._get_long('RefreshRate') def _get_long(self, key): kCFNumberLongType = 10 cfkey = create_cfstring(key) number = carbon.CFDictionaryGetValue(self.mode, cfkey) if not number: return None value = c_long() carbon.CFNumberGetValue(number, kCFNumberLongType, byref(value)) return value.value class CarbonCanvas(Canvas): bounds = None def __init__(self, display, screen, drawable): super(CarbonCanvas, self).__init__(display) self.screen = screen self.drawable = drawable class CarbonFullScreenCanvas(Canvas): # XXX not used any more. def __init__(self, display, screen, width, height): super(CarbonFullScreenCanvas, self).__init__(display) self.screen = screen self.width = width self.height = height
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from pyglet import app from base import Display, Screen, ScreenMode, Canvas from pyglet.libs.darwin import * from pyglet.libs.darwin import _oscheck class CarbonDisplay(Display): # TODO: CarbonDisplay could be per display device, which would make # reporting of screens and available configs more accurate. The number of # Macs with more than one video card is probably small, though. def __init__(self): super(CarbonDisplay, self).__init__() import MacOS if not MacOS.WMAvailable(): raise app.AppException('Window manager is not available. ' \ 'Ensure you run "pythonw", not "python"') self._install_application_event_handlers() def get_screens(self): count = CGDisplayCount() carbon.CGGetActiveDisplayList(0, None, byref(count)) displays = (CGDirectDisplayID * count.value)() carbon.CGGetActiveDisplayList(count.value, displays, byref(count)) return [CarbonScreen(self, id) for id in displays] def _install_application_event_handlers(self): self._carbon_event_handlers = [] self._carbon_event_handler_refs = [] target = carbon.GetApplicationEventTarget() # TODO something with a metaclass or hacky like CarbonWindow # to make this list extensible handlers = [ (self._on_mouse_down, kEventClassMouse, kEventMouseDown), (self._on_apple_event, kEventClassAppleEvent, kEventAppleEvent), (self._on_command, kEventClassCommand, kEventProcessCommand), ] ae_handlers = [ (self._on_ae_quit, kCoreEventClass, kAEQuitApplication), ] # Install the application-wide handlers for method, cls, event in handlers: proc = EventHandlerProcPtr(method) self._carbon_event_handlers.append(proc) upp = carbon.NewEventHandlerUPP(proc) types = EventTypeSpec() types.eventClass = cls types.eventKind = event handler_ref = EventHandlerRef() carbon.InstallEventHandler( target, upp, 1, byref(types), c_void_p(), byref(handler_ref)) self._carbon_event_handler_refs.append(handler_ref) # Install Apple event handlers for method, cls, event in ae_handlers: proc = EventHandlerProcPtr(method) self._carbon_event_handlers.append(proc) upp = carbon.NewAEEventHandlerUPP(proc) carbon.AEInstallEventHandler( cls, event, upp, 0, False) def _on_command(self, next_handler, ev, data): command = HICommand() carbon.GetEventParameter(ev, kEventParamDirectObject, typeHICommand, c_void_p(), sizeof(command), c_void_p(), byref(command)) if command.commandID == kHICommandQuit: self._on_quit() return noErr def _on_mouse_down(self, next_handler, ev, data): # Check for menubar hit position = Point() carbon.GetEventParameter(ev, kEventParamMouseLocation, typeQDPoint, c_void_p(), sizeof(position), c_void_p(), byref(position)) if carbon.FindWindow(position, None) == inMenuBar: # Mouse down in menu bar. MenuSelect() takes care of all # menu tracking and blocks until the menu is dismissed. # Use command events to handle actual menu item invokations. # This function blocks, so tell the event loop it needs to install # a timer. app.event_loop.enter_blocking() carbon.MenuSelect(position) app.event_loop.exit_blocking() # Menu selection has now returned. Remove highlight from the # menubar. carbon.HiliteMenu(0) carbon.CallNextEventHandler(next_handler, ev) return noErr def _on_apple_event(self, next_handler, ev, data): # Somewhat involved way of redispatching Apple event contained # within a Carbon event, described in # http://developer.apple.com/documentation/AppleScript/ # Conceptual/AppleEvents/dispatch_aes_aepg/chapter_4_section_3.html release = False if carbon.IsEventInQueue(carbon.GetMainEventQueue(), ev): carbon.RetainEvent(ev) release = True carbon.RemoveEventFromQueue(carbon.GetMainEventQueue(), ev) ev_record = EventRecord() carbon.ConvertEventRefToEventRecord(ev, byref(ev_record)) carbon.AEProcessAppleEvent(byref(ev_record)) if release: carbon.ReleaseEvent(ev) return noErr def _on_ae_quit(self, ae, reply, refcon): self._on_quit() return noErr def _on_quit(self): '''Called when the user tries to quit the application. This is not an actual event handler, it is called in response to Command+Q, the Quit menu item, and the Dock context menu's Quit item. The default implementation calls `EventLoop.exit` on `pyglet.app.event_loop`. ''' app.event_loop.exit() class CarbonScreen(Screen): _initial_mode = None def __init__(self, display, id): self.display = display rect = carbon.CGDisplayBounds(id) super(CarbonScreen, self).__init__(display, int(rect.origin.x), int(rect.origin.y), int(rect.size.width), int(rect.size.height)) self.id = id mode = carbon.CGDisplayCurrentMode(id) kCGDisplayRefreshRate = create_cfstring('RefreshRate') number = carbon.CFDictionaryGetValue(mode, kCGDisplayRefreshRate) refresh = c_long() kCFNumberLongType = 10 carbon.CFNumberGetValue(number, kCFNumberLongType, byref(refresh)) self._refresh_rate = refresh.value def get_gdevice(self): gdevice = POINTER(None)() _oscheck(carbon.DMGetGDeviceByDisplayID(self.id, byref(gdevice), False)) return gdevice def get_matching_configs(self, template): canvas = CarbonCanvas(self.display, self, None) configs = template.match(canvas) # XXX deprecate for config in configs: config.screen = self return configs def get_modes(self): modes_array = carbon.CGDisplayAvailableModes(self.id) n_modes_array = carbon.CFArrayGetCount(modes_array) modes = [] for i in range(n_modes_array): mode = carbon.CFArrayGetValueAtIndex(modes_array, i) modes.append(CarbonScreenMode(self, mode)) return modes def get_mode(self): mode = carbon.CGDisplayCurrentMode(self.id) return CarbonScreenMode(self, mode) def set_mode(self, mode): assert mode.screen is self if not self._initial_mode: self._initial_mode = self.get_mode() _oscheck(carbon.CGDisplayCapture(self.id)) _oscheck(carbon.CGDisplaySwitchToMode(self.id, mode.mode)) self.width = mode.width self.height = mode.height def restore_mode(self): if self._initial_mode: _oscheck(carbon.CGDisplaySwitchToMode(self.id, self._initial_mode.mode)) _oscheck(carbon.CGDisplayRelease(self.id)) class CarbonScreenMode(ScreenMode): def __init__(self, screen, mode): super(CarbonScreenMode, self).__init__(screen) self.mode = mode self.width = self._get_long('Width') self.height = self._get_long('Height') self.depth = self._get_long('BitsPerPixel') self.rate = self._get_long('RefreshRate') def _get_long(self, key): kCFNumberLongType = 10 cfkey = create_cfstring(key) number = carbon.CFDictionaryGetValue(self.mode, cfkey) if not number: return None value = c_long() carbon.CFNumberGetValue(number, kCFNumberLongType, byref(value)) return value.value class CarbonCanvas(Canvas): bounds = None def __init__(self, display, screen, drawable): super(CarbonCanvas, self).__init__(display) self.screen = screen self.drawable = drawable class CarbonFullScreenCanvas(Canvas): # XXX not used any more. def __init__(self, display, screen, width, height): super(CarbonFullScreenCanvas, self).__init__(display) self.screen = screen self.width = width self.height = height
Python
#!/usr/bin/python # $Id:$ from pyglet import app from pyglet import gl from pyglet import window class Display(object): '''A display device supporting one or more screens. :Ivariables: `name` : str Name of this display, if applicable. `x_screen` : int The X11 screen number of this display, if applicable. :since: pyglet 1.2 ''' name = None x_screen = None def __init__(self, name=None, x_screen=None): '''Create a display connection for the given name and screen. On X11, `name` is of the form ``"hostname:display"``, where the default is usually ``":1"``. On X11, `x_screen` gives the X screen number to use with this display. A pyglet display can only be used with one X screen; open multiple display connections to access multiple X screens. Note that TwinView, Xinerama, xrandr and other extensions present multiple monitors on a single X screen; this is usually the preferred mechanism for working with multiple monitors under X11 and allows each screen to be accessed through a single pyglet `Display`. On platforms other than X11, `name` and `x_screen` are ignored; there is only a single display device on these systems. :Parameters: `name` : str The name of the display to connect to. `x_screen` : int The X11 screen number to use. ''' app.displays.add(self) def get_screens(self): '''Get the available screens. A typical multi-monitor workstation comprises one `Display` with multiple `Screen` s. This method returns a list of screens which can be enumerated to select one for full-screen display. For the purposes of creating an OpenGL config, the default screen will suffice. :rtype: list of `Screen` ''' raise NotImplementedError('abstract') def get_default_screen(self): '''Get the default screen as specified by the user's operating system preferences. :rtype: `Screen` ''' return self.get_screens()[0] def get_windows(self): '''Get the windows currently attached to this display. :rtype: sequence of `Window` ''' return [window for window in app.windows if window.display is self] class Screen(object): '''A virtual monitor that supports fullscreen windows. Screens typically map onto a physical display such as a monitor, television or projector. Selecting a screen for a window has no effect unless the window is made fullscreen, in which case the window will fill only that particular virtual screen. The `width` and `height` attributes of a screen give the current resolution of the screen. The `x` and `y` attributes give the global location of the top-left corner of the screen. This is useful for determining if screens arranged above or next to one another. Use `Display.get_screens` or `Display.get_default_screen` to obtain an instance of this class. :Ivariables: `display` : `Display` Display this screen belongs to. `x` : int Left edge of the screen on the virtual desktop. `y` : int Top edge of the screen on the virtual desktop. `width` : int Width of the screen, in pixels. `height` : int Height of the screen, in pixels. ''' def __init__(self, display, x, y, width, height): self.display = display self.x = x self.y = y self.width = width self.height = height def __repr__(self): return '%s(x=%d, y=%d, width=%d, height=%d)' % \ (self.__class__.__name__, self.x, self.y, self.width, self.height) def get_best_config(self, template=None): '''Get the best available GL config. Any required attributes can be specified in `template`. If no configuration matches the template, `NoSuchConfigException` will be raised. :deprecated: Use `pyglet.gl.Config.match`. :Parameters: `template` : `pyglet.gl.Config` A configuration with desired attributes filled in. :rtype: `pyglet.gl.Config` :return: A configuration supported by the platform that best fulfils the needs described by the template. ''' configs = None if template is None: for template_config in [ gl.Config(double_buffer=True, depth_size=24), gl.Config(double_buffer=True, depth_size=16), None]: try: configs = self.get_matching_configs(template_config) break except NoSuchConfigException: pass else: configs = self.get_matching_configs(template) if not configs: raise window.NoSuchConfigException() return configs[0] def get_matching_configs(self, template): '''Get a list of configs that match a specification. Any attributes specified in `template` will have values equal to or greater in each returned config. If no configs satisfy the template, an empty list is returned. :deprecated: Use `pyglet.gl.Config.match`. :Parameters: `template` : `pyglet.gl.Config` A configuration with desired attributes filled in. :rtype: list of `pyglet.gl.Config` :return: A list of matching configs. ''' raise NotImplementedError('abstract') def get_modes(self): '''Get a list of screen modes supported by this screen. :rtype: list of `ScreenMode` :since: pyglet 1.2 ''' raise NotImplementedError('abstract') def get_mode(self): '''Get the current display mode for this screen. :rtype: `ScreenMode` :since: pyglet 1.2 ''' raise NotImplementedError('abstract') def get_closest_mode(self, width, height): '''Get the screen mode that best matches a given size. If no supported mode exactly equals the requested size, a larger one is returned; or ``None`` if no mode is large enough. :Parameters: `width` : int Requested screen width. `height` : int Requested screen height. :rtype: `ScreenMode` :since: pyglet 1.2 ''' # Best mode is one with smallest resolution larger than width/height, # with depth and refresh rate equal to current mode. current = self.get_mode() best = None for mode in self.get_modes(): # Reject resolutions that are too small if mode.width < width or mode.height < height: continue if best is None: best = mode # Must strictly dominate dimensions if (mode.width <= best.width and mode.height <= best.height and (mode.width < best.width or mode.height < best.height)): best = mode # Preferably match rate, then depth. if mode.width == best.width and mode.height == best.height: points = 0 if mode.rate == current.rate: points += 2 if best.rate == current.rate: points -= 2 if mode.depth == current.depth: points += 1 if best.depth == current.depth: points -= 1 if points > 0: best = mode return best def set_mode(self, mode): '''Set the display mode for this screen. The mode must be one previously returned by `get_mode` or `get_modes`. :Parameters: `mode` : `ScreenMode` Screen mode to switch this screen to. ''' raise NotImplementedError('abstract') def restore_mode(self): '''Restore the screen mode to the user's default. ''' raise NotImplementedError('abstract') class ScreenMode(object): '''Screen resolution and display settings. Applications should not construct `ScreenMode` instances themselves; see `Screen.get_modes`. The `depth` and `rate` variables may be ``None`` if the operating system does not provide relevant data. :Ivariables: `width` : int Width of screen, in pixels. `height` : int Height of screen, in pixels. `depth` : int Pixel color depth, in bits per pixel. `rate` : int Screen refresh rate in Hz. :since: pyglet 1.2 ''' width = None height = None depth = None rate = None def __init__(self, screen): self.screen = screen def __repr__(self): return '%s(width=%r, height=%r, depth=%r, rate=%r)' % ( self.__class__.__name__, self.width, self.height, self.depth, self.rate) class Canvas(object): '''Abstract drawing area. Canvases are used internally by pyglet to represent drawing areas -- either within a window or full-screen. :Ivariables: `display` : `Display` Display this canvas was created on. :since: pyglet 1.2 ''' def __init__(self, display): self.display = display
Python