code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
#!/usr/bin/python
# $Id:$
import unittest
from pyglet.image import atlas
__noninteractive = True
class Rect(object):
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def __repr__(self):
return 'Rect(%d, %d to %d, %d)' % (
self.x1, self.y1, self.x2, self.y2)
def intersects(self, other):
return self.x2 > other.x1 and self.x1 < other.x2 and \
self.y2 > other.y1 and self.y1 < other.y2
class AllocatorEnvironment(object):
def __init__(self, test_case, width, height):
self.test_case = test_case
self.rectes = []
self.allocator = atlas.Allocator(width, height)
def check(self, test_case):
for i, rect in enumerate(self.rectes):
test_case.assertTrue(0 <= rect.x1 < self.allocator.width)
test_case.assertTrue(0 <= rect.x2 <= self.allocator.width)
test_case.assertTrue(0 <= rect.y1 < self.allocator.height)
test_case.assertTrue(0 <= rect.y2 <= self.allocator.height)
for other in self.rectes[i + 1:]:
test_case.assertFalse(rect.intersects(other))
def add(self, width, height):
x, y = self.allocator.alloc(width, height)
self.rectes.append(Rect(x, y, x + width, y + height))
self.check(self.test_case)
def add_fail(self, width, height):
self.test_case.assertRaises(atlas.AllocatorException,
self.allocator.alloc, width, height)
class TestPack(unittest.TestCase):
def test_over_x(self):
env = AllocatorEnvironment(self, 3, 3)
env.add_fail(3, 4)
def test_over_y(self):
env = AllocatorEnvironment(self, 3, 3)
env.add_fail(4, 3)
def test_1(self):
env = AllocatorEnvironment(self, 4, 4)
for i in range(16):
env.add(1, 1)
env.add_fail(1, 1)
def test_2(self):
env = AllocatorEnvironment(self, 3, 3)
env.add(2, 2)
for i in range(4):
env.add(1, 1)
def test_3(self):
env = AllocatorEnvironment(self, 3, 3)
env.add(3, 3)
env.add_fail(1, 1)
def test_4(self):
env = AllocatorEnvironment(self, 5, 4)
for i in range(4):
env.add(2, 2)
env.add_fail(2, 1)
env.add(1, 2)
env.add(1, 2)
env.add_fail(1, 1)
def test_5(self):
env = AllocatorEnvironment(self, 4, 4)
env.add(3, 2)
env.add(4, 2)
env.add(1, 2)
env.add_fail(1, 1)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test rearrangement of color components using the OpenGL color matrix.
The test will be skipped if the GL_ARB_imaging extension is not present.
You should see the RGB test image correctly rendered. Press ESC to
end the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
import sys
from pyglet.gl import gl_info
class TEST_MATRIX_RGB(base_load.TestLoad):
texture_file = 'rgb.png'
def load_image(self):
if not gl_info.have_extension('GL_ARB_imaging'):
print 'GL_ARB_imaging is not present, skipping test.'
self.has_exit = True
else:
# Load image as usual then rearrange components
super(TEST_MATRIX_RGB, self).load_image()
self.image.format = 'GRB'
pixels = self.image.data # forces conversion
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test LA load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk).
You should see the la.png image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
import sys
if sys.platform.startswith('linux'):
from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass
elif sys.platform in ('win32', 'cygwin'):
from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass
elif sys.platform == 'darwin':
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass
else:
from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass
class TEST_PLATFORM_LA_LOAD(base_load.TestLoad):
texture_file = 'la.png'
decoder = dclass()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_8bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_8bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_1bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_1bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGBA save using PIL. You should see rgba.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.image.codecs.pil import PILImageEncoder
class TEST_PIL_RGBA_SAVE(base_save.TestSave):
texture_file = 'rgba.png'
encoder = PILImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from pyglet.gl import *
from pyglet.image import *
from pyglet.window import *
__noninteractive = True
class TestTextureGrid(unittest.TestCase):
def set_grid_image(self, itemwidth, itemheight, rows, cols, rowpad, colpad):
data = ''
color = 1
width = itemwidth * cols + colpad * (cols - 1)
height = itemheight * rows + rowpad * (rows - 1)
for row in range(rows):
rowdata = ''
for col in range(cols):
rowdata += ('%c' % color) * itemwidth
if col < cols - 1:
rowdata += '\0' * colpad
color += 1
data += rowdata * itemheight
if row < rows - 1:
data += (width * '\0') * rowpad
assert len(data) == width * height
self.image = ImageData(width, height, 'L', data)
self.grid = ImageGrid(self.image, rows, cols,
itemwidth, itemheight, rowpad, colpad).texture_sequence
def check_cell(self, cellimage, cellindex):
self.assertTrue(cellimage.width == self.grid.item_width)
self.assertTrue(cellimage.height == self.grid.item_height)
color = '%c' % (cellindex + 1)
cellimage = cellimage.image_data
data = cellimage.get_data('L', cellimage.width)
self.assertTrue(data == color * len(data))
def setUp(self):
self.w = Window(visible=False)
def testSquare(self):
# Test a 3x3 grid with no padding and 4x4 images
rows = cols = 3
self.set_grid_image(4, 4, rows, cols, 0, 0)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testRect(self):
# Test a 2x5 grid with no padding and 3x8 images
rows, cols = 2, 5
self.set_grid_image(3, 8, rows, cols, 0, 0)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testPad(self):
# Test a 5x3 grid with rowpad=3 and colpad=7 and 10x9 images
rows, cols = 5, 3
self.set_grid_image(10, 9, rows, cols, 3, 7)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testTuple(self):
# Test tuple access
rows, cols = 3, 4
self.set_grid_image(5, 5, rows, cols, 0, 0)
for row in range(rows):
for col in range(cols):
self.check_cell(self.grid[(row, col)], row * cols + col)
def testRange(self):
# Test range access
rows, cols = 4, 3
self.set_grid_image(10, 1, rows, cols, 0, 0)
images = self.grid[4:8]
for i, image in enumerate(images):
self.check_cell(image, i + 4)
def testTupleRange(self):
# Test range over tuples
rows, cols = 10, 10
self.set_grid_image(4, 4, rows, cols, 0, 0)
images = self.grid[(3,2):(6,5)]
i = 0
for row in range(3,6):
for col in range(2,5):
self.check_cell(images[i], row * cols + col)
i += 1
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test colour buffer save.
A scene consisting of a single coloured triangle will be rendered. The
colour buffer will then be saved to a stream and loaded as a texture.
You will see the original scene first for up to several seconds before the
buffer image appears (because retrieving and saving the image is a slow
operation). Messages will be printed to stdout indicating what stage is
occuring.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from StringIO import StringIO
import unittest
import base_save
from pyglet.gl import *
from pyglet import image
class TEST_BUFFER_SAVE(base_save.TestSave):
alpha = False
def draw_original(self):
glBegin(GL_TRIANGLES)
glColor4f(1, 0, 0, 1)
glVertex3f(0, 0, -1)
glColor4f(0, 1, 0, 1)
glVertex3f(200, 0, 0)
glColor4f(0, 0, 1, 1)
glVertex3f(0, 200, 1)
glEnd()
glColor4f(1, 1, 1, 1)
def load_texture(self):
print 'Drawing scene...'
self.window.set_visible()
self.window.dispatch_events()
self.draw()
print 'Saving colour image...'
img = image.get_buffer_manager().get_color_buffer()
file = StringIO()
img.save('buffer.png', file)
print 'Loading colour image as texture...'
file.seek(0)
self.saved_texture = image.load('buffer.png', file)
print 'Done.'
self.window.set_visible(False)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB save using PIL. You should see rgb.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.image.codecs.pil import PILImageEncoder
class TEST_PNG_RGB_SAVE(base_save.TestSave):
texture_file = 'rgb.png'
encoder = PILImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test L load using PyPNG. You should see the l.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.png import PNGImageDecoder
class TEST_PNG_L_LOAD(base_load.TestLoad):
texture_file = 'l.png'
decoder = PNGImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB load using PIL. You should see the rgb.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
from pyglet.image.codecs.pil import *
class TEST_PIL_RGB_LOAD(base_load.TestLoad):
texture_file = 'rgb.png'
decoder = PILImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_4bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_4bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGBA save using PIL. You should see rgba.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.image.codecs.pil import PILImageEncoder
class TEST_PIL_RGBA_SAVE(base_save.TestSave):
texture_file = 'rgba.png'
encoder = PILImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGBA load using PIL. You should see the rgba.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
from pyglet.image.codecs.pil import *
class TEST_PIL_RGBA_LOAD(base_load.TestLoad):
texture_file = 'rgba.png'
decoder = PILImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test DXT5 compressed RGBA load from a DDS file. You should see the
rgba_dxt5.dds image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.dds import DDSImageDecoder
class TEST_DDS_RGBA_DXT5(base_load.TestLoad):
texture_file = 'rgba_dxt5.dds'
decoder = DDSImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test colour buffer save.
A scene consisting of a single coloured triangle will be rendered. The
colour buffer will then be saved to a stream and loaded as a texture.
You will see the original scene first for up to several seconds before the
buffer image appears (because retrieving and saving the image is a slow
operation). Messages will be printed to stdout indicating what stage is
occuring.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from StringIO import StringIO
import unittest
import base_save
from pyglet.gl import *
from pyglet import image
class TEST_BUFFER_SAVE(base_save.TestSave):
alpha = False
def draw_original(self):
glBegin(GL_TRIANGLES)
glColor4f(1, 0, 0, 1)
glVertex3f(0, 0, -1)
glColor4f(0, 1, 0, 1)
glVertex3f(200, 0, 0)
glColor4f(0, 0, 1, 1)
glVertex3f(0, 200, 1)
glEnd()
glColor4f(1, 1, 1, 1)
def load_texture(self):
print 'Drawing scene...'
self.window.set_visible()
self.window.dispatch_events()
self.draw()
print 'Saving colour image...'
img = image.get_buffer_manager().get_color_buffer()
file = StringIO()
img.save('buffer.png', file)
print 'Loading colour image as texture...'
file.seek(0)
self.saved_texture = image.load('buffer.png', file)
print 'Done.'
self.window.set_visible(False)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test DXT1 compressed RGB load from a DDS file. You should see the
rgb_dxt1.dds image.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.dds import DDSImageDecoder
class TEST_DDS_RGB_DXT1(base_load.TestLoad):
texture_file = 'rgb_dxt1.dds'
decoder = DDSImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_1bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_1bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Base class for image tests.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from StringIO import StringIO
from os.path import dirname, join
from pyglet.gl import *
from pyglet import image
from pyglet.image import codecs
from pyglet.window import *
from pyglet.window.event import *
from tests.regression import ImageRegressionTestCase
class TestSave(ImageRegressionTestCase):
texture_file = None
original_texture = None
saved_texture = None
show_checkerboard = True
alpha = True
has_exit = False
def on_expose(self):
self.draw()
self.window.flip()
if self.capture_regression_image():
self.has_exit = True
def draw(self):
glClearColor(1, 1, 1, 1)
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
if self.show_checkerboard:
glPushMatrix()
glScalef(self.window.width/float(self.checkerboard.width),
self.window.height/float(self.checkerboard.height),
1.)
glMatrixMode(GL_TEXTURE)
glPushMatrix()
glScalef(self.window.width/float(self.checkerboard.width),
self.window.height/float(self.checkerboard.height),
1.)
glMatrixMode(GL_MODELVIEW)
self.checkerboard.blit(0, 0, 0)
glMatrixMode(GL_TEXTURE)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
self.draw_original()
self.draw_saved()
def draw_original(self):
if self.original_texture:
self.original_texture.blit(
self.window.width / 4 - self.original_texture.width / 2,
(self.window.height - self.original_texture.height) / 2,
0)
def draw_saved(self):
if self.saved_texture:
self.saved_texture.blit(
self.window.width * 3 / 4 - self.saved_texture.width / 2,
(self.window.height - self.saved_texture.height) / 2,
0)
def load_texture(self):
if self.texture_file:
self.texture_file = join(dirname(__file__), self.texture_file)
self.original_texture = image.load(self.texture_file).texture
file = StringIO()
self.original_texture.save(self.texture_file, file,
encoder=self.encoder)
file.seek(0)
self.saved_texture = image.load(self.texture_file, file).texture
def create_window(self):
width, height = 800, 600
return Window(width, height, visible=False)
def test_save(self):
self.window = w = self.create_window()
w.push_handlers(self)
self.screen = image.get_buffer_manager().get_color_buffer()
self.checkerboard = image.create(32, 32, image.CheckerImagePattern())
self.load_texture()
if self.alpha:
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
w.set_visible()
while not (w.has_exit or self.has_exit):
w.dispatch_events()
w.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGBA load using PyPNG. You should see the rgba.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
from pyglet.image.codecs.png import PNGImageDecoder
class TEST_PNG_RGBA_LOAD(base_load.TestLoad):
texture_file = 'rgba.png'
decoder = PNGImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test L load using PIL. You should see the la.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.pil import *
class TEST_PIL_L(base_load.TestLoad):
texture_file = 'l.png'
decoder = PILImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB save using PIL. You should see rgb.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.image.codecs.pil import PILImageEncoder
class TEST_PNG_RGB_SAVE(base_save.TestSave):
texture_file = 'rgb.png'
encoder = PILImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test colour buffer copy to texture.
A scene consisting of a single coloured triangle will be rendered. The
colour buffer will then be saved to a stream and loaded as a texture.
You will see the original scene first for up to several seconds before the
buffer image appears (because retrieving and saving the image is a slow
operation). Messages will be printed to stdout indicating what stage is
occuring.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from StringIO import StringIO
import unittest
import base_save
from pyglet.gl import *
from pyglet import image
class TEST_BUFFER_COPY(base_save.TestSave):
alpha = False
def draw_original(self):
glBegin(GL_TRIANGLES)
glColor4f(1, 0, 0, 1)
glVertex3f(0, 0, -1)
glColor4f(0, 1, 0, 1)
glVertex3f(200, 0, 0)
glColor4f(0, 0, 1, 1)
glVertex3f(0, 200, 1)
glEnd()
glColor4f(1, 1, 1, 1)
def load_texture(self):
print 'Drawing scene...'
self.window.set_visible()
self.window.dispatch_events()
self.draw()
print 'Copying colour image...'
self.saved_texture = \
image.get_buffer_manager().get_color_buffer().texture
print 'Done.'
self.window.set_visible(False)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Base class for image tests.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from os.path import dirname, join
from pyglet.gl import *
from pyglet import image
from pyglet.image import codecs
from pyglet.window import *
from pyglet.window.event import *
from tests.regression import ImageRegressionTestCase
class TestLoad(ImageRegressionTestCase):
texture_file = None
image = None
texture = None
show_checkerboard = True
alpha = True
has_exit = False
decoder = None
def on_expose(self):
glClearColor(1, 1, 1, 1)
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
if self.show_checkerboard:
glPushMatrix()
glScalef(self.window.width/float(self.checkerboard.width),
self.window.height/float(self.checkerboard.height),
1.)
glMatrixMode(GL_TEXTURE)
glPushMatrix()
glScalef(self.window.width/float(self.checkerboard.width),
self.window.height/float(self.checkerboard.height),
1.)
glMatrixMode(GL_MODELVIEW)
self.checkerboard.blit(0, 0, 0)
glMatrixMode(GL_TEXTURE)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
if self.texture:
glPushMatrix()
glTranslatef((self.window.width - self.texture.width) / 2,
(self.window.height - self.texture.height) / 2,
0)
self.texture.blit(0, 0, 0)
glPopMatrix()
self.window.flip()
if self.capture_regression_image():
self.has_exit = True
def load_image(self):
if self.texture_file:
self.texture_file = join(dirname(__file__), self.texture_file)
self.image = image.load(self.texture_file, decoder=self.decoder)
def test_load(self):
width, height = 800, 600
self.window = w = Window(width, height, visible=False)
w.push_handlers(self)
self.screen = image.get_buffer_manager().get_color_buffer()
self.checkerboard = image.create(32, 32, image.CheckerImagePattern())
self.load_image()
if self.image:
self.texture = self.image.texture
if self.alpha:
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
w.set_visible()
while not (w.has_exit or self.has_exit):
w.dispatch_events()
w.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test LA save using PyPNG. You should see la.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_save
from pyglet.image.codecs.png import PNGImageEncoder
class TEST_PNG_LA_SAVE(base_save.TestSave):
texture_file = 'la.png'
encoder = PNGImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test L load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk).
You should see the l.png image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
import sys
if sys.platform.startswith('linux'):
from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass
elif sys.platform in ('win32', 'cygwin'):
from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass
elif sys.platform == 'darwin':
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass
else:
from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass
class TEST_PLATFORM_L_LOAD(base_load.TestLoad):
texture_file = 'l.png'
decoder = dclass()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test LA save using PIL. You should see la.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_save
from pyglet.image.codecs.pil import PILImageEncoder
class TEST_PIL_LA_SAVE(base_save.TestSave):
texture_file = 'la.png'
encoder = PILImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test L save using PIL. You should see l.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_save
from pyglet.image.codecs.pil import PILImageEncoder
class TEST_PIL_L_SAVE(base_save.TestSave):
texture_file = 'l.png'
encoder = PILImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from pyglet.gl import *
from pyglet.image import *
from pyglet.window import *
__noninteractive = True
class TestTextureGrid(unittest.TestCase):
def set_grid_image(self, itemwidth, itemheight, rows, cols, rowpad, colpad):
data = ''
color = 1
width = itemwidth * cols + colpad * (cols - 1)
height = itemheight * rows + rowpad * (rows - 1)
for row in range(rows):
rowdata = ''
for col in range(cols):
rowdata += ('%c' % color) * itemwidth
if col < cols - 1:
rowdata += '\0' * colpad
color += 1
data += rowdata * itemheight
if row < rows - 1:
data += (width * '\0') * rowpad
assert len(data) == width * height
self.image = ImageData(width, height, 'L', data)
self.grid = ImageGrid(self.image, rows, cols,
itemwidth, itemheight, rowpad, colpad).texture_sequence
def check_cell(self, cellimage, cellindex):
self.assertTrue(cellimage.width == self.grid.item_width)
self.assertTrue(cellimage.height == self.grid.item_height)
color = '%c' % (cellindex + 1)
cellimage = cellimage.image_data
data = cellimage.get_data('L', cellimage.width)
self.assertTrue(data == color * len(data))
def setUp(self):
self.w = Window(visible=False)
def testSquare(self):
# Test a 3x3 grid with no padding and 4x4 images
rows = cols = 3
self.set_grid_image(4, 4, rows, cols, 0, 0)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testRect(self):
# Test a 2x5 grid with no padding and 3x8 images
rows, cols = 2, 5
self.set_grid_image(3, 8, rows, cols, 0, 0)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testPad(self):
# Test a 5x3 grid with rowpad=3 and colpad=7 and 10x9 images
rows, cols = 5, 3
self.set_grid_image(10, 9, rows, cols, 3, 7)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testTuple(self):
# Test tuple access
rows, cols = 3, 4
self.set_grid_image(5, 5, rows, cols, 0, 0)
for row in range(rows):
for col in range(cols):
self.check_cell(self.grid[(row, col)], row * cols + col)
def testRange(self):
# Test range access
rows, cols = 4, 3
self.set_grid_image(10, 1, rows, cols, 0, 0)
images = self.grid[4:8]
for i, image in enumerate(images):
self.check_cell(image, i + 4)
def testTupleRange(self):
# Test range over tuples
rows, cols = 10, 10
self.set_grid_image(4, 4, rows, cols, 0, 0)
images = self.grid[(3,2):(6,5)]
i = 0
for row in range(3,6):
for col in range(2,5):
self.check_cell(images[i], row * cols + col)
i += 1
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test depth buffer save.
A scene consisting of a single coloured triangle will be rendered. The
depth buffer will then be saved to a stream and loaded as a texture.
You will see the original scene first for up to several seconds before the
depth buffer image appears (because retrieving and saving the image is
a slow operation). Messages will be printed to stdout indicating
what stage is occuring.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from StringIO import StringIO
import unittest
import base_save
from pyglet.gl import *
from pyglet import image
class TEST_DEPTH_SAVE(base_save.TestSave):
alpha = False
def draw_original(self):
glClear(GL_DEPTH_BUFFER_BIT)
glEnable(GL_DEPTH_TEST)
glBegin(GL_TRIANGLES)
glColor4f(1, 0, 0, 1)
glVertex3f(0, 0, -1)
glColor4f(0, 1, 0, 1)
glVertex3f(200, 0, 0)
glColor4f(0, 0, 1, 1)
glVertex3f(0, 200, 1)
glEnd()
glDisable(GL_DEPTH_TEST)
glColor4f(1, 1, 1, 1)
def load_texture(self):
print 'Drawing scene...'
self.window.set_visible()
self.window.dispatch_events()
self.draw()
print 'Saving depth image...'
img = image.get_buffer_manager().get_depth_buffer()
file = StringIO()
img.save('buffer.png', file)
print 'Loading depth image as texture...'
file.seek(0)
self.saved_texture = image.load('buffer.png', file)
print 'Done.'
self.window.set_visible(False)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from pyglet.gl import *
from pyglet.image import *
from pyglet.window import *
__noninteractive = True
class TestTexture3D(unittest.TestCase):
def create_image(self, width, height, color):
data = ('%c' % color) * (width * height)
return ImageData(width, height, 'L', data)
def check_image(self, image, width, height, color):
self.assertTrue(image.width == width)
self.assertTrue(image.height == height)
color = '%c' % (color)
image = image.image_data
data = image.get_data('L', image.width)
self.assertTrue(data == color * len(data))
def set_grid_image(self, itemwidth, itemheight, rows, cols, rowpad, colpad):
data = ''
color = 1
width = itemwidth * cols + colpad * (cols - 1)
height = itemheight * rows + rowpad * (rows - 1)
for row in range(rows):
rowdata = ''
for col in range(cols):
rowdata += ('%c' % color) * itemwidth
if col < cols - 1:
rowdata += '\0' * colpad
color += 1
data += rowdata * itemheight
if row < rows - 1:
data += (width * '\0') * rowpad
assert len(data) == width * height
self.image = ImageData(width, height, 'L', data)
grid = ImageGrid(self.image, rows, cols,
itemwidth, itemheight, rowpad, colpad)
self.grid = Texture3D.create_for_image_grid(grid)
def check_cell(self, cellimage, cellindex):
self.assertTrue(cellimage.width == self.grid.item_width)
self.assertTrue(cellimage.height == self.grid.item_height)
color = '%c' % (cellindex + 1)
cellimage = cellimage.image_data
data = cellimage.get_data('L', cellimage.width)
self.assertTrue(data == color * len(data))
def setUp(self):
self.w = Window(visible=False)
def test2(self):
# Test 2 images of 32x32
images = [self.create_image(32, 32, i+1) for i in range(2)]
texture = Texture3D.create_for_images(images)
self.assertTrue(len(texture) == 2)
for i in range(2):
self.check_image(texture[i], 32, 32, i+1)
def test5(self):
# test 5 images of 31x94 (power2 issues)
images = [self.create_image(31, 94, i+1) for i in range(5)]
texture = Texture3D.create_for_images(images)
self.assertTrue(len(texture) == 5)
for i in range(5):
self.check_image(texture[i], 31, 94, i+1)
def testSet(self):
# test replacing an image
images = [self.create_image(32, 32, i+1) for i in range(3)]
texture = Texture3D.create_for_images(images)
self.assertTrue(len(texture) == 3)
for i in range(3):
self.check_image(texture[i], 32, 32, i+1)
texture[1] = self.create_image(32, 32, 87)
self.check_image(texture[0], 32, 32, 1)
self.check_image(texture[1], 32, 32, 87)
self.check_image(texture[2], 32, 32, 3)
def testSquare(self):
# Test a 3x3 grid with no padding and 4x4 images
rows = cols = 3
self.set_grid_image(4, 4, rows, cols, 0, 0)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testRect(self):
# Test a 2x5 grid with no padding and 3x8 images
rows, cols = 2, 5
self.set_grid_image(3, 8, rows, cols, 0, 0)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testPad(self):
# Test a 5x3 grid with rowpad=3 and colpad=7 and 10x9 images
rows, cols = 5, 3
self.set_grid_image(10, 9, rows, cols, 3, 7)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the checkerboard pattern looks correct.
One window will open, it should show one instance of the checkerboard
pattern in two levels of grey.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from pyglet.gl import *
from pyglet import image
from pyglet.window import *
from pyglet.window.event import *
from tests.regression import ImageRegressionTestCase
class TEST_CHECKERBOARD(ImageRegressionTestCase):
has_exit = False
def on_expose(self):
glClearColor(1, 1, 1, 1)
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
self.texture.blit(0, 0, 0)
self.window.flip()
if self.capture_regression_image():
self.has_exit = True
def test_main(self):
width, height = 200, 200
self.window = w = Window(width, height, visible=False)
w.push_handlers(self)
self.texture = image.create(32, 32, image.CheckerImagePattern()).texture
w.set_visible()
while not (w.has_exit or self.has_exit):
w.dispatch_events()
w.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_16bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_16bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test L save using PyPNG. You should see l.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_save
from pyglet.image.codecs.png import PNGImageEncoder
class TEST_PNG_L_SAVE(base_save.TestSave):
texture_file = 'l.png'
encoder = PNGImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB save using PyPNG. You should see rgb.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.image.codecs.png import PNGImageEncoder
class TEST_PNG_RGB_SAVE(base_save.TestSave):
texture_file = 'rgb.png'
encoder = PNGImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_8bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_8bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGBA load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk).
You should see the rgba.png image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
import sys
if sys.platform.startswith('linux'):
from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass
elif sys.platform in ('win32', 'cygwin'):
from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass
elif sys.platform == 'darwin':
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass
else:
from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass
class TEST_PLATFORM_RGBA_LOAD(base_load.TestLoad):
texture_file = 'rgba.png'
decoder = dclass()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test framework for pyglet. Reads details of components and capabilities
from a requirements document, runs the appropriate unit tests.
How to Run the Tests
--------------------
::
python tests/test.py top app graphics clock resource # these all run automatically
python tests/test.py font media text
python tests/test.py image
python tests/test.py window
Because the tests are interactive, they can take quite a while to complete. The
'window' section in particular takes a long time. It can be frustrating to get
almost through the tests and then something gets messed up, so we suggest you
run the tests in sections as listed above. If you are curious, the sections are
defined in tests/plan.txt.
Here are the different sections and how long they take.
=========== ===========
Section Time to Run
=========== ===========
top automatic
app automatic
graphics automatic
clock automatic
resource automatic
font 1 minute
media 1 minute
text 1 minute
image 5 minutes
window 10 minutes
=========== ===========
Overview
--------
First, some definitions:
Test case:
A single test, implemented by a Python module in the tests/ directory.
Tests can be interactive (requiring the user to pass or fail them) or
non-interactive (the test passes or fails itself).
Section:
A list of test cases to be run in a specified order. Sections can
also contain other sections to an arbitrary level.
Capability:
A capability is a tag that can be applied to a test-case, which specifies
a particular instance of the test. The tester can select which
capabilities are present on their system; and only test cases matching
those capabilities will be run.
There are platform capabilities "WIN", "OSX" and "X11", which are
automatically selected by default.
The "DEVELOPER" capability is used to mark test cases which test a feature
under active development.
The "GENERIC" capability signifies that the test case is equivalent under
all platforms, and is selected by default.
Other capabilities can be specified and selected as needed. For example,
we may wish to use an "NVIDIA" or "ATI" capability to specialise a
test-case for a particular video card make.
Some tests generate regression images if enabled, so you will only
need to run through the interactive procedure once. During
subsequent runs the image shown on screen will be compared with the
regression images and passed automatically if they match. There are
command line options for enabling this feature.Literal block
By default regression images are saved in tests/regression/images/
Running tests
-------------
The test procedure is interactive (this is necessary to facilitate the
many GUI-related tests, which cannot be completely automated). With no
command-line arguments, all test cases in all sections will be run::
python tests/test.py
Before each test, a description of the test will be printed, including
some information of what you should look for, and what interactivityLiteral block
is provided (including how to stop the test). Press ENTER to begin
the test.
When the test is complete, assuming there were no detectable errors
(for example, failed assertions or an exception), you will be asked
to enter a [P]ass or [F]ail. You should Fail the test if the behaviour
was not as described, and enter a short reason.
Details of each test session are logged for future use.
Command-line options:
`--plan=`
Specify the test plan file (defaults to tests/plan.txt)
`--test-root=`
Specify the top-level directory to look for unit tests in (defaults
to test/)
`--capabilities=`
Specify the capabilities to select, comma separated. By default this
only includes your operating system capability (X11, WIN or OSX) and
GENERIC.
`--log-level=`
Specify the minimum log level to write (defaults to 10: info)
`--log-file=`
Specify log file to write to (defaults to "pyglet.%d.log")
`--regression-capture`
Save regression images to disk. Use this only if the tests have
already been shown to pass.
`--regression-check`
Look for a regression image on disk instead of prompting the user for
passage. If a regression image is found, it is compared with the test
case using the tolerance specified below. Recommended only for
developers.
`--regression-tolerance=`
Specify the tolerance when comparing a regression image. A value of
2, for example, means each sample component must be +/- 2 units
of the regression image. Tolerance of 0 means images must be identical,
tolerance of 256 means images will always match (if correct dimensions).
Defaults to 2.
`--regression-path=`
Specify the directory to store and look for regression images.
Defaults to tests/regression/images/
`--developer`
Selects the DEVELOPER capability.
`--no-interactive=`
Don't write descriptions or prompt for confirmation; just run each
test in succcession.
After the command line options, you can specify a list of sections or test
cases to run.
Examples
--------
python tests/test.py --capabilities=GENERIC,NVIDIA,WIN window
Runs all tests in the window section with the given capabilities.
Test just the FULLSCREEN_TOGGLE test case without prompting for input (useful
for development).
python tests/image/PIL_RGBA_SAVE.py
Run a single test outside of the test harness. Handy for development; it
is equivalent to specifying --no-interactive.
Writing tests
-------------
Add the test case to the appropriate section in the test plan (plan.txt).
Create one unit test script per test case. For example, the test for
window.FULLSCREEN_TOGGLE is located at::
tests/window/FULLSCREEN_TOGGLE.py
The test file must contain:
- A module docstring describing what the test does and what the user should
look for.
- One or more subclasses of unittest.TestCase.
- No other module-level code, except perhaps an if __name__ == '__main__'
condition for running tests stand-alone.
- Optionally, the attribute "__noninteractive = True" to specify that
the test is not interactive; doesn't require user intervention.
During development, test cases should be marked with DEVELOPER. Once finished
add the WIN, OSX and X11 capabilities, or GENERIC if it's platform
independent.
Writing regression tests
------------------------
Your test case should subclass tests.regression.ImageRegressionTestCase
instead of unitttest.TestCase. At the point where the buffer (window
image) should be checked/saved, call self.capture_regression_image().
If this method returns True, you can exit straight away (regression
test passed), otherwise continue running interactively (regression image
was captured, wait for user confirmation). You can call
capture_regression_image() several times; only the final image will be
used.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import array
import logging
import os
import optparse
import re
import sys
import time
import unittest
# So we can find tests.regression and ensure local pyglet copy is tested.
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
import tests.regression
import pyglet.image
regressions_path = os.path.join(os.path.dirname(__file__),
'regression', 'images')
class TestCase(object):
def __init__(self, name):
self.name = name
self.short_name = name.split('.')[-1]
self.capabilities = set()
def get_module_filename(self, root=''):
path = os.path.join(*self.name.split('.'))
return '%s.py' % os.path.join(root, path)
def get_module(self, root=''):
name = 'tests.%s' % self.name
module = __import__(name)
for c in name.split('.')[1:]:
module = getattr(module, c)
return module
def get_regression_image_filename(self):
return os.path.join(regressions_path, '%s.png' % self.name)
def test(self, options):
if not options.capabilities.intersection(self.capabilities):
return
options.log.info('Testing %s.', self)
if options.pretend:
return
module = None
try:
module = self.get_module(options.test_root)
except IOError:
options.log.warning('No test exists for %s', self)
except Exception:
options.log.exception('Cannot load test for %s', self)
if not module:
return
module_interactive = options.interactive
if hasattr(module, '__noninteractive') and \
getattr(module, '__noninteractive'):
module_interactive = False
if options.regression_check and \
os.path.exists(self.get_regression_image_filename()):
result = RegressionCheckTestResult(
self, options.regression_tolerance)
module_interactive = False
elif options.regression_capture:
result = RegressionCaptureTestResult(self)
else:
result = StandardTestResult(self)
print '-' * 78
options.completed_tests += 1
print ("Running Test: %s (%d/%d)\n" % (self, options.completed_tests, options.num_tests))
if module.__doc__:
print ' ' + module.__doc__.replace('\n','\n ')
if module_interactive:
raw_input('Press return to begin test...')
suite = unittest.TestLoader().loadTestsFromModule(module)
options.log.info('Begin unit tests for %s', self)
suite(result)
for failure in result.failures:
options.log.error('Failure in %s', self)
options.log.error(failure[1])
for error in result.errors:
options.log.error('Error in %s', self)
options.log.error(error[1])
options.log.info('%d tests run', result.testsRun)
num_failures = len(result.failures)
num_errors = len(result.errors)
if num_failures or num_errors:
print '%d Failures and %d Errors detected.' % (num_failures, num_errors)
if (module_interactive and
len(result.failures) == 0 and
len(result.errors) == 0):
# print module.__doc__
user_result = raw_input('[P]assed test, [F]ailed test: ')
if user_result and user_result.strip()[0] in ('F', 'f'):
print 'Enter failure description: '
description = raw_input('> ')
options.log.error('User marked fail for %s', self)
options.log.error(description)
else:
options.log.info('User marked pass for %s', self)
result.setUserPass()
def __repr__(self):
return 'TestCase(%s)' % self.name
def __str__(self):
return self.name
def __cmp__(self, other):
return cmp(str(self), str(other))
def num_tests(self):
return 1
class TestSection(object):
def __init__(self, name):
self.name = name
self.children = []
def add(self, child):
# child can be TestSection or TestCase
self.children.append(child)
def test(self, options):
for child in self.children:
child.test(options)
def __repr__(self):
return 'TestSection(%s)' % self.name
def num_tests(self):
return sum([c.num_tests() for c in self.children])
class TestPlan(TestSection):
def __init__(self):
self.root = None
self.names = {}
@classmethod
def from_file(cls, file):
plan = TestPlan()
plan.root = TestSection('{root}')
plan.root.indent = None
# Section stack
sections = [plan.root]
if not hasattr(file, 'read'):
file = open(file, 'r')
line_number = 0
for line in file:
line_number += 1
# Skip empty lines
if not line.strip():
continue
# Skip comments
if line[0] == '#':
continue
indent = len(line) - len(line.lstrip())
while (sections and sections[-1].indent and
sections[-1].indent > indent):
sections.pop()
if sections[-1].indent is None:
sections[-1].indent = indent
if sections[-1].indent != indent:
raise Exception('Indentation mismatch line %d' % line_number)
if '.' in line:
tokens = line.strip().split()
test_case = TestCase(tokens[0])
test_case.capabilities = set(tokens[1:])
sections[-1].add(test_case)
plan.names[test_case.name] = test_case
plan.names[test_case.short_name] = test_case
else:
section = TestSection(line.strip())
section.indent = None
sections[-1].add(section)
sections.append(section)
plan.names[section.name] = section
return plan
class StandardTestResult(unittest.TestResult):
def __init__(self, component):
super(StandardTestResult, self).__init__()
def setUserPass(self):
pass
class RegressionCaptureTestResult(unittest.TestResult):
def __init__(self, component):
super(RegressionCaptureTestResult, self).__init__()
self.component = component
self.captured_image = None
def startTest(self, test):
super(RegressionCaptureTestResult, self).startTest(test)
if isinstance(test, tests.regression.ImageRegressionTestCase):
test._enable_regression_image = True
def addSuccess(self, test):
super(RegressionCaptureTestResult, self).addSuccess(test)
assert self.captured_image is None
if isinstance(test, tests.regression.ImageRegressionTestCase):
self.captured_image = test._captured_image
def setUserPass(self):
if self.captured_image:
filename = self.component.get_regression_image_filename()
self.captured_image.save(filename)
logging.getLogger().info('Wrote regression image %s' % filename)
class Regression(Exception):
pass
def buffer_equal(a, b, tolerance=0):
if tolerance == 0:
return a == b
if len(a) != len(b):
return False
a = array.array('B', a)
b = array.array('B', b)
for i in range(len(a)):
if abs(a[i] - b[i]) > tolerance:
return False
return True
class RegressionCheckTestResult(unittest.TestResult):
def __init__(self, component, tolerance):
super(RegressionCheckTestResult, self).__init__()
self.filename = component.get_regression_image_filename()
self.regression_image = pyglet.image.load(self.filename)
self.tolerance = tolerance
def startTest(self, test):
super(RegressionCheckTestResult, self).startTest(test)
if isinstance(test, tests.regression.ImageRegressionTestCase):
test._enable_regression_image = True
test._enable_interactive = False
logging.getLogger().info('Using regression %s' % self.filename)
def addSuccess(self, test):
# Check image
ref_image = self.regression_image.image_data
this_image = test._captured_image.image_data
this_image.format = ref_image.format
this_image.pitch = ref_image.pitch
if this_image.width != ref_image.width:
self.addFailure(test,
'Buffer width does not match regression image')
elif this_image.height != ref_image.height:
self.addFailure(test,
'Buffer height does not match regression image')
elif not buffer_equal(this_image.data, ref_image.data,
self.tolerance):
self.addFailure(test,
'Buffer does not match regression image')
else:
super(RegressionCheckTestResult, self).addSuccess(test)
def addFailure(self, test, err):
err = Regression(err)
super(RegressionCheckTestResult, self).addFailure(test, (Regression,
err, []))
def main():
capabilities = ['GENERIC']
platform_capabilities = {
'linux': 'X11',
'linux2': 'X11',
'linux3': 'X11',
'win32': 'WIN',
'cygwin': 'WIN',
'darwin': 'OSX'
}
if sys.platform in platform_capabilities:
capabilities.append(platform_capabilities[sys.platform])
script_root = os.path.dirname(__file__)
plan_filename = os.path.normpath(os.path.join(script_root, 'plan.txt'))
test_root = script_root
op = optparse.OptionParser()
op.usage = 'test.py [options] [components]'
op.add_option('--plan', help='test plan file', default=plan_filename)
op.add_option('--test-root', default=script_root,
help='directory containing test cases')
op.add_option('--capabilities', help='selected test capabilities',
default=','.join(capabilities))
op.add_option('--log-level', help='verbosity of logging',
default=10, type='int')
op.add_option('--log-file', help='log to FILE', metavar='FILE',
default='pyglet.%d.log')
op.add_option('--regression-path', metavar='DIR', default=regressions_path,
help='locate regression images in DIR')
op.add_option('--regression-tolerance', type='int', default=2,
help='tolerance for comparing regression images')
op.add_option('--regression-check', action='store_true',
help='enable image regression checks')
op.add_option('--regression-capture', action='store_true',
help='enable image regression capture')
op.add_option('--no-interactive', action='store_false', default=True,
dest='interactive', help='disable interactive prompting')
op.add_option('--developer', action='store_true',
help='add DEVELOPER capability')
op.add_option('--pretend', action='store_true',
help='print selected test cases only')
options, args = op.parse_args()
options.capabilities = set(options.capabilities.split(','))
if options.developer:
options.capabilities.add('DEVELOPER')
if options.regression_capture:
try:
os.makedirs(regressions_path)
except OSError:
pass
if '%d' in options.log_file:
i = 1
while os.path.exists(options.log_file % i):
i += 1
options.log_file = options.log_file % i
print 'Test results are saved in log file:', options.log_file
logging.basicConfig(filename=options.log_file, level=options.log_level, format='%(levelname)s %(message)s')
options.log = logging.getLogger()
options.log.info('Beginning test at %s', time.ctime())
options.log.info('Capabilities are: %s', ', '.join(options.capabilities))
options.log.info('sys.platform = %s', sys.platform)
options.log.info('pyglet.version = %s', pyglet.version)
options.log.info('Reading test plan from %s', options.plan)
plan = TestPlan.from_file(options.plan)
errors = False
if args:
components = []
for arg in args:
try:
component = plan.names[arg]
components.append(component)
except KeyError:
options.log.error('Unknown test case or section "%s"', arg)
errors = True
else:
components = [plan.root]
if not errors:
options.num_tests = sum([c.num_tests() for c in components])
options.completed_tests = 0
for component in components:
component.test(options)
print '-' * 78
print 'Test results are saved in log file:', options.log_file
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
'''Test that inline elements can have their style changed, even after text
has been deleted before them. [This triggers bug 538 if it has not yet been fixed.]
To run the test, delete the first line, one character at a time,
verifying that the element remains visible and no tracebacks are
printed to the console.
Press ESC to end the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import pyglet
from pyglet.text import caret, document, layout
doctext = '''ELEMENT.py test document.
PLACE CURSOR AT THE END OF THE ABOVE LINE, AND DELETE ALL ITS TEXT,
BY PRESSING THE DELETE KEY REPEATEDLY.
IF THIS WORKS OK, AND THE ELEMENT (GRAY RECTANGLE) WITHIN THIS LINE
[element here]
REMAINS VISIBLE BETWEEN THE SAME CHARACTERS, WITH NO ASSERTIONS PRINTED TO
THE CONSOLE, THE TEST PASSES.
(In code with bug 538, the element sometimes moves within the text, and
eventually there is an assertion failure. Note that there is another bug,
unrelated to this one, which sometimes causes the first press of the delete
key to be ignored.)
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce venenatis
pharetra libero. Phasellus lacinia nisi feugiat felis. Sed id magna in nisl
cursus consectetuer. Aliquam aliquam lectus eu magna. Praesent sit amet ipsum
vitae nisl mattis commodo. Aenean pulvinar facilisis lectus. Phasellus sodales
risus sit amet lectus. Suspendisse in turpis. Vestibulum ac mi accumsan eros
commodo tincidunt. Nullam velit. In pulvinar, dui sit amet ullamcorper dictum,
dui risus ultricies nisl, a dignissim sapien enim sit amet tortor.
Pellentesque fringilla, massa sit amet bibendum blandit, pede leo commodo mi,
eleifend feugiat neque tortor dapibus mauris. Morbi nunc arcu, tincidunt vel,
blandit non, iaculis vel, libero. Vestibulum sed metus vel velit scelerisque
varius. Vivamus a tellus. Proin nec orci vel elit molestie venenatis. Aenean
fringilla, lorem vel fringilla bibendum, nibh mi varius mi, eget semper ipsum
ligula ut urna. Nullam tempor convallis augue. Sed at dui.
'''
element_index = doctext.index('[element here]')
doctext = doctext.replace('[element here]', '')
class TestElement(document.InlineElement):
vertex_list = None
def place(self, layout, x, y):
## assert layout.document.text[self._position] == '\x00'
### in bug 538, this fails after two characters are deleted.
self.vertex_list = layout.batch.add(4, pyglet.gl.GL_QUADS,
layout.top_group,
'v2i',
('c4B', [200, 200, 200, 255] * 4))
y += self.descent
w = self.advance
h = self.ascent - self.descent
self.vertex_list.vertices[:] = (x, y,
x + w, y,
x + w, y + h,
x, y + h)
def remove(self, layout):
self.vertex_list.delete()
del self.vertex_list
class TestWindow(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.document = pyglet.text.decode_attributed(doctext)
for i in [element_index]:
self.document.insert_element(i, TestElement(60, -10, 70))
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_draw(self):
pyglet.gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == pyglet.window.key.TAB:
self.caret.on_text('\t')
self.document.set_style(0, len(self.document.text), dict(bold = None)) ### trigger bug 538
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(##resizable=True,
visible=False)
self.window.set_visible()
pyglet.app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that HTML data is decoded into a formatted document.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: ELEMENT.py 1764 2008-02-16 05:24:46Z Alex.Holkner $'
import unittest
import pyglet
from pyglet.text import caret, document, layout
doctext = '''
<html>
<head>
(metadata including title is not displayed.)
<title>Test document</title>
</head>
<body>
<h1>HTML test document</h1>
<p>Several paragraphs of HTML formatted text follow. Ensure they are
formatted as they are described. Here is a copyright symbol: © and
again, using hexadecimal ref: ©.</p>
<P>This paragraph has some <b>bold</b> and <i>italic</i> and <b><i>bold
italic</b> text. <!-- i tag does not need to be closed -->
<p>This paragraph has some <em>emphasis</em> and <strong>strong</strong>
and <em><strong>emphatic strong</em> text.
<p>This paragraph demonstrates superscript: a<sup>2</sup> + b<sup>2</sup>
= c<sup>2</sup>; and subscript: H<sub>2</sub>O.
<p>This paragraph uses the <font> element:
<font face="Courier New">Courier New</font>, <font size=1>size 1</font>,
<font size=2>size 2</font>, <font size=3>size 3</font>, <font size=4>size
4</font>, <font size=5>size 5</font>, <font size=6>size 6</font>, <font
size=7>size 7</font>.
<p>This paragraph uses relative sizes: <font size=5>size 5<font
size=-2>size 3</font><!--<font size=+1>size 6</font>--></font>
<p>Font color changes to <font color=red>red</font>, <font
color=green>green</font> and <font color=#0f0fff>pastel blue using a
hexidecimal number</font>.
<p><u>This text is underlined</u>. <font color=green><u>This text is
underlined and green.</u></font>
<h1>Heading 1
<h2>Heading 2
<h3>Heading 3
<h4>Heading 4
<h5>Heading 5
<h6>Heading 6
<p align=center>Centered paragraph.
<p align=right>Right-aligned paragraph.
<div><div> element instead of paragraph.
<div>This sentence should start a new paragraph, as the div is nested.
</div>
This sentence should start a new paragraph, as the nested div was
closed.
</div>
<pre>This text is preformatted.
Hard line breaks
Indentation. <b>Inline formatting</b> is still ok.</pre>
<p>This paragraph<br>
has a<br>
line break<br>
after every<br>
two words.</p>
<blockquote>This paragraph is blockquote. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
<blockquote>Nested blockquote. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.</blockquote>
</blockquote>
Here is a quotation. The previous paragraph mentioned, <q>Lorem ipsum
dolor sit amet, ...</q>.
<ul>
<li>
Unordered list, level 1. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
<li>
Item 2. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
<li>
Item 3. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
<ul>
<li>
A nested list. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat.
<li>
Item 3.2. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua.
</ul>
</ul>
<ul type="circle">
<li>Unordered list with circle bullets.
<li>Item 2.
</ul>
<ul type="square">
<li>Unordered list with square bullets.
<li>Item 2.
</ul>
<ol>
<li>Numbered list.
<li>Item 2.
<li>Item 3.
<li value=10>Item 10
<li>Item 11
</ol>
<ol start=12>
<li>Numbered list starting at 12.
<li>Item 13.
</ol>
<ol type="a">
<li>Numbered list with "a" type
<li>Item 2
<li>Item 3
</ol>
<ol type="A">
<li>Numbered list with "A" type
<li>Item 2
<li>Item 3
</ol>
<ol type="i">
<li>Numbered list with "i" type
<li>Item 2
<li>Item 3
</ol>
<ol type="I">
<li>Numbered list with "I" type
<li>Item 2
<li>Item 3
</ol>
Here's a definition list:
<dl>
<dt>Term</dt>
<dd>Definition.</dd>
<dt>Term</dt>
<dd>Definition.</dd>
<dt>Term</dt>
<dd>Definition.</dd>
</dl>
</body>
</html>
'''
class TestWindow(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.document = pyglet.text.decode_html(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
pyglet.gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == pyglet.window.key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
pyglet.app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that an empty document doesn't break, even when its
(nonexistent) text is set to bold.
'''
__docformat__ = 'restructuredtext'
__noninteractive = True
import unittest
from pyglet import gl
from pyglet import graphics
from pyglet.text import document
from pyglet.text import layout
from pyglet import window
class TestWindow(window.Window):
def __init__(self, doctype, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = doctype()
self.layout = layout.IncrementalTextLayout(self.document,
self.width, self.height, batch=self.batch)
self.document.set_style(0, len(self.document.text), {"bold": True})
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
class TestCase(unittest.TestCase):
def testUnformatted(self):
self.window = TestWindow(document.UnformattedDocument)
self.window.dispatch_events()
self.window.close()
def testFormatted(self):
self.window = TestWindow(document.FormattedDocument)
self.window.dispatch_events()
self.window.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that character and paragraph-level style is adhered to correctly in
incremental layout.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel. There are no formatting
commands, however formatting should be preserved as expected when entering or
replacing text and resizing the window.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''STYLE.py test document.
{font_size 24}This is 24pt text.{font_size 12}
This is 12pt text (as is everything that follows).
This text has some {bold True}bold character style{bold False}, some
{italic True}italic character style{italic False}, some {underline [0, 0, 0,
255]}underlined text{underline None}, {underline [255, 0, 0, 255]}underline
in red{underline None}, a {color [255, 0, 0, 255]}change {color [0, 255, 0,
255]}in {color [0, 0, 255, 255]}color{color None}, and in
{background_color [255, 255, 0, 255]}background
{background_color [0, 255, 255, 255]}color{background_color None}.
{kerning '2pt'}This sentence has 2pt kerning.{kerning 0}
{kerning '-1pt'}This sentence has negative 1pt kerning.{kerning 0}
Superscript is emulated by setting a positive baseline offset and reducing the
font size, as in
a{font_size 9}{baseline '4pt'}2{font_size None}{baseline 0} +
b{font_size 9}{baseline '4pt'}2{font_size None}{baseline 0} =
c{font_size 9}{baseline '4pt'}2{font_size None}{baseline 0}.
Subscript is similarly emulated with a negative baseline offset, as in
H{font_size 9}{baseline '-3pt'}2{font_size None}{baseline 0}O.
This paragraph uses {font_name 'Courier New'}Courier New{font_name None} and
{font_name 'Times New Roman'}Times New Roman{font_name None} fonts.
{.leading '5pt'}This paragraph has 5pts leading. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.leading None}{.line_spacing '12pt'}This paragraph has constant line spacing of
12pt. When an {font_size 18}18pt font is used{font_size None}, the text
overlaps and the baselines stay equally spaced. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, {font_size 18}sed do eiusmod tempor incididunt
ut labore et dolore{font_size None} magna aliqua.
{.line_spacing None}{.indent '20pt'}This paragraph has a 20pt indent. Lorem
ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.
{.indent None}{.tab_stops [300, 500]}Tablated data:{#x09}Player{#x09}Score{}
{#x09}Alice{#x09}30,000{}
{#x09}Bob{#x09}20,000{}
{#x09}Candice{#x09}10,000{}
{#x09}David{#x09}500
{.indent None}{.align 'right'}This paragraph is right aligned. Lorem ipsum
dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
{.align 'center'}This paragraph is centered. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.align 'left'}{.margin_left 50}This paragraph has a 50 pixel left margin.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
{.margin_left 0}{.margin_right '50px'}This paragraph has a 50 pixel right
margin. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
{.margin_left 200}{.margin_right 200}This paragraph has 200 pixel left and
right margins. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
{.align 'right'}{.margin_left 100}{.margin_right 100}This paragraph is
right-aligned, and has 100 pixel left and right margins. Lorem ipsum dolor sit
amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.align 'center'}{.margin_left 100}{.margin_right 100}This paragraph is
centered, and has 100 pixel left and right margins. Lorem ipsum dolor sit
amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.align 'left'}{.margin_left 0}{.margin_right 0}{.wrap False}This paragraph
does not word-wrap. Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
{.align 'left'}{.margin_left 0}{.margin_right 0}{.wrap 'char'}This paragraph
has character-level wrapping. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
{.wrap True}{.margin_bottom 15}This and the following two paragraphs have a 15
pixel vertical margin separating them. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
{.margin_bottom 0}{.margin_top 30}This and the following two paragraphs have
a 30 pixel vertical margin (this time, the top margin is used instead of the
bottom margin). There is a 45 pixel margin between this paragraph and the
previous one.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_attributed(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# $Id:$
from pyglet.text import runlist
import unittest
__noninteractive = True
class TestStyleRuns(unittest.TestCase):
def check_value(self, runs, value):
for i, style in enumerate(value):
self.assertTrue(runs[i] == style, repr(runs.runs))
self.check_optimal(runs)
self.check_continuous(runs)
self.check_iter(runs, value)
self.check_iter_range(runs, value)
def check_optimal(self, runs):
last_style = None
for _, _, style in runs:
self.assertTrue(style != last_style)
last_style = style
def check_continuous(self, runs):
next_start = 0
for start, end, _ in runs:
self.assertTrue(start == next_start)
next_start = end
def check_iter(self, runs, value):
for start, end, style in runs:
for v in value[start:end]:
self.assertTrue(v == style)
def check_iter_range(self, runs, value):
for interval in range(1, len(value)):
it = runs.get_run_iterator()
for start in range(0, len(value), interval):
end = min(start + interval, len(value))
for s, e, style in it.ranges(start, end):
for v in value[s:e]:
self.assertTrue(v == style, (start, end, s, e, style))
def check_empty(self, runs, value):
start, end, style = iter(runs).next()
self.assertTrue(start == 0)
self.assertTrue(end == 0)
self.assertTrue(style == value)
def test_zero(self):
runs = runlist.RunList(0, 'x')
it = iter(runs)
start, end, s = it.next()
self.assertTrue(start == 0)
self.assertTrue(end == 0)
self.assertTrue(s == 'x')
self.assertRaises(StopIteration, it.next)
self.check_optimal(runs)
def test_initial(self):
runs = runlist.RunList(10, 'x')
it = iter(runs)
start, end, s = it.next()
self.assertTrue(start == 0)
self.assertTrue(end == 10)
self.assertTrue(s == 'x')
self.assertRaises(StopIteration, it.next)
self.check_value(runs, 'x' * 10)
def test_set1(self):
runs = runlist.RunList(10, 'a')
runs.set_run(2, 8, 'b')
self.check_value(runs, 'aabbbbbbaa')
def test_set1_start(self):
runs = runlist.RunList(10, 'a')
runs.set_run(0, 5, 'b')
self.check_value(runs, 'bbbbbaaaaa')
def test_set1_end(self):
runs = runlist.RunList(10, 'a')
runs.set_run(5, 10, 'b')
self.check_value(runs, 'aaaaabbbbb')
def test_set1_all(self):
runs = runlist.RunList(10, 'a')
runs.set_run(0, 10, 'b')
self.check_value(runs, 'bbbbbbbbbb')
def test_set1_1(self):
runs = runlist.RunList(10, 'a')
runs.set_run(1, 2, 'b')
self.check_value(runs, 'abaaaaaaaa')
def test_set_overlapped(self):
runs = runlist.RunList(10, 'a')
runs.set_run(0, 5, 'b')
self.check_value(runs, 'bbbbbaaaaa')
runs.set_run(5, 10, 'c')
self.check_value(runs, 'bbbbbccccc')
runs.set_run(3, 7, 'd')
self.check_value(runs, 'bbbddddccc')
runs.set_run(4, 6, 'e')
self.check_value(runs, 'bbbdeedccc')
runs.set_run(5, 9, 'f')
self.check_value(runs, 'bbbdeffffc')
runs.set_run(2, 3, 'g')
self.check_value(runs, 'bbgdeffffc')
runs.set_run(1, 3, 'h')
self.check_value(runs, 'bhhdeffffc')
runs.set_run(1, 9, 'i')
self.check_value(runs, 'biiiiiiiic')
runs.set_run(0, 10, 'j')
self.check_value(runs, 'jjjjjjjjjj')
def test_insert_empty(self):
runs = runlist.RunList(0, 'a')
runs.insert(0, 10)
self.check_value(runs, 'aaaaaaaaaa')
def test_insert_beginning(self):
runs = runlist.RunList(5, 'a')
runs.set_run(1, 4, 'b')
self.check_value(runs, 'abbba')
runs.insert(0, 3)
self.check_value(runs, 'aaaabbba')
def test_insert_beginning_1(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'a')
self.check_value(runs, 'aaaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'a')
self.check_value(runs, 'aaaaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'a')
self.check_value(runs, 'aaaaaaaa')
def test_insert_beginning_2(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'b')
self.check_value(runs, 'baaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'c')
self.check_value(runs, 'cbaaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'c')
self.check_value(runs, 'ccbaaaaa')
def test_insert_1(self):
runs = runlist.RunList(5, 'a')
runs.set_run(1, 4, 'b')
self.check_value(runs, 'abbba')
runs.insert(1, 3)
self.check_value(runs, 'aaaabbba')
def test_insert_2(self):
runs = runlist.RunList(5, 'a')
runs.set_run(1, 2, 'b')
self.check_value(runs, 'abaaa')
runs.insert(2, 3)
self.check_value(runs, 'abbbbaaa')
def test_insert_end(self):
runs = runlist.RunList(5, 'a')
runs.set_run(4, 5, 'b')
self.check_value(runs, 'aaaab')
runs.insert(5, 3)
self.check_value(runs, 'aaaabbbb')
def test_insert_almost_end(self):
runs = runlist.RunList(5, 'a')
runs.set_run(0, 3, 'b')
runs.set_run(4, 5, 'c')
self.check_value(runs, 'bbbac')
runs.insert(4, 3)
self.check_value(runs, 'bbbaaaac')
def test_delete_1_beginning(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(0, 3)
self.check_value(runs, 'aa')
def test_delete_1_middle(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(1, 4)
self.check_value(runs, 'aa')
def test_delete_1_end(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(2, 5)
self.check_value(runs, 'aa')
def test_delete_1_all(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(0, 5)
self.check_value(runs, '')
self.check_empty(runs, 'a')
def create_runs1(self):
runs = runlist.RunList(10, 'a')
runs.set_run(1, 10, 'b')
runs.set_run(2, 10, 'c')
runs.set_run(3, 10, 'd')
runs.set_run(4, 10, 'e')
runs.set_run(5, 10, 'f')
runs.set_run(6, 10, 'g')
runs.set_run(7, 10, 'h')
runs.set_run(8, 10, 'i')
runs.set_run(9, 10, 'j')
self.check_value(runs, 'abcdefghij')
return runs
def create_runs2(self):
runs = runlist.RunList(10, 'a')
runs.set_run(4, 7, 'b')
runs.set_run(7, 10, 'c')
self.check_value(runs, 'aaaabbbccc')
return runs
def test_delete2(self):
runs = self.create_runs1()
runs.delete(0, 5)
self.check_value(runs, 'fghij')
def test_delete3(self):
runs = self.create_runs1()
runs.delete(2, 8)
self.check_value(runs, 'abij')
def test_delete4(self):
runs = self.create_runs2()
runs.delete(0, 5)
self.check_value(runs, 'bbccc')
def test_delete5(self):
runs = self.create_runs2()
runs.delete(5, 10)
self.check_value(runs, 'aaaab')
def test_delete6(self):
runs = self.create_runs2()
runs.delete(0, 8)
self.check_value(runs, 'cc')
def test_delete7(self):
runs = self.create_runs2()
runs.delete(2, 10)
self.check_value(runs, 'aa')
def test_delete8(self):
runs = self.create_runs2()
runs.delete(3, 8)
self.check_value(runs, 'aaacc')
def test_delete9(self):
runs = self.create_runs2()
runs.delete(7, 8)
self.check_value(runs, 'aaaabbbcc')
def test_delete10(self):
runs = self.create_runs2()
runs.delete(8, 9)
self.check_value(runs, 'aaaabbbcc')
def test_delete11(self):
runs = self.create_runs2()
runs.delete(9, 10)
self.check_value(runs, 'aaaabbbcc')
def test_delete12(self):
runs = self.create_runs2()
runs.delete(4, 5)
self.check_value(runs, 'aaaabbccc')
def test_delete13(self):
runs = self.create_runs2()
runs.delete(5, 6)
self.check_value(runs, 'aaaabbccc')
def test_delete14(self):
runs = self.create_runs2()
runs.delete(6, 7)
self.check_value(runs, 'aaaabbccc')
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that a paragraph is broken or not according the settings in an
incremental layout.
Three windows will be open (one per test) showing:
- A paragraph in a single line, skipping newlines and no wrapping the line.
- A paragraph in multiple lines, but the long lines will no be wrapped.
- Last, a paragraph in multiple lines with wrapped lines.
You can edit the text in each window and you must press ESC to close the window
and continue with the next window until finish the test.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
nonewline_nowrap = '''{font_size 24}Multiline=False\n
{font_size 12}This paragraph contains a lots of newlines however,\n
the parameter multiline=False makes pyglet {font_size 16}ignore{font_size 12} it.\n
For example this line should be not in a new line.\n
And because the parameter multiline=False (ignoring wrap_lines) the {font_size 16}long lines are not broken{font_size 12}, as you can see in this line.'''
newline_nowrap = '''{font_size 24}Multiline=True -- Wrap_line=False\n
{font_size 12}This paragraph contains a lots of newlines however,\n
the parameter multiline=True makes pyglet {font_size 16}accept{font_size 12} it.\n
For example this line should be in a new line.\n
And because the parameter wrap_lines=False the {font_size 16}long lines are not broken{font_size 12}, as you can see in this line.'''
newline_wrap = '''{font_size 24}Multiline=True -- Wrap_line=True\n
{font_size 12}This paragraph contains a lots of newlines however,\n
the parameter multiline=True makes pyglet {font_size 16}accept{font_size 12} it.\n
For example this line should be in a new line.\n
And because the parameter wrap_lines=False the {font_size 16}long lines are broken{font_size 12}, as you can see in this line.'''
class TestWindow(window.Window):
def __init__(self, multiline, wrap_lines, msg, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_attributed(msg)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
(self.width - self.margin * 2),
self.height - self.margin * 2,
multiline=multiline,
wrap_lines=wrap_lines,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.wrap_lines = wrap_lines
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
if self.wrap_lines:
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def testMultilineFalse(self):
self.window = TestWindow(
multiline=False, wrap_lines=False,
msg=nonewline_nowrap, resizable=True, visible=False)
self.window.set_visible()
app.run()
def testMultilineTrueNoLimited(self):
self.window = TestWindow(
multiline=True, wrap_lines=False,
msg=newline_nowrap, resizable=True, visible=False)
self.window.set_visible()
app.run()
def testMultilineTrueLimited(self):
self.window = TestWindow(
multiline=True, wrap_lines=True,
msg=newline_wrap, resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that an empty document doesn't break.
'''
__docformat__ = 'restructuredtext'
__noninteractive = True
import unittest
from pyglet import gl
from pyglet import graphics
from pyglet.text import document
from pyglet.text import layout
from pyglet import window
class TestWindow(window.Window):
def __init__(self, doctype, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = doctype()
self.layout = layout.IncrementalTextLayout(self.document,
self.width, self.height, batch=self.batch)
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
class TestCase(unittest.TestCase):
def testUnformatted(self):
self.window = TestWindow(document.UnformattedDocument)
self.window.dispatch_events()
self.window.close()
def testFormatted(self):
self.window = TestWindow(document.FormattedDocument)
self.window.dispatch_events()
self.window.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that a paragraph is broken or not according the settings in an
incremental layout.
Three windows will be open (one per test) showing:
- A paragraph in a single line, skipping newlines and no wrapping the line.
- A paragraph in multiple lines, but the long lines will no be wrapped.
- Last, a paragraph in multiple lines with wrapped lines.
You can edit the text in each window and you must press ESC to close the window
and continue with the next window until finish the test.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
nonewline_nowrap = '''{font_size 24}Multiline=False\n
{font_size 12}This paragraph contains a lots of newlines however,\n
the parameter multiline=False makes pyglet {font_size 16}ignore{font_size 12} it.\n
For example this line should be not in a new line.\n
And because the parameter multiline=False (ignoring wrap_lines) the {font_size 16}long lines are not broken{font_size 12}, as you can see in this line.'''
newline_nowrap = '''{font_size 24}Multiline=True -- Wrap_line=False\n
{font_size 12}This paragraph contains a lots of newlines however,\n
the parameter multiline=True makes pyglet {font_size 16}accept{font_size 12} it.\n
For example this line should be in a new line.\n
And because the parameter wrap_lines=False the {font_size 16}long lines are not broken{font_size 12}, as you can see in this line.'''
newline_wrap = '''{font_size 24}Multiline=True -- Wrap_line=True\n
{font_size 12}This paragraph contains a lots of newlines however,\n
the parameter multiline=True makes pyglet {font_size 16}accept{font_size 12} it.\n
For example this line should be in a new line.\n
And because the parameter wrap_lines=False the {font_size 16}long lines are broken{font_size 12}, as you can see in this line.'''
class TestWindow(window.Window):
def __init__(self, multiline, wrap_lines, msg, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_attributed(msg)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
(self.width - self.margin * 2),
self.height - self.margin * 2,
multiline=multiline,
wrap_lines=wrap_lines,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.wrap_lines = wrap_lines
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
if self.wrap_lines:
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def testMultilineFalse(self):
self.window = TestWindow(
multiline=False, wrap_lines=False,
msg=nonewline_nowrap, resizable=True, visible=False)
self.window.set_visible()
app.run()
def testMultilineTrueNoLimited(self):
self.window = TestWindow(
multiline=True, wrap_lines=False,
msg=newline_nowrap, resizable=True, visible=False)
self.window.set_visible()
app.run()
def testMultilineTrueLimited(self):
self.window = TestWindow(
multiline=True, wrap_lines=True,
msg=newline_wrap, resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that HTML data is decoded into a formatted document.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: ELEMENT.py 1764 2008-02-16 05:24:46Z Alex.Holkner $'
import unittest
import pyglet
from pyglet.text import caret, document, layout
doctext = '''
<html>
<head>
(metadata including title is not displayed.)
<title>Test document</title>
</head>
<body>
<h1>HTML test document</h1>
<p>Several paragraphs of HTML formatted text follow. Ensure they are
formatted as they are described. Here is a copyright symbol: © and
again, using hexadecimal ref: ©.</p>
<P>This paragraph has some <b>bold</b> and <i>italic</i> and <b><i>bold
italic</b> text. <!-- i tag does not need to be closed -->
<p>This paragraph has some <em>emphasis</em> and <strong>strong</strong>
and <em><strong>emphatic strong</em> text.
<p>This paragraph demonstrates superscript: a<sup>2</sup> + b<sup>2</sup>
= c<sup>2</sup>; and subscript: H<sub>2</sub>O.
<p>This paragraph uses the <font> element:
<font face="Courier New">Courier New</font>, <font size=1>size 1</font>,
<font size=2>size 2</font>, <font size=3>size 3</font>, <font size=4>size
4</font>, <font size=5>size 5</font>, <font size=6>size 6</font>, <font
size=7>size 7</font>.
<p>This paragraph uses relative sizes: <font size=5>size 5<font
size=-2>size 3</font><!--<font size=+1>size 6</font>--></font>
<p>Font color changes to <font color=red>red</font>, <font
color=green>green</font> and <font color=#0f0fff>pastel blue using a
hexidecimal number</font>.
<p><u>This text is underlined</u>. <font color=green><u>This text is
underlined and green.</u></font>
<h1>Heading 1
<h2>Heading 2
<h3>Heading 3
<h4>Heading 4
<h5>Heading 5
<h6>Heading 6
<p align=center>Centered paragraph.
<p align=right>Right-aligned paragraph.
<div><div> element instead of paragraph.
<div>This sentence should start a new paragraph, as the div is nested.
</div>
This sentence should start a new paragraph, as the nested div was
closed.
</div>
<pre>This text is preformatted.
Hard line breaks
Indentation. <b>Inline formatting</b> is still ok.</pre>
<p>This paragraph<br>
has a<br>
line break<br>
after every<br>
two words.</p>
<blockquote>This paragraph is blockquote. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
<blockquote>Nested blockquote. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.</blockquote>
</blockquote>
Here is a quotation. The previous paragraph mentioned, <q>Lorem ipsum
dolor sit amet, ...</q>.
<ul>
<li>
Unordered list, level 1. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
<li>
Item 2. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
<li>
Item 3. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
<ul>
<li>
A nested list. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat.
<li>
Item 3.2. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua.
</ul>
</ul>
<ul type="circle">
<li>Unordered list with circle bullets.
<li>Item 2.
</ul>
<ul type="square">
<li>Unordered list with square bullets.
<li>Item 2.
</ul>
<ol>
<li>Numbered list.
<li>Item 2.
<li>Item 3.
<li value=10>Item 10
<li>Item 11
</ol>
<ol start=12>
<li>Numbered list starting at 12.
<li>Item 13.
</ol>
<ol type="a">
<li>Numbered list with "a" type
<li>Item 2
<li>Item 3
</ol>
<ol type="A">
<li>Numbered list with "A" type
<li>Item 2
<li>Item 3
</ol>
<ol type="i">
<li>Numbered list with "i" type
<li>Item 2
<li>Item 3
</ol>
<ol type="I">
<li>Numbered list with "I" type
<li>Item 2
<li>Item 3
</ol>
Here's a definition list:
<dl>
<dt>Term</dt>
<dd>Definition.</dd>
<dt>Term</dt>
<dd>Definition.</dd>
<dt>Term</dt>
<dd>Definition.</dd>
</dl>
</body>
</html>
'''
class TestWindow(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.document = pyglet.text.decode_html(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
pyglet.gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == pyglet.window.key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
pyglet.app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# $Id:$
from pyglet.text import runlist
import unittest
__noninteractive = True
class TestStyleRuns(unittest.TestCase):
def check_value(self, runs, value):
for i, style in enumerate(value):
self.assertTrue(runs[i] == style, repr(runs.runs))
self.check_optimal(runs)
self.check_continuous(runs)
self.check_iter(runs, value)
self.check_iter_range(runs, value)
def check_optimal(self, runs):
last_style = None
for _, _, style in runs:
self.assertTrue(style != last_style)
last_style = style
def check_continuous(self, runs):
next_start = 0
for start, end, _ in runs:
self.assertTrue(start == next_start)
next_start = end
def check_iter(self, runs, value):
for start, end, style in runs:
for v in value[start:end]:
self.assertTrue(v == style)
def check_iter_range(self, runs, value):
for interval in range(1, len(value)):
it = runs.get_run_iterator()
for start in range(0, len(value), interval):
end = min(start + interval, len(value))
for s, e, style in it.ranges(start, end):
for v in value[s:e]:
self.assertTrue(v == style, (start, end, s, e, style))
def check_empty(self, runs, value):
start, end, style = iter(runs).next()
self.assertTrue(start == 0)
self.assertTrue(end == 0)
self.assertTrue(style == value)
def test_zero(self):
runs = runlist.RunList(0, 'x')
it = iter(runs)
start, end, s = it.next()
self.assertTrue(start == 0)
self.assertTrue(end == 0)
self.assertTrue(s == 'x')
self.assertRaises(StopIteration, it.next)
self.check_optimal(runs)
def test_initial(self):
runs = runlist.RunList(10, 'x')
it = iter(runs)
start, end, s = it.next()
self.assertTrue(start == 0)
self.assertTrue(end == 10)
self.assertTrue(s == 'x')
self.assertRaises(StopIteration, it.next)
self.check_value(runs, 'x' * 10)
def test_set1(self):
runs = runlist.RunList(10, 'a')
runs.set_run(2, 8, 'b')
self.check_value(runs, 'aabbbbbbaa')
def test_set1_start(self):
runs = runlist.RunList(10, 'a')
runs.set_run(0, 5, 'b')
self.check_value(runs, 'bbbbbaaaaa')
def test_set1_end(self):
runs = runlist.RunList(10, 'a')
runs.set_run(5, 10, 'b')
self.check_value(runs, 'aaaaabbbbb')
def test_set1_all(self):
runs = runlist.RunList(10, 'a')
runs.set_run(0, 10, 'b')
self.check_value(runs, 'bbbbbbbbbb')
def test_set1_1(self):
runs = runlist.RunList(10, 'a')
runs.set_run(1, 2, 'b')
self.check_value(runs, 'abaaaaaaaa')
def test_set_overlapped(self):
runs = runlist.RunList(10, 'a')
runs.set_run(0, 5, 'b')
self.check_value(runs, 'bbbbbaaaaa')
runs.set_run(5, 10, 'c')
self.check_value(runs, 'bbbbbccccc')
runs.set_run(3, 7, 'd')
self.check_value(runs, 'bbbddddccc')
runs.set_run(4, 6, 'e')
self.check_value(runs, 'bbbdeedccc')
runs.set_run(5, 9, 'f')
self.check_value(runs, 'bbbdeffffc')
runs.set_run(2, 3, 'g')
self.check_value(runs, 'bbgdeffffc')
runs.set_run(1, 3, 'h')
self.check_value(runs, 'bhhdeffffc')
runs.set_run(1, 9, 'i')
self.check_value(runs, 'biiiiiiiic')
runs.set_run(0, 10, 'j')
self.check_value(runs, 'jjjjjjjjjj')
def test_insert_empty(self):
runs = runlist.RunList(0, 'a')
runs.insert(0, 10)
self.check_value(runs, 'aaaaaaaaaa')
def test_insert_beginning(self):
runs = runlist.RunList(5, 'a')
runs.set_run(1, 4, 'b')
self.check_value(runs, 'abbba')
runs.insert(0, 3)
self.check_value(runs, 'aaaabbba')
def test_insert_beginning_1(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'a')
self.check_value(runs, 'aaaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'a')
self.check_value(runs, 'aaaaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'a')
self.check_value(runs, 'aaaaaaaa')
def test_insert_beginning_2(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'b')
self.check_value(runs, 'baaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'c')
self.check_value(runs, 'cbaaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'c')
self.check_value(runs, 'ccbaaaaa')
def test_insert_1(self):
runs = runlist.RunList(5, 'a')
runs.set_run(1, 4, 'b')
self.check_value(runs, 'abbba')
runs.insert(1, 3)
self.check_value(runs, 'aaaabbba')
def test_insert_2(self):
runs = runlist.RunList(5, 'a')
runs.set_run(1, 2, 'b')
self.check_value(runs, 'abaaa')
runs.insert(2, 3)
self.check_value(runs, 'abbbbaaa')
def test_insert_end(self):
runs = runlist.RunList(5, 'a')
runs.set_run(4, 5, 'b')
self.check_value(runs, 'aaaab')
runs.insert(5, 3)
self.check_value(runs, 'aaaabbbb')
def test_insert_almost_end(self):
runs = runlist.RunList(5, 'a')
runs.set_run(0, 3, 'b')
runs.set_run(4, 5, 'c')
self.check_value(runs, 'bbbac')
runs.insert(4, 3)
self.check_value(runs, 'bbbaaaac')
def test_delete_1_beginning(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(0, 3)
self.check_value(runs, 'aa')
def test_delete_1_middle(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(1, 4)
self.check_value(runs, 'aa')
def test_delete_1_end(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(2, 5)
self.check_value(runs, 'aa')
def test_delete_1_all(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(0, 5)
self.check_value(runs, '')
self.check_empty(runs, 'a')
def create_runs1(self):
runs = runlist.RunList(10, 'a')
runs.set_run(1, 10, 'b')
runs.set_run(2, 10, 'c')
runs.set_run(3, 10, 'd')
runs.set_run(4, 10, 'e')
runs.set_run(5, 10, 'f')
runs.set_run(6, 10, 'g')
runs.set_run(7, 10, 'h')
runs.set_run(8, 10, 'i')
runs.set_run(9, 10, 'j')
self.check_value(runs, 'abcdefghij')
return runs
def create_runs2(self):
runs = runlist.RunList(10, 'a')
runs.set_run(4, 7, 'b')
runs.set_run(7, 10, 'c')
self.check_value(runs, 'aaaabbbccc')
return runs
def test_delete2(self):
runs = self.create_runs1()
runs.delete(0, 5)
self.check_value(runs, 'fghij')
def test_delete3(self):
runs = self.create_runs1()
runs.delete(2, 8)
self.check_value(runs, 'abij')
def test_delete4(self):
runs = self.create_runs2()
runs.delete(0, 5)
self.check_value(runs, 'bbccc')
def test_delete5(self):
runs = self.create_runs2()
runs.delete(5, 10)
self.check_value(runs, 'aaaab')
def test_delete6(self):
runs = self.create_runs2()
runs.delete(0, 8)
self.check_value(runs, 'cc')
def test_delete7(self):
runs = self.create_runs2()
runs.delete(2, 10)
self.check_value(runs, 'aa')
def test_delete8(self):
runs = self.create_runs2()
runs.delete(3, 8)
self.check_value(runs, 'aaacc')
def test_delete9(self):
runs = self.create_runs2()
runs.delete(7, 8)
self.check_value(runs, 'aaaabbbcc')
def test_delete10(self):
runs = self.create_runs2()
runs.delete(8, 9)
self.check_value(runs, 'aaaabbbcc')
def test_delete11(self):
runs = self.create_runs2()
runs.delete(9, 10)
self.check_value(runs, 'aaaabbbcc')
def test_delete12(self):
runs = self.create_runs2()
runs.delete(4, 5)
self.check_value(runs, 'aaaabbccc')
def test_delete13(self):
runs = self.create_runs2()
runs.delete(5, 6)
self.check_value(runs, 'aaaabbccc')
def test_delete14(self):
runs = self.create_runs2()
runs.delete(6, 7)
self.check_value(runs, 'aaaabbccc')
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that inline elements are positioned correctly and are repositioned
within an incremental layout.
Examine and type over the text in the window that appears. There are several
elements drawn with grey boxes. These should maintain their sizes and
relative document positions as the text is scrolled and edited.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import pyglet
from pyglet.text import caret, document, layout
doctext = '''ELEMENT.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce venenatis
pharetra libero. Phasellus lacinia nisi feugiat felis. Sed id magna in nisl
cursus consectetuer. Aliquam aliquam lectus eu magna. Praesent sit amet ipsum
vitae nisl mattis commodo. Aenean pulvinar facilisis lectus. Phasellus sodales
risus sit amet lectus. Suspendisse in turpis. Vestibulum ac mi accumsan eros
commodo tincidunt. Nullam velit. In pulvinar, dui sit amet ullamcorper dictum,
dui risus ultricies nisl, a dignissim sapien enim sit amet tortor.
Pellentesque fringilla, massa sit amet bibendum blandit, pede leo commodo mi,
eleifend feugiat neque tortor dapibus mauris. Morbi nunc arcu, tincidunt vel,
blandit non, iaculis vel, libero. Vestibulum sed metus vel velit scelerisque
varius. Vivamus a tellus. Proin nec orci vel elit molestie venenatis. Aenean
fringilla, lorem vel fringilla bibendum, nibh mi varius mi, eget semper ipsum
ligula ut urna. Nullam tempor convallis augue. Sed at dui.
Nunc faucibus pretium ipsum. Sed ultricies ligula a arcu. Pellentesque vel
urna in augue euismod hendrerit. Donec consequat. Morbi convallis nulla at
ante bibendum auctor. In augue mi, tincidunt a, porta ac, tempor sit amet,
sapien. In sollicitudin risus. Vivamus leo turpis, elementum sed, accumsan eu,
scelerisque at, augue. Ut eu tortor non sem vulputate bibendum. Fusce
ultricies ultrices lorem. In hac habitasse platea dictumst. Morbi ac ipsum.
Nam tellus sem, congue in, fermentum a, ullamcorper vel, mauris. Etiam erat
tortor, facilisis ut, blandit id, placerat sed, orci. Donec quam eros,
bibendum eu, ultricies id, mattis eu, tellus. Ut hendrerit erat vel ligula.
Sed tellus. Quisque imperdiet ornare diam.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac
turpis egestas. Sed neque quam, pretium et, malesuada sed, porttitor eu, leo.
Sed varius ornare augue. Maecenas pede dui, nonummy eu, ullamcorper sed,
lobortis id, sem. In sed leo. Nulla ornare. Curabitur dui. Cras ipsum. Cras
massa augue, sodales nec, ultricies at, fermentum in, turpis. Aenean lorem
lectus, fermentum et, lacinia quis, ullamcorper ac, purus. Pellentesque
pharetra diam at elit. Donec dolor. Aenean turpis orci, aliquam vitae,
fermentum et, consectetuer sed, lacus. Maecenas pulvinar, nisi sit amet
lobortis rhoncus, est ipsum ullamcorper mauris, nec cursus felis neque et
dolor. Nulla venenatis sapien vitae lectus. Praesent in risus. In imperdiet
adipiscing nisi. Quisque volutpat, ante sed vehicula sodales, nisi quam
bibendum turpis, id bibendum pede enim porttitor tellus. Aliquam velit.
Pellentesque at mauris quis libero fermentum cursus.
Integer bibendum scelerisque elit. Curabitur justo tellus, vehicula luctus,
consequat vitae, convallis quis, nunc. Fusce libero nulla, convallis eu,
dignissim sit amet, sagittis ac, odio. Morbi dictum tincidunt nisi. Curabitur
hendrerit. Aliquam eleifend sodales leo. Donec interdum. Nam vulputate, purus
in euismod bibendum, pede mi pellentesque dolor, at viverra quam tellus eget
pede. Suspendisse varius mi id felis. Aenean in velit eu nisi suscipit mollis.
Suspendisse vitae augue et diam volutpat luctus.
Mauris et lorem. In mauris. Morbi commodo rutrum nibh. Pellentesque lobortis.
Sed eget urna ut massa venenatis luctus. Morbi egestas purus eget ante
pulvinar vulputate. Suspendisse sollicitudin. Cras tortor erat, semper
vehicula, suscipit non, facilisis ut, est. Aenean quis libero varius nisl
fringilla mollis. Donec viverra. Phasellus mi tortor, pulvinar id, pulvinar
in, lacinia nec, massa. Curabitur lectus erat, volutpat at, volutpat at,
pharetra nec, turpis. Donec ornare nonummy leo. Donec consectetuer posuere
metus. Quisque tincidunt risus facilisis dui. Ut suscipit turpis in massa.
Aliquam erat volutpat.
'''
class TestElement(document.InlineElement):
vertex_list = None
def place(self, layout, x, y):
self.vertex_list = layout.batch.add(4, pyglet.gl.GL_QUADS,
layout.top_group,
'v2i',
('c4B', [200, 200, 200, 255] * 4))
y += self.descent
w = self.advance
h = self.ascent - self.descent
self.vertex_list.vertices[:] = (x, y,
x + w, y,
x + w, y + h,
x, y + h)
def remove(self, layout):
self.vertex_list.delete()
del self.vertex_list
class TestWindow(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.document = pyglet.text.decode_attributed(doctext)
for i in range(0, len(doctext), 300):
self.document.insert_element(i, TestElement(60, -10, 70))
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
pyglet.gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == pyglet.window.key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
pyglet.app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that character and paragraph-level style is adhered to correctly in
incremental layout.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel. There are no formatting
commands, however formatting should be preserved as expected when entering or
replacing text and resizing the window.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''STYLE.py test document.
{font_size 24}This is 24pt text.{font_size 12}
This is 12pt text (as is everything that follows).
This text has some {bold True}bold character style{bold False}, some
{italic True}italic character style{italic False}, some {underline [0, 0, 0,
255]}underlined text{underline None}, {underline [255, 0, 0, 255]}underline
in red{underline None}, a {color [255, 0, 0, 255]}change {color [0, 255, 0,
255]}in {color [0, 0, 255, 255]}color{color None}, and in
{background_color [255, 255, 0, 255]}background
{background_color [0, 255, 255, 255]}color{background_color None}.
{kerning '2pt'}This sentence has 2pt kerning.{kerning 0}
{kerning '-1pt'}This sentence has negative 1pt kerning.{kerning 0}
Superscript is emulated by setting a positive baseline offset and reducing the
font size, as in
a{font_size 9}{baseline '4pt'}2{font_size None}{baseline 0} +
b{font_size 9}{baseline '4pt'}2{font_size None}{baseline 0} =
c{font_size 9}{baseline '4pt'}2{font_size None}{baseline 0}.
Subscript is similarly emulated with a negative baseline offset, as in
H{font_size 9}{baseline '-3pt'}2{font_size None}{baseline 0}O.
This paragraph uses {font_name 'Courier New'}Courier New{font_name None} and
{font_name 'Times New Roman'}Times New Roman{font_name None} fonts.
{.leading '5pt'}This paragraph has 5pts leading. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.leading None}{.line_spacing '12pt'}This paragraph has constant line spacing of
12pt. When an {font_size 18}18pt font is used{font_size None}, the text
overlaps and the baselines stay equally spaced. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, {font_size 18}sed do eiusmod tempor incididunt
ut labore et dolore{font_size None} magna aliqua.
{.line_spacing None}{.indent '20pt'}This paragraph has a 20pt indent. Lorem
ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.
{.indent None}{.tab_stops [300, 500]}Tablated data:{#x09}Player{#x09}Score{}
{#x09}Alice{#x09}30,000{}
{#x09}Bob{#x09}20,000{}
{#x09}Candice{#x09}10,000{}
{#x09}David{#x09}500
{.indent None}{.align 'right'}This paragraph is right aligned. Lorem ipsum
dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
{.align 'center'}This paragraph is centered. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.align 'left'}{.margin_left 50}This paragraph has a 50 pixel left margin.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
{.margin_left 0}{.margin_right '50px'}This paragraph has a 50 pixel right
margin. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
{.margin_left 200}{.margin_right 200}This paragraph has 200 pixel left and
right margins. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
{.align 'right'}{.margin_left 100}{.margin_right 100}This paragraph is
right-aligned, and has 100 pixel left and right margins. Lorem ipsum dolor sit
amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.align 'center'}{.margin_left 100}{.margin_right 100}This paragraph is
centered, and has 100 pixel left and right margins. Lorem ipsum dolor sit
amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.align 'left'}{.margin_left 0}{.margin_right 0}{.wrap False}This paragraph
does not word-wrap. Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
{.align 'left'}{.margin_left 0}{.margin_right 0}{.wrap 'char'}This paragraph
has character-level wrapping. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
{.wrap True}{.margin_bottom 15}This and the following two paragraphs have a 15
pixel vertical margin separating them. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
{.margin_bottom 0}{.margin_top 30}This and the following two paragraphs have
a 30 pixel vertical margin (this time, the top margin is used instead of the
bottom margin). There is a 45 pixel margin between this paragraph and the
previous one.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_attributed(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test an unformatted document is editable.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: STYLE.py 1754 2008-02-10 13:26:52Z Alex.Holkner $'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''PLAIN.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquet quam sit amet enim. Donec iaculis, magna vitae imperdiet convallis, lectus sem ultricies nulla, non fringilla quam felis tempus velit. Etiam et velit. Integer euismod. Aliquam a diam. Donec sed ante. Mauris enim pede, dapibus sed, dapibus vitae, consectetuer in, est. Donec aliquam risus eu ipsum. Integer et tortor. Ut accumsan risus sed ante.
Aliquam dignissim, massa a imperdiet fermentum, orci dolor facilisis ante, ut vulputate nisi nunc sed massa. Morbi sodales hendrerit tortor. Nunc id tortor ut lacus mollis malesuada. Sed nibh tellus, rhoncus et, egestas eu, laoreet eu, urna. Vestibulum massa leo, convallis et, pharetra vitae, iaculis at, ante. Pellentesque volutpat porta enim. Morbi ac nunc eget mi pretium viverra. Pellentesque felis risus, lobortis vitae, malesuada vitae, bibendum eu, tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus dapibus tortor ac neque. Curabitur pulvinar bibendum lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla turpis leo, rhoncus vel, euismod non, consequat sed, massa. Quisque ultricies. Aliquam fringilla faucibus est. Proin nec felis eget felis suscipit vehicula.
Etiam quam. Aliquam at ligula. Aenean quis dolor. Suspendisse potenti. Sed lacinia leo eu est. Nam pede ligula, molestie nec, tincidunt vel, posuere in, tellus. Donec fringilla dictum dolor. Aenean tellus orci, viverra id, vehicula eget, tempor a, dui. Morbi eu dolor nec lacus fringilla dapibus. Nulla facilisi. Nulla posuere. Nunc interdum. Donec convallis libero vitae odio.
Aenean metus lectus, faucibus in, malesuada at, fringilla nec, risus. Integer enim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin bibendum felis vel neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ipsum dui, euismod at, dictum eu, congue tincidunt, urna. Sed quis odio. Integer aliquam pretium augue. Vivamus nonummy, dolor vel viverra rutrum, lacus dui congue pede, vel sodales dui diam nec libero. Morbi et leo sit amet quam sollicitudin laoreet. Vivamus suscipit.
Duis arcu eros, iaculis ut, vehicula in, elementum a, sapien. Phasellus ut tellus. Integer feugiat nunc eget odio. Morbi accumsan nonummy ipsum. Donec condimentum, tortor non faucibus luctus, neque mi mollis magna, nec gravida risus elit nec ipsum. Donec nec sem. Maecenas varius libero quis diam. Curabitur pulvinar. Morbi at sem eget mauris tempor vulputate. Aenean eget turpis.
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_text(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that an empty document doesn't break.
'''
__docformat__ = 'restructuredtext'
__noninteractive = True
import unittest
from pyglet import gl
from pyglet import graphics
from pyglet.text import document
from pyglet.text import layout
from pyglet import window
class TestWindow(window.Window):
def __init__(self, doctype, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = doctype()
self.layout = layout.IncrementalTextLayout(self.document,
self.width, self.height, batch=self.batch)
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
class TestCase(unittest.TestCase):
def testUnformatted(self):
self.window = TestWindow(document.UnformattedDocument)
self.window.dispatch_events()
self.window.close()
def testFormatted(self):
self.window = TestWindow(document.FormattedDocument)
self.window.dispatch_events()
self.window.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that an empty document doesn't break, even when its
(nonexistent) text is set to bold.
'''
__docformat__ = 'restructuredtext'
__noninteractive = True
import unittest
from pyglet import gl
from pyglet import graphics
from pyglet.text import document
from pyglet.text import layout
from pyglet import window
class TestWindow(window.Window):
def __init__(self, doctype, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = doctype()
self.layout = layout.IncrementalTextLayout(self.document,
self.width, self.height, batch=self.batch)
self.document.set_style(0, len(self.document.text), {"bold": True})
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
class TestCase(unittest.TestCase):
def testUnformatted(self):
self.window = TestWindow(document.UnformattedDocument)
self.window.dispatch_events()
self.window.close()
def testFormatted(self):
self.window = TestWindow(document.FormattedDocument)
self.window.dispatch_events()
self.window.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that inline elements can have their style changed, even after text
has been deleted before them. [This triggers bug 538 if it has not yet been fixed.]
To run the test, delete the first line, one character at a time,
verifying that the element remains visible and no tracebacks are
printed to the console.
Press ESC to end the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import pyglet
from pyglet.text import caret, document, layout
doctext = '''ELEMENT.py test document.
PLACE CURSOR AT THE END OF THE ABOVE LINE, AND DELETE ALL ITS TEXT,
BY PRESSING THE DELETE KEY REPEATEDLY.
IF THIS WORKS OK, AND THE ELEMENT (GRAY RECTANGLE) WITHIN THIS LINE
[element here]
REMAINS VISIBLE BETWEEN THE SAME CHARACTERS, WITH NO ASSERTIONS PRINTED TO
THE CONSOLE, THE TEST PASSES.
(In code with bug 538, the element sometimes moves within the text, and
eventually there is an assertion failure. Note that there is another bug,
unrelated to this one, which sometimes causes the first press of the delete
key to be ignored.)
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce venenatis
pharetra libero. Phasellus lacinia nisi feugiat felis. Sed id magna in nisl
cursus consectetuer. Aliquam aliquam lectus eu magna. Praesent sit amet ipsum
vitae nisl mattis commodo. Aenean pulvinar facilisis lectus. Phasellus sodales
risus sit amet lectus. Suspendisse in turpis. Vestibulum ac mi accumsan eros
commodo tincidunt. Nullam velit. In pulvinar, dui sit amet ullamcorper dictum,
dui risus ultricies nisl, a dignissim sapien enim sit amet tortor.
Pellentesque fringilla, massa sit amet bibendum blandit, pede leo commodo mi,
eleifend feugiat neque tortor dapibus mauris. Morbi nunc arcu, tincidunt vel,
blandit non, iaculis vel, libero. Vestibulum sed metus vel velit scelerisque
varius. Vivamus a tellus. Proin nec orci vel elit molestie venenatis. Aenean
fringilla, lorem vel fringilla bibendum, nibh mi varius mi, eget semper ipsum
ligula ut urna. Nullam tempor convallis augue. Sed at dui.
'''
element_index = doctext.index('[element here]')
doctext = doctext.replace('[element here]', '')
class TestElement(document.InlineElement):
vertex_list = None
def place(self, layout, x, y):
## assert layout.document.text[self._position] == '\x00'
### in bug 538, this fails after two characters are deleted.
self.vertex_list = layout.batch.add(4, pyglet.gl.GL_QUADS,
layout.top_group,
'v2i',
('c4B', [200, 200, 200, 255] * 4))
y += self.descent
w = self.advance
h = self.ascent - self.descent
self.vertex_list.vertices[:] = (x, y,
x + w, y,
x + w, y + h,
x, y + h)
def remove(self, layout):
self.vertex_list.delete()
del self.vertex_list
class TestWindow(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.document = pyglet.text.decode_attributed(doctext)
for i in [element_index]:
self.document.insert_element(i, TestElement(60, -10, 70))
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_draw(self):
pyglet.gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == pyglet.window.key.TAB:
self.caret.on_text('\t')
self.document.set_style(0, len(self.document.text), dict(bold = None)) ### trigger bug 538
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(##resizable=True,
visible=False)
self.window.set_visible()
pyglet.app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test content_valign = 'bottom' property of IncrementalTextLayout.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel. When the content height
is less than the window height, the content should be aligned to the bottom
of the window.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: STYLE.py 1754 2008-02-10 13:26:52Z Alex.Holkner $'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''CONTENT_VALIGN_BOTTOM.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquet quam sit amet enim. Donec iaculis, magna vitae imperdiet convallis, lectus sem ultricies nulla, non fringilla quam felis tempus velit. Etiam et velit. Integer euismod. Aliquam a diam. Donec sed ante. Mauris enim pede, dapibus sed, dapibus vitae, consectetuer in, est. Donec aliquam risus eu ipsum. Integer et tortor. Ut accumsan risus sed ante.
Aliquam dignissim, massa a imperdiet fermentum, orci dolor facilisis ante, ut vulputate nisi nunc sed massa. Morbi sodales hendrerit tortor. Nunc id tortor ut lacus mollis malesuada. Sed nibh tellus, rhoncus et, egestas eu, laoreet eu, urna. Vestibulum massa leo, convallis et, pharetra vitae, iaculis at, ante. Pellentesque volutpat porta enim. Morbi ac nunc eget mi pretium viverra. Pellentesque felis risus, lobortis vitae, malesuada vitae, bibendum eu, tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus dapibus tortor ac neque. Curabitur pulvinar bibendum lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla turpis leo, rhoncus vel, euismod non, consequat sed, massa. Quisque ultricies. Aliquam fringilla faucibus est. Proin nec felis eget felis suscipit vehicula.
Etiam quam. Aliquam at ligula. Aenean quis dolor. Suspendisse potenti. Sed lacinia leo eu est. Nam pede ligula, molestie nec, tincidunt vel, posuere in, tellus. Donec fringilla dictum dolor. Aenean tellus orci, viverra id, vehicula eget, tempor a, dui. Morbi eu dolor nec lacus fringilla dapibus. Nulla facilisi. Nulla posuere. Nunc interdum. Donec convallis libero vitae odio.
Aenean metus lectus, faucibus in, malesuada at, fringilla nec, risus. Integer enim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin bibendum felis vel neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ipsum dui, euismod at, dictum eu, congue tincidunt, urna. Sed quis odio. Integer aliquam pretium augue. Vivamus nonummy, dolor vel viverra rutrum, lacus dui congue pede, vel sodales dui diam nec libero. Morbi et leo sit amet quam sollicitudin laoreet. Vivamus suscipit.
Duis arcu eros, iaculis ut, vehicula in, elementum a, sapien. Phasellus ut tellus. Integer feugiat nunc eget odio. Morbi accumsan nonummy ipsum. Donec condimentum, tortor non faucibus luctus, neque mi mollis magna, nec gravida risus elit nec ipsum. Donec nec sem. Maecenas varius libero quis diam. Curabitur pulvinar. Morbi at sem eget mauris tempor vulputate. Aenean eget turpis.
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_text(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.layout.content_valign = 'bottom'
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test content_valign = 'center' property of IncrementalTextLayout.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel. When the content height
is less than the window height, the content should be aligned to the center
of the window.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: STYLE.py 1754 2008-02-10 13:26:52Z Alex.Holkner $'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''CONTENT_VALIGN_CENTER.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquet quam sit amet enim. Donec iaculis, magna vitae imperdiet convallis, lectus sem ultricies nulla, non fringilla quam felis tempus velit. Etiam et velit. Integer euismod. Aliquam a diam. Donec sed ante. Mauris enim pede, dapibus sed, dapibus vitae, consectetuer in, est. Donec aliquam risus eu ipsum. Integer et tortor. Ut accumsan risus sed ante.
Aliquam dignissim, massa a imperdiet fermentum, orci dolor facilisis ante, ut vulputate nisi nunc sed massa. Morbi sodales hendrerit tortor. Nunc id tortor ut lacus mollis malesuada. Sed nibh tellus, rhoncus et, egestas eu, laoreet eu, urna. Vestibulum massa leo, convallis et, pharetra vitae, iaculis at, ante. Pellentesque volutpat porta enim. Morbi ac nunc eget mi pretium viverra. Pellentesque felis risus, lobortis vitae, malesuada vitae, bibendum eu, tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus dapibus tortor ac neque. Curabitur pulvinar bibendum lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla turpis leo, rhoncus vel, euismod non, consequat sed, massa. Quisque ultricies. Aliquam fringilla faucibus est. Proin nec felis eget felis suscipit vehicula.
Etiam quam. Aliquam at ligula. Aenean quis dolor. Suspendisse potenti. Sed lacinia leo eu est. Nam pede ligula, molestie nec, tincidunt vel, posuere in, tellus. Donec fringilla dictum dolor. Aenean tellus orci, viverra id, vehicula eget, tempor a, dui. Morbi eu dolor nec lacus fringilla dapibus. Nulla facilisi. Nulla posuere. Nunc interdum. Donec convallis libero vitae odio.
Aenean metus lectus, faucibus in, malesuada at, fringilla nec, risus. Integer enim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin bibendum felis vel neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ipsum dui, euismod at, dictum eu, congue tincidunt, urna. Sed quis odio. Integer aliquam pretium augue. Vivamus nonummy, dolor vel viverra rutrum, lacus dui congue pede, vel sodales dui diam nec libero. Morbi et leo sit amet quam sollicitudin laoreet. Vivamus suscipit.
Duis arcu eros, iaculis ut, vehicula in, elementum a, sapien. Phasellus ut tellus. Integer feugiat nunc eget odio. Morbi accumsan nonummy ipsum. Donec condimentum, tortor non faucibus luctus, neque mi mollis magna, nec gravida risus elit nec ipsum. Donec nec sem. Maecenas varius libero quis diam. Curabitur pulvinar. Morbi at sem eget mauris tempor vulputate. Aenean eget turpis.
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_text(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.layout.content_valign = 'center'
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the code snippets mentioned in issue 471
(and related issues 241 and 429) don't have exceptions.
(Most of them delete all text in a formatted document
with some styles set; one of them (like the test in EMPTY_BOLD.py)
sets style on a 0-length range of text in an empty document.)
'''
__docformat__ = 'restructuredtext'
__noninteractive = True
import unittest
import pyglet
class TestCase(unittest.TestCase):
def test_issue471(self):
doc = pyglet.text.document.FormattedDocument()
layout = pyglet.text.layout.IncrementalTextLayout(doc, 100, 100)
doc.insert_text(0, "hello", {'bold': True})
doc.text = ""
def test_issue471_comment2(self):
doc2 = pyglet.text.decode_attributed('{bold True}a')
layout = pyglet.text.layout.IncrementalTextLayout(doc2, 100, 10)
layout.document.delete_text(0, len(layout.document.text))
def test_issue241_comment4a(self):
document = pyglet.text.document.FormattedDocument("")
layout = pyglet.text.layout.IncrementalTextLayout(document, 50, 50)
document.set_style(0, len(document.text), {"font_name": "Arial"})
def test_issue241_comment4b(self):
document = pyglet.text.document.FormattedDocument("test")
layout = pyglet.text.layout.IncrementalTextLayout(document, 50, 50)
document.set_style(0, len(document.text), {"font_name": "Arial"})
document.delete_text(0, len(document.text))
def test_issue241_comment5(self):
document = pyglet.text.document.FormattedDocument('A')
document.set_style(0, 1, dict(bold=True))
layout = pyglet.text.layout.IncrementalTextLayout(document,100,100)
document.delete_text(0,1)
def test_issue429_comment4a(self):
doc = pyglet.text.decode_attributed('{bold True}Hello{bold False}\n\n\n\n')
doc2 = pyglet.text.decode_attributed('{bold True}Goodbye{bold False}\n\n\n\n')
layout = pyglet.text.layout.IncrementalTextLayout(doc, 100, 10)
layout.document = doc2
layout.document.delete_text(0, len(layout.document.text))
def test_issue429_comment4b(self):
doc2 = pyglet.text.decode_attributed('{bold True}a{bold False}b')
layout = pyglet.text.layout.IncrementalTextLayout(doc2, 100, 10)
layout.document.delete_text(0, len(layout.document.text))
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the code snippets mentioned in issue 471
(and related issues 241 and 429) don't have exceptions.
(Most of them delete all text in a formatted document
with some styles set; one of them (like the test in EMPTY_BOLD.py)
sets style on a 0-length range of text in an empty document.)
'''
__docformat__ = 'restructuredtext'
__noninteractive = True
import unittest
import pyglet
class TestCase(unittest.TestCase):
def test_issue471(self):
doc = pyglet.text.document.FormattedDocument()
layout = pyglet.text.layout.IncrementalTextLayout(doc, 100, 100)
doc.insert_text(0, "hello", {'bold': True})
doc.text = ""
def test_issue471_comment2(self):
doc2 = pyglet.text.decode_attributed('{bold True}a')
layout = pyglet.text.layout.IncrementalTextLayout(doc2, 100, 10)
layout.document.delete_text(0, len(layout.document.text))
def test_issue241_comment4a(self):
document = pyglet.text.document.FormattedDocument("")
layout = pyglet.text.layout.IncrementalTextLayout(document, 50, 50)
document.set_style(0, len(document.text), {"font_name": "Arial"})
def test_issue241_comment4b(self):
document = pyglet.text.document.FormattedDocument("test")
layout = pyglet.text.layout.IncrementalTextLayout(document, 50, 50)
document.set_style(0, len(document.text), {"font_name": "Arial"})
document.delete_text(0, len(document.text))
def test_issue241_comment5(self):
document = pyglet.text.document.FormattedDocument('A')
document.set_style(0, 1, dict(bold=True))
layout = pyglet.text.layout.IncrementalTextLayout(document,100,100)
document.delete_text(0,1)
def test_issue429_comment4a(self):
doc = pyglet.text.decode_attributed('{bold True}Hello{bold False}\n\n\n\n')
doc2 = pyglet.text.decode_attributed('{bold True}Goodbye{bold False}\n\n\n\n')
layout = pyglet.text.layout.IncrementalTextLayout(doc, 100, 10)
layout.document = doc2
layout.document.delete_text(0, len(layout.document.text))
def test_issue429_comment4b(self):
doc2 = pyglet.text.decode_attributed('{bold True}a{bold False}b')
layout = pyglet.text.layout.IncrementalTextLayout(doc2, 100, 10)
layout.document.delete_text(0, len(layout.document.text))
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test an unformatted document is editable.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: STYLE.py 1754 2008-02-10 13:26:52Z Alex.Holkner $'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''PLAIN.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquet quam sit amet enim. Donec iaculis, magna vitae imperdiet convallis, lectus sem ultricies nulla, non fringilla quam felis tempus velit. Etiam et velit. Integer euismod. Aliquam a diam. Donec sed ante. Mauris enim pede, dapibus sed, dapibus vitae, consectetuer in, est. Donec aliquam risus eu ipsum. Integer et tortor. Ut accumsan risus sed ante.
Aliquam dignissim, massa a imperdiet fermentum, orci dolor facilisis ante, ut vulputate nisi nunc sed massa. Morbi sodales hendrerit tortor. Nunc id tortor ut lacus mollis malesuada. Sed nibh tellus, rhoncus et, egestas eu, laoreet eu, urna. Vestibulum massa leo, convallis et, pharetra vitae, iaculis at, ante. Pellentesque volutpat porta enim. Morbi ac nunc eget mi pretium viverra. Pellentesque felis risus, lobortis vitae, malesuada vitae, bibendum eu, tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus dapibus tortor ac neque. Curabitur pulvinar bibendum lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla turpis leo, rhoncus vel, euismod non, consequat sed, massa. Quisque ultricies. Aliquam fringilla faucibus est. Proin nec felis eget felis suscipit vehicula.
Etiam quam. Aliquam at ligula. Aenean quis dolor. Suspendisse potenti. Sed lacinia leo eu est. Nam pede ligula, molestie nec, tincidunt vel, posuere in, tellus. Donec fringilla dictum dolor. Aenean tellus orci, viverra id, vehicula eget, tempor a, dui. Morbi eu dolor nec lacus fringilla dapibus. Nulla facilisi. Nulla posuere. Nunc interdum. Donec convallis libero vitae odio.
Aenean metus lectus, faucibus in, malesuada at, fringilla nec, risus. Integer enim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin bibendum felis vel neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ipsum dui, euismod at, dictum eu, congue tincidunt, urna. Sed quis odio. Integer aliquam pretium augue. Vivamus nonummy, dolor vel viverra rutrum, lacus dui congue pede, vel sodales dui diam nec libero. Morbi et leo sit amet quam sollicitudin laoreet. Vivamus suscipit.
Duis arcu eros, iaculis ut, vehicula in, elementum a, sapien. Phasellus ut tellus. Integer feugiat nunc eget odio. Morbi accumsan nonummy ipsum. Donec condimentum, tortor non faucibus luctus, neque mi mollis magna, nec gravida risus elit nec ipsum. Donec nec sem. Maecenas varius libero quis diam. Curabitur pulvinar. Morbi at sem eget mauris tempor vulputate. Aenean eget turpis.
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_text(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that inline elements are positioned correctly and are repositioned
within an incremental layout.
Examine and type over the text in the window that appears. There are several
elements drawn with grey boxes. These should maintain their sizes and
relative document positions as the text is scrolled and edited.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import pyglet
from pyglet.text import caret, document, layout
doctext = '''ELEMENT.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce venenatis
pharetra libero. Phasellus lacinia nisi feugiat felis. Sed id magna in nisl
cursus consectetuer. Aliquam aliquam lectus eu magna. Praesent sit amet ipsum
vitae nisl mattis commodo. Aenean pulvinar facilisis lectus. Phasellus sodales
risus sit amet lectus. Suspendisse in turpis. Vestibulum ac mi accumsan eros
commodo tincidunt. Nullam velit. In pulvinar, dui sit amet ullamcorper dictum,
dui risus ultricies nisl, a dignissim sapien enim sit amet tortor.
Pellentesque fringilla, massa sit amet bibendum blandit, pede leo commodo mi,
eleifend feugiat neque tortor dapibus mauris. Morbi nunc arcu, tincidunt vel,
blandit non, iaculis vel, libero. Vestibulum sed metus vel velit scelerisque
varius. Vivamus a tellus. Proin nec orci vel elit molestie venenatis. Aenean
fringilla, lorem vel fringilla bibendum, nibh mi varius mi, eget semper ipsum
ligula ut urna. Nullam tempor convallis augue. Sed at dui.
Nunc faucibus pretium ipsum. Sed ultricies ligula a arcu. Pellentesque vel
urna in augue euismod hendrerit. Donec consequat. Morbi convallis nulla at
ante bibendum auctor. In augue mi, tincidunt a, porta ac, tempor sit amet,
sapien. In sollicitudin risus. Vivamus leo turpis, elementum sed, accumsan eu,
scelerisque at, augue. Ut eu tortor non sem vulputate bibendum. Fusce
ultricies ultrices lorem. In hac habitasse platea dictumst. Morbi ac ipsum.
Nam tellus sem, congue in, fermentum a, ullamcorper vel, mauris. Etiam erat
tortor, facilisis ut, blandit id, placerat sed, orci. Donec quam eros,
bibendum eu, ultricies id, mattis eu, tellus. Ut hendrerit erat vel ligula.
Sed tellus. Quisque imperdiet ornare diam.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac
turpis egestas. Sed neque quam, pretium et, malesuada sed, porttitor eu, leo.
Sed varius ornare augue. Maecenas pede dui, nonummy eu, ullamcorper sed,
lobortis id, sem. In sed leo. Nulla ornare. Curabitur dui. Cras ipsum. Cras
massa augue, sodales nec, ultricies at, fermentum in, turpis. Aenean lorem
lectus, fermentum et, lacinia quis, ullamcorper ac, purus. Pellentesque
pharetra diam at elit. Donec dolor. Aenean turpis orci, aliquam vitae,
fermentum et, consectetuer sed, lacus. Maecenas pulvinar, nisi sit amet
lobortis rhoncus, est ipsum ullamcorper mauris, nec cursus felis neque et
dolor. Nulla venenatis sapien vitae lectus. Praesent in risus. In imperdiet
adipiscing nisi. Quisque volutpat, ante sed vehicula sodales, nisi quam
bibendum turpis, id bibendum pede enim porttitor tellus. Aliquam velit.
Pellentesque at mauris quis libero fermentum cursus.
Integer bibendum scelerisque elit. Curabitur justo tellus, vehicula luctus,
consequat vitae, convallis quis, nunc. Fusce libero nulla, convallis eu,
dignissim sit amet, sagittis ac, odio. Morbi dictum tincidunt nisi. Curabitur
hendrerit. Aliquam eleifend sodales leo. Donec interdum. Nam vulputate, purus
in euismod bibendum, pede mi pellentesque dolor, at viverra quam tellus eget
pede. Suspendisse varius mi id felis. Aenean in velit eu nisi suscipit mollis.
Suspendisse vitae augue et diam volutpat luctus.
Mauris et lorem. In mauris. Morbi commodo rutrum nibh. Pellentesque lobortis.
Sed eget urna ut massa venenatis luctus. Morbi egestas purus eget ante
pulvinar vulputate. Suspendisse sollicitudin. Cras tortor erat, semper
vehicula, suscipit non, facilisis ut, est. Aenean quis libero varius nisl
fringilla mollis. Donec viverra. Phasellus mi tortor, pulvinar id, pulvinar
in, lacinia nec, massa. Curabitur lectus erat, volutpat at, volutpat at,
pharetra nec, turpis. Donec ornare nonummy leo. Donec consectetuer posuere
metus. Quisque tincidunt risus facilisis dui. Ut suscipit turpis in massa.
Aliquam erat volutpat.
'''
class TestElement(document.InlineElement):
vertex_list = None
def place(self, layout, x, y):
self.vertex_list = layout.batch.add(4, pyglet.gl.GL_QUADS,
layout.top_group,
'v2i',
('c4B', [200, 200, 200, 255] * 4))
y += self.descent
w = self.advance
h = self.ascent - self.descent
self.vertex_list.vertices[:] = (x, y,
x + w, y,
x + w, y + h,
x, y + h)
def remove(self, layout):
self.vertex_list.delete()
del self.vertex_list
class TestWindow(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.document = pyglet.text.decode_attributed(doctext)
for i in range(0, len(doctext), 300):
self.document.insert_element(i, TestElement(60, -10, 70))
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
pyglet.gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == pyglet.window.key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
pyglet.app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test content_valign = 'center' property of IncrementalTextLayout.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel. When the content height
is less than the window height, the content should be aligned to the center
of the window.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: STYLE.py 1754 2008-02-10 13:26:52Z Alex.Holkner $'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''CONTENT_VALIGN_CENTER.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquet quam sit amet enim. Donec iaculis, magna vitae imperdiet convallis, lectus sem ultricies nulla, non fringilla quam felis tempus velit. Etiam et velit. Integer euismod. Aliquam a diam. Donec sed ante. Mauris enim pede, dapibus sed, dapibus vitae, consectetuer in, est. Donec aliquam risus eu ipsum. Integer et tortor. Ut accumsan risus sed ante.
Aliquam dignissim, massa a imperdiet fermentum, orci dolor facilisis ante, ut vulputate nisi nunc sed massa. Morbi sodales hendrerit tortor. Nunc id tortor ut lacus mollis malesuada. Sed nibh tellus, rhoncus et, egestas eu, laoreet eu, urna. Vestibulum massa leo, convallis et, pharetra vitae, iaculis at, ante. Pellentesque volutpat porta enim. Morbi ac nunc eget mi pretium viverra. Pellentesque felis risus, lobortis vitae, malesuada vitae, bibendum eu, tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus dapibus tortor ac neque. Curabitur pulvinar bibendum lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla turpis leo, rhoncus vel, euismod non, consequat sed, massa. Quisque ultricies. Aliquam fringilla faucibus est. Proin nec felis eget felis suscipit vehicula.
Etiam quam. Aliquam at ligula. Aenean quis dolor. Suspendisse potenti. Sed lacinia leo eu est. Nam pede ligula, molestie nec, tincidunt vel, posuere in, tellus. Donec fringilla dictum dolor. Aenean tellus orci, viverra id, vehicula eget, tempor a, dui. Morbi eu dolor nec lacus fringilla dapibus. Nulla facilisi. Nulla posuere. Nunc interdum. Donec convallis libero vitae odio.
Aenean metus lectus, faucibus in, malesuada at, fringilla nec, risus. Integer enim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin bibendum felis vel neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ipsum dui, euismod at, dictum eu, congue tincidunt, urna. Sed quis odio. Integer aliquam pretium augue. Vivamus nonummy, dolor vel viverra rutrum, lacus dui congue pede, vel sodales dui diam nec libero. Morbi et leo sit amet quam sollicitudin laoreet. Vivamus suscipit.
Duis arcu eros, iaculis ut, vehicula in, elementum a, sapien. Phasellus ut tellus. Integer feugiat nunc eget odio. Morbi accumsan nonummy ipsum. Donec condimentum, tortor non faucibus luctus, neque mi mollis magna, nec gravida risus elit nec ipsum. Donec nec sem. Maecenas varius libero quis diam. Curabitur pulvinar. Morbi at sem eget mauris tempor vulputate. Aenean eget turpis.
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_text(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.layout.content_valign = 'center'
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test content_valign = 'bottom' property of IncrementalTextLayout.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel. When the content height
is less than the window height, the content should be aligned to the bottom
of the window.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: STYLE.py 1754 2008-02-10 13:26:52Z Alex.Holkner $'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''CONTENT_VALIGN_BOTTOM.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquet quam sit amet enim. Donec iaculis, magna vitae imperdiet convallis, lectus sem ultricies nulla, non fringilla quam felis tempus velit. Etiam et velit. Integer euismod. Aliquam a diam. Donec sed ante. Mauris enim pede, dapibus sed, dapibus vitae, consectetuer in, est. Donec aliquam risus eu ipsum. Integer et tortor. Ut accumsan risus sed ante.
Aliquam dignissim, massa a imperdiet fermentum, orci dolor facilisis ante, ut vulputate nisi nunc sed massa. Morbi sodales hendrerit tortor. Nunc id tortor ut lacus mollis malesuada. Sed nibh tellus, rhoncus et, egestas eu, laoreet eu, urna. Vestibulum massa leo, convallis et, pharetra vitae, iaculis at, ante. Pellentesque volutpat porta enim. Morbi ac nunc eget mi pretium viverra. Pellentesque felis risus, lobortis vitae, malesuada vitae, bibendum eu, tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus dapibus tortor ac neque. Curabitur pulvinar bibendum lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla turpis leo, rhoncus vel, euismod non, consequat sed, massa. Quisque ultricies. Aliquam fringilla faucibus est. Proin nec felis eget felis suscipit vehicula.
Etiam quam. Aliquam at ligula. Aenean quis dolor. Suspendisse potenti. Sed lacinia leo eu est. Nam pede ligula, molestie nec, tincidunt vel, posuere in, tellus. Donec fringilla dictum dolor. Aenean tellus orci, viverra id, vehicula eget, tempor a, dui. Morbi eu dolor nec lacus fringilla dapibus. Nulla facilisi. Nulla posuere. Nunc interdum. Donec convallis libero vitae odio.
Aenean metus lectus, faucibus in, malesuada at, fringilla nec, risus. Integer enim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin bibendum felis vel neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ipsum dui, euismod at, dictum eu, congue tincidunt, urna. Sed quis odio. Integer aliquam pretium augue. Vivamus nonummy, dolor vel viverra rutrum, lacus dui congue pede, vel sodales dui diam nec libero. Morbi et leo sit amet quam sollicitudin laoreet. Vivamus suscipit.
Duis arcu eros, iaculis ut, vehicula in, elementum a, sapien. Phasellus ut tellus. Integer feugiat nunc eget odio. Morbi accumsan nonummy ipsum. Donec condimentum, tortor non faucibus luctus, neque mi mollis magna, nec gravida risus elit nec ipsum. Donec nec sem. Maecenas varius libero quis diam. Curabitur pulvinar. Morbi at sem eget mauris tempor vulputate. Aenean eget turpis.
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_text(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.layout.content_valign = 'bottom'
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test framework for pyglet. Reads details of components and capabilities
from a requirements document, runs the appropriate unit tests.
Overview
--------
First, some definitions:
Test case:
A single test, implemented by a Python module in the tests/ directory.
Tests can be interactive (requiring the user to pass or fail them) or
non-interactive (the test passes or fails itself).
Section:
A list of test cases to be run in a specified order. Sections can
also contain other sections to an arbitrary level.
Capability:
A capability is a tag that can be applied to a test-case, which specifies
a particular instance of the test. The tester can select which
capabilities are present on their system; and only test cases matching
those capabilities will be run.
There are platform capabilities "WIN", "OSX" and "X11", which are
automatically selected by default.
The "DEVELOPER" capability is used to mark test cases which test a feature
under active development.
The "GENERIC" capability signifies that the test case is equivalent under
all platforms, and is selected by default.
Other capabilities can be specified and selected as needed. For example,
we may wish to use an "NVIDIA" or "ATI" capability to specialise a
test-case for a particular video card make.
Some tests generate regression images if enabled, so you will only
need to run through the interactive procedure once. During
subsequent runs the image shown on screen will be compared with the
regression images and passed automatically if they match. There are
command line options for enabling this feature.
By default regression images are saved in tests/regression/images/
Running tests
-------------
The test procedure is interactive (this is necessary to facilitate the
many GUI-related tests, which cannot be completely automated). With no
command-line arguments, all test cases in all sections will be run::
python tests/test.py
Before each test, a description of the test will be printed, including
some information of what you should look for, and what interactivity
is provided (including how to stop the test). Press ENTER to begin
the test.
When the test is complete, assuming there were no detectable errors
(for example, failed assertions or an exception), you will be asked
to enter a [P]ass or [F]ail. You should Fail the test if the behaviour
was not as described, and enter a short reason.
Details of each test session are logged for future use.
Command-line options:
--plan=
Specify the test plan file (defaults to tests/plan.txt)
--test-root=
Specify the top-level directory to look for unit tests in (defaults
to test/)
--capabilities=
Specify the capabilities to select, comma separated. By default this
only includes your operating system capability (X11, WIN or OSX) and
GENERIC.
--log-level=
Specify the minimum log level to write (defaults to 10: info)
--log-file=
Specify log file to write to (defaults to "pyglet.%d.log")
--regression-capture
Save regression images to disk. Use this only if the tests have
already been shown to pass.
--regression-check
Look for a regression image on disk instead of prompting the user for
passage. If a regression image is found, it is compared with the test
case using the tolerance specified below. Recommended only for
developers.
--regression-tolerance=
Specify the tolerance when comparing a regression image. A value of
2, for example, means each sample component must be +/- 2 units
of the regression image. Tolerance of 0 means images must be identical,
tolerance of 256 means images will always match (if correct dimensions).
Defaults to 2.
--regression-path=
Specify the directory to store and look for regression images.
Defaults to tests/regression/images/
--developer
Selects the DEVELOPER capability.
--no-interactive=
Don't write descriptions or prompt for confirmation; just run each
test in succcession.
After the command line options, you can specify a list of sections or test
cases to run.
Examples
--------
python tests/test.py --capabilities=GENERIC,NVIDIA,WIN window
Runs all tests in the window section with the given capabilities.
python tests/test.py --no-interactive FULLSCREEN_TOGGLE
Test just the FULLSCREEN_TOGGLE test case without prompting for input (useful
for development).
python tests/image/PIL_RGBA_SAVE.py
Run a single test outside of the test harness. Handy for development; it
is equivalent to specifying --no-interactive.
Writing tests
-------------
Add the test case to the appropriate section in the test plan (plan.txt).
Create one unit test script per test case. For example, the test for
window.FULLSCREEN_TOGGLE is located at::
tests/window/FULLSCREEN_TOGGLE.py
The test file must contain:
- A module docstring describing what the test does and what the user should
look for.
- One or more subclasses of unittest.TestCase.
- No other module-level code, except perhaps an if __name__ == '__main__'
condition for running tests stand-alone.
- Optionally, the attribute "__noninteractive = True" to specify that
the test is not interactive; doesn't require user intervention.
During development, test cases should be marked with DEVELOPER. Once finished
add the WIN, OSX and X11 capabilities, or GENERIC if it's platform
independent.
Writing regression tests
------------------------
Your test case should subclass tests.regression.ImageRegressionTestCase
instead of unitttest.TestCase. At the point where the buffer (window
image) should be checked/saved, call self.capture_regression_image().
If this method returns True, you can exit straight away (regression
test passed), otherwise continue running interactively (regression image
was captured, wait for user confirmation). You can call
capture_regression_image() several times; only the final image will be
used.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import array
import logging
import os
import optparse
import re
import sys
import time
import unittest
# So we can find tests.regression and ensure local pyglet copy is tested.
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
import tests.regression
import pyglet.image
regressions_path = os.path.join(os.path.dirname(__file__),
'regression', 'images')
class TestCase(object):
def __init__(self, name):
self.name = name
self.short_name = name.split('.')[-1]
self.capabilities = set()
def get_module_filename(self, root=''):
path = os.path.join(*self.name.split('.'))
return '%s.py' % os.path.join(root, path)
def get_module(self, root=''):
name = 'tests.%s' % self.name
module = __import__(name)
for c in name.split('.')[1:]:
module = getattr(module, c)
return module
def get_regression_image_filename(self):
return os.path.join(regressions_path, '%s.png' % self.name)
def test(self, options):
if not options.capabilities.intersection(self.capabilities):
return
options.log.info('Testing %s.', self)
if options.pretend:
return
module = None
try:
module = self.get_module(options.test_root)
except IOError:
options.log.warning('No test exists for %s', self)
except Exception:
options.log.exception('Cannot load test for %s', self)
if not module:
return
module_interactive = options.interactive
if hasattr(module, '__noninteractive') and \
getattr(module, '__noninteractive'):
module_interactive = False
if options.regression_check and \
os.path.exists(self.get_regression_image_filename()):
result = RegressionCheckTestResult(
self, options.regression_tolerance)
module_interactive = False
elif options.regression_capture:
result = RegressionCaptureTestResult(self)
else:
result = StandardTestResult(self)
print('-' * 78)
options.completed_tests += 1
print("Running Test: %s (%d/%d)\n" % (self, options.completed_tests, options.num_tests))
if module.__doc__:
print(' ' + module.__doc__.replace('\n','\n '))
if module_interactive:
raw_input('Press return to begin test...')
suite = unittest.TestLoader().loadTestsFromModule(module)
options.log.info('Begin unit tests for %s', self)
suite(result)
for failure in result.failures:
options.log.error('Failure in %s', self)
options.log.error(failure[1])
for error in result.errors:
options.log.error('Error in %s', self)
options.log.error(error[1])
options.log.info('%d tests run', result.testsRun)
num_failures = len(result.failures)
num_errors = len(result.errors)
if num_failures or num_errors:
print('%d Failures and %d Errors detected.' % (num_failures, num_errors))
if (module_interactive and
len(result.failures) == 0 and
len(result.errors) == 0):
# print(module.__doc__)
user_result = raw_input('[P]assed test, [F]ailed test: ')
if user_result and user_result.strip()[0] in ('F', 'f'):
print('Enter failure description: ')
description = raw_input('> ')
options.log.error('User marked fail for %s', self)
options.log.error(description)
else:
options.log.info('User marked pass for %s', self)
result.setUserPass()
def __repr__(self):
return 'TestCase(%s)' % self.name
def __str__(self):
return self.name
def __cmp__(self, other):
return cmp(str(self), str(other))
def num_tests(self):
return 1
class TestSection(object):
def __init__(self, name):
self.name = name
self.children = []
def add(self, child):
# child can be TestSection or TestCase
self.children.append(child)
def test(self, options):
for child in self.children:
child.test(options)
def __repr__(self):
return 'TestSection(%s)' % self.name
def num_tests(self):
return sum([c.num_tests() for c in self.children])
class TestPlan(TestSection):
def __init__(self):
self.root = None
self.names = {}
@classmethod
def from_file(cls, file):
plan = TestPlan()
plan.root = TestSection('{root}')
plan.root.indent = None
# Section stack
sections = [plan.root]
if not hasattr(file, 'read'):
file = open(file, 'r')
line_number = 0
for line in file:
line_number += 1
# Skip empty lines
if not line.strip():
continue
# Skip comments
if line[0] == '#':
continue
indent = len(line) - len(line.lstrip())
while (sections and sections[-1].indent and
sections[-1].indent > indent):
sections.pop()
if sections[-1].indent is None:
sections[-1].indent = indent
if sections[-1].indent != indent:
raise Exception('Indentation mismatch line %d' % line_number)
if '.' in line:
tokens = line.strip().split()
test_case = TestCase(tokens[0])
test_case.capabilities = set(tokens[1:])
sections[-1].add(test_case)
plan.names[test_case.name] = test_case
plan.names[test_case.short_name] = test_case
else:
section = TestSection(line.strip())
section.indent = None
sections[-1].add(section)
sections.append(section)
plan.names[section.name] = section
return plan
class StandardTestResult(unittest.TestResult):
def __init__(self, component):
super(StandardTestResult, self).__init__()
def setUserPass(self):
pass
class RegressionCaptureTestResult(unittest.TestResult):
def __init__(self, component):
super(RegressionCaptureTestResult, self).__init__()
self.component = component
self.captured_image = None
def startTest(self, test):
super(RegressionCaptureTestResult, self).startTest(test)
if isinstance(test, tests.regression.ImageRegressionTestCase):
test._enable_regression_image = True
def addSuccess(self, test):
super(RegressionCaptureTestResult, self).addSuccess(test)
assert self.captured_image is None
if isinstance(test, tests.regression.ImageRegressionTestCase):
self.captured_image = test._captured_image
def setUserPass(self):
if self.captured_image:
filename = self.component.get_regression_image_filename()
self.captured_image.save(filename)
logging.getLogger().info('Wrote regression image %s' % filename)
class Regression(Exception):
pass
def buffer_equal(a, b, tolerance=0):
if tolerance == 0:
return a == b
if len(a) != len(b):
return False
a = array.array('B', a)
b = array.array('B', b)
for i in range(len(a)):
if abs(a[i] - b[i]) > tolerance:
return False
return True
class RegressionCheckTestResult(unittest.TestResult):
def __init__(self, component, tolerance):
super(RegressionCheckTestResult, self).__init__()
self.filename = component.get_regression_image_filename()
self.regression_image = pyglet.image.load(self.filename)
self.tolerance = tolerance
def startTest(self, test):
super(RegressionCheckTestResult, self).startTest(test)
if isinstance(test, tests.regression.ImageRegressionTestCase):
test._enable_regression_image = True
test._enable_interactive = False
logging.getLogger().info('Using regression %s' % self.filename)
def addSuccess(self, test):
# Check image
ref_image = self.regression_image.image_data
this_image = test._captured_image.image_data
this_image.format = ref_image.format
this_image.pitch = ref_image.pitch
if this_image.width != ref_image.width:
self.addFailure(test,
'Buffer width does not match regression image')
elif this_image.height != ref_image.height:
self.addFailure(test,
'Buffer height does not match regression image')
elif not buffer_equal(this_image.data, ref_image.data,
self.tolerance):
self.addFailure(test,
'Buffer does not match regression image')
else:
super(RegressionCheckTestResult, self).addSuccess(test)
def addFailure(self, test, err):
err = Regression(err)
super(RegressionCheckTestResult, self).addFailure(test, (Regression,
err, []))
def main():
capabilities = ['GENERIC']
platform_capabilities = {
'linux': 'X11',
'linux2': 'X11',
'linux3': 'X11',
'win32': 'WIN',
'cygwin': 'WIN',
'darwin': 'OSX'
}
if sys.platform in platform_capabilities:
capabilities.append(platform_capabilities[sys.platform])
script_root = os.path.dirname(__file__)
plan_filename = os.path.normpath(os.path.join(script_root, 'plan.txt'))
test_root = script_root
op = optparse.OptionParser()
op.usage = 'test.py [options] [components]'
op.add_option('--plan', help='test plan file', default=plan_filename)
op.add_option('--test-root', default=script_root,
help='directory containing test cases')
op.add_option('--capabilities', help='selected test capabilities',
default=','.join(capabilities))
op.add_option('--log-level', help='verbosity of logging',
default=10, type='int')
op.add_option('--log-file', help='log to FILE', metavar='FILE',
default='pyglet.%d.log')
op.add_option('--regression-path', metavar='DIR', default=regressions_path,
help='locate regression images in DIR')
op.add_option('--regression-tolerance', type='int', default=2,
help='tolerance for comparing regression images')
op.add_option('--regression-check', action='store_true',
help='enable image regression checks')
op.add_option('--regression-capture', action='store_true',
help='enable image regression capture')
op.add_option('--no-interactive', action='store_false', default=True,
dest='interactive', help='disable interactive prompting')
op.add_option('--developer', action='store_true',
help='add DEVELOPER capability')
op.add_option('--pretend', action='store_true',
help='print selected test cases only')
options, args = op.parse_args()
options.capabilities = set(options.capabilities.split(','))
if options.developer:
options.capabilities.add('DEVELOPER')
if options.regression_capture:
try:
os.makedirs(regressions_path)
except OSError:
pass
if '%d' in options.log_file:
i = 1
while os.path.exists(options.log_file % i):
i += 1
options.log_file = options.log_file % i
print('Test results are saved in log file:', options.log_file)
logging.basicConfig(filename=options.log_file, level=options.log_level, format='%(levelname)s %(message)s')
options.log = logging.getLogger()
options.log.info('Beginning test at %s', time.ctime())
options.log.info('Capabilities are: %s', ', '.join(options.capabilities))
options.log.info('sys.platform = %s', sys.platform)
options.log.info('pyglet.version = %s', pyglet.version)
options.log.info('Reading test plan from %s', options.plan)
plan = TestPlan.from_file(options.plan)
errors = False
if args:
components = []
for arg in args:
try:
component = plan.names[arg]
components.append(component)
except KeyError:
options.log.error('Unknown test case or section "%s"', arg)
errors = True
else:
components = [plan.root]
if not errors:
options.num_tests = sum([c.num_tests() for c in components])
options.completed_tests = 0
for component in components:
component.test(options)
print('-' * 78)
print('Test results are saved in log file:', options.log_file)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
'''Test that a scheduled function gets called every interval with the correct
time delta.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $'
import time
import unittest
from pyglet import clock
__noninteractive = True
class SCHEDULE_INTERVAL(unittest.TestCase):
callback_1_count = 0
callback_2_count = 0
callback_3_count = 0
def callback_1(self, dt):
self.assertTrue(abs(dt - 0.1) < 0.06)
self.callback_1_count += 1
def callback_2(self, dt):
self.assertTrue(abs(dt - 0.35) < 0.06)
self.callback_2_count += 1
def callback_3(self, dt):
self.assertTrue(abs(dt - 0.07) < 0.06)
self.callback_3_count += 1
def clear(self):
self.callback_1_count = 0
self.callback_2_count = 0
self.callback_3_count = 0
def test_schedule_interval(self):
self.clear()
clock.set_default(clock.Clock())
clock.schedule_interval(self.callback_1, 0.1)
clock.schedule_interval(self.callback_2, 0.35)
clock.schedule_interval(self.callback_3, 0.07)
t = 0
while t < 2.04: # number chosen to avoid +/- 1 errors in div
t += clock.tick()
self.assertTrue(self.callback_1_count == int(t / 0.1))
self.assertTrue(self.callback_2_count == int(t / 0.35))
self.assertTrue(self.callback_3_count == int(t / 0.07))
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the clock effectively limits the FPS to 20 Hz when requested.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import time
import unittest
from pyglet import clock
__noninteractive = True
class FPS_LIMIT(unittest.TestCase):
def test_fps_limit(self):
clock.set_default(clock.Clock())
clock.set_fps_limit(20)
self.assertTrue(clock.get_fps() == 0)
t1 = time.time()
clock.tick() # One to get it going
for i in range(20):
clock.tick()
t2 = time.time()
self.assertTrue(abs((t2 - t1) - 1.) < 0.05)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that a scheduled function gets called every tick with the correct
time delta.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $'
import time
import unittest
from pyglet import clock
__noninteractive = True
class SCHEDULE(unittest.TestCase):
callback_dt = None
callback_count = 0
def callback(self, dt):
self.callback_dt = dt
self.callback_count += 1
def test_schedule(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
self.callback_dt = None
time.sleep(1)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
self.callback_dt = None
time.sleep(1)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
def test_unschedule(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
self.callback_dt = None
time.sleep(1)
clock.unschedule(self.callback)
result = clock.tick()
self.assertTrue(self.callback_dt == None)
def test_schedule_multiple(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
clock.schedule(self.callback)
self.callback_count = 0
clock.tick()
self.assertTrue(self.callback_count == 2)
clock.tick()
self.assertTrue(self.callback_count == 4)
def test_schedule_multiple(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
clock.schedule(self.callback)
self.callback_count = 0
clock.tick()
self.assertTrue(self.callback_count == 2)
clock.unschedule(self.callback)
clock.tick()
self.assertTrue(self.callback_count == 2)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the clock tick function returns the elaspsed time between
frames, in seconds.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import time
import unittest
from pyglet import clock
__noninteractive = True
class TICK(unittest.TestCase):
def test_tick(self):
clock.set_default(clock.Clock())
result = clock.tick()
self.assertTrue(result == 0)
time.sleep(1)
result_1 = clock.tick()
time.sleep(1)
result_2 = clock.tick()
self.assertTrue(abs(result_1 - 1.0) < 0.05)
self.assertTrue(abs(result_2 - 1.0) < 0.05)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that a scheduled function gets called every once with the correct
time delta.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $'
import time
import unittest
from pyglet import clock
__noninteractive = True
class SCHEDULE_ONCE(unittest.TestCase):
callback_1_count = 0
callback_2_count = 0
callback_3_count = 0
def callback_1(self, dt):
self.assertTrue(abs(dt - 0.1) < 0.01)
self.callback_1_count += 1
def callback_2(self, dt):
self.assertTrue(abs(dt - 0.35) < 0.01)
self.callback_2_count += 1
def callback_3(self, dt):
self.assertTrue(abs(dt - 0.07) < 0.01)
self.callback_3_count += 1
def clear(self):
self.callback_1_count = 0
self.callback_2_count = 0
self.callback_3_count = 0
def test_schedule_once(self):
self.clear()
clock.set_default(clock.Clock())
clock.schedule_once(self.callback_1, 0.1)
clock.schedule_once(self.callback_2, 0.35)
clock.schedule_once(self.callback_3, 0.07)
t = 0
while t < 1:
t += clock.tick()
self.assertTrue(self.callback_1_count == 1)
self.assertTrue(self.callback_2_count == 1)
self.assertTrue(self.callback_3_count == 1)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that a scheduled function gets called every interval with the correct
time delta.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $'
import time
import unittest
from pyglet import clock
__noninteractive = True
class SCHEDULE_INTERVAL(unittest.TestCase):
callback_1_count = 0
callback_2_count = 0
callback_3_count = 0
def callback_1(self, dt):
self.assertTrue(abs(dt - 0.1) < 0.06)
self.callback_1_count += 1
def callback_2(self, dt):
self.assertTrue(abs(dt - 0.35) < 0.06)
self.callback_2_count += 1
def callback_3(self, dt):
self.assertTrue(abs(dt - 0.07) < 0.06)
self.callback_3_count += 1
def clear(self):
self.callback_1_count = 0
self.callback_2_count = 0
self.callback_3_count = 0
def test_schedule_interval(self):
self.clear()
clock.set_default(clock.Clock())
clock.schedule_interval(self.callback_1, 0.1)
clock.schedule_interval(self.callback_2, 0.35)
clock.schedule_interval(self.callback_3, 0.07)
t = 0
while t < 2.04: # number chosen to avoid +/- 1 errors in div
t += clock.tick()
self.assertTrue(self.callback_1_count == int(t / 0.1))
self.assertTrue(self.callback_2_count == int(t / 0.35))
self.assertTrue(self.callback_3_count == int(t / 0.07))
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
# Contributed by Claudio Canepa
# Integrated by Ben Smith
""" There is the possibility that time.clock be non monotonic in multicore hardware,
due to the underlaying use of win32 QueryPerformanceCounter.
If your update is seeing a negative dt, then time.clock is probably the culprit.
AMD or Intel Patches for multicore may fix this problem (if you see it at all)"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import time
import unittest
__noninteractive = True
class MULTICORE(unittest.TestCase):
def test_multicore(self):
failures = 0
old_time = time.clock()
end_time = time.time() + 3
while time.time() < end_time:
t = time.clock()
if t < old_time:
failures += 1
old_time = t
time.sleep(0.001)
self.assertTrue(failures == 0)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that a scheduled function gets called every tick with the correct
time delta.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $'
import time
import unittest
from pyglet import clock
__noninteractive = True
class SCHEDULE(unittest.TestCase):
callback_dt = None
callback_count = 0
def callback(self, dt):
self.callback_dt = dt
self.callback_count += 1
def test_schedule(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
self.callback_dt = None
time.sleep(1)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
self.callback_dt = None
time.sleep(1)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
def test_unschedule(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
self.callback_dt = None
time.sleep(1)
clock.unschedule(self.callback)
result = clock.tick()
self.assertTrue(self.callback_dt == None)
def test_schedule_multiple(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
clock.schedule(self.callback)
self.callback_count = 0
clock.tick()
self.assertTrue(self.callback_count == 2)
clock.tick()
self.assertTrue(self.callback_count == 4)
def test_schedule_multiple(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
clock.schedule(self.callback)
self.callback_count = 0
clock.tick()
self.assertTrue(self.callback_count == 2)
clock.unschedule(self.callback)
clock.tick()
self.assertTrue(self.callback_count == 2)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the clock effectively limits the FPS to 20 Hz when requested.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import time
import unittest
from pyglet import clock
__noninteractive = True
class FPS_LIMIT(unittest.TestCase):
def test_fps_limit(self):
clock.set_default(clock.Clock())
clock.set_fps_limit(20)
self.assertTrue(clock.get_fps() == 0)
t1 = time.time()
clock.tick() # One to get it going
for i in range(20):
clock.tick()
t2 = time.time()
self.assertTrue(abs((t2 - t1) - 1.) < 0.05)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the clock returns a reasonable average FPS calculation when
stimulated at 5 Hz.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import time
import unittest
from pyglet import clock
__noninteractive = True
class FPS(unittest.TestCase):
def test_fps(self):
clock.set_default(clock.Clock())
self.assertTrue(clock.get_fps() == 0)
for i in range(10):
time.sleep(0.2)
clock.tick()
result = clock.get_fps()
self.assertTrue(abs(result - 5.0) < 0.05)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
# Contributed by Claudio Canepa
# Integrated by Ben Smith
""" There is the possibility that time.clock be non monotonic in multicore hardware,
due to the underlaying use of win32 QueryPerformanceCounter.
If your update is seeing a negative dt, then time.clock is probably the culprit.
AMD or Intel Patches for multicore may fix this problem (if you see it at all)"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import time
import unittest
__noninteractive = True
class MULTICORE(unittest.TestCase):
def test_multicore(self):
failures = 0
old_time = time.clock()
end_time = time.time() + 3
while time.time() < end_time:
t = time.clock()
if t < old_time:
failures += 1
old_time = t
time.sleep(0.001)
self.assertTrue(failures == 0)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the clock returns a reasonable average FPS calculation when
stimulated at 5 Hz.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import time
import unittest
from pyglet import clock
__noninteractive = True
class FPS(unittest.TestCase):
def test_fps(self):
clock.set_default(clock.Clock())
self.assertTrue(clock.get_fps() == 0)
for i in range(10):
time.sleep(0.2)
clock.tick()
result = clock.get_fps()
self.assertTrue(abs(result - 5.0) < 0.05)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the clock tick function returns the elaspsed time between
frames, in seconds.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import time
import unittest
from pyglet import clock
__noninteractive = True
class TICK(unittest.TestCase):
def test_tick(self):
clock.set_default(clock.Clock())
result = clock.tick()
self.assertTrue(result == 0)
time.sleep(1)
result_1 = clock.tick()
time.sleep(1)
result_2 = clock.tick()
self.assertTrue(abs(result_1 - 1.0) < 0.05)
self.assertTrue(abs(result_2 - 1.0) < 0.05)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that a scheduled function gets called every once with the correct
time delta.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $'
import time
import unittest
from pyglet import clock
__noninteractive = True
class SCHEDULE_ONCE(unittest.TestCase):
callback_1_count = 0
callback_2_count = 0
callback_3_count = 0
def callback_1(self, dt):
self.assertTrue(abs(dt - 0.1) < 0.01)
self.callback_1_count += 1
def callback_2(self, dt):
self.assertTrue(abs(dt - 0.35) < 0.01)
self.callback_2_count += 1
def callback_3(self, dt):
self.assertTrue(abs(dt - 0.07) < 0.01)
self.callback_3_count += 1
def clear(self):
self.callback_1_count = 0
self.callback_2_count = 0
self.callback_3_count = 0
def test_schedule_once(self):
self.clear()
clock.set_default(clock.Clock())
clock.schedule_once(self.callback_1, 0.1)
clock.schedule_once(self.callback_2, 0.35)
clock.schedule_once(self.callback_3, 0.07)
t = 0
while t < 1:
t += clock.tick()
self.assertTrue(self.callback_1_count == 1)
self.assertTrue(self.callback_2_count == 1)
self.assertTrue(self.callback_3_count == 1)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import pyglet
from graphics_common import *
__noninteractive = True
class TEST_CASE(unittest.TestCase):
def check(self, expected, result, dimensions):
if len(expected) != len(result) * dimensions / 4:
self.fail('Incorrect number of vertices in feedback array')
for d in range(2):
for e, r in zip(expected[d::dimensions], result[d::4]):
if abs(e - r) > 0.01:
self.fail('Feedback array is in error: %r, %r' % \
(e, r))
def generic_test(self, v_fmt, v_data,
c_fmt=None, c_data=None,
t_fmt=None, t_data=None):
data = [(v_fmt, v_data)]
n_v = int(v_fmt[1])
if c_fmt:
data.append((c_fmt, c_data))
n_c = int(c_fmt[1])
if t_fmt:
data.append((t_fmt, t_data))
n_t = int(t_fmt[1])
vertex_list = pyglet.graphics.vertex_list_indexed(
n_vertices, index_data, *data)
vertices, colors, tex_coords = get_feedback(lambda: \
vertex_list.draw(GL_TRIANGLES))
self.check(get_ordered_data(v_data, n_v), vertices, n_v)
if c_fmt:
self.check(get_ordered_data(c_data, n_c), colors, n_c)
if t_fmt:
self.check(get_ordered_data(t_data, n_t), tex_coords, n_t)
def test_v2f(self):
self.generic_test('v2f', v2f_data)
def test_v3f(self):
self.generic_test('v3f', v3f_data)
def test_v2f_c3f(self):
self.generic_test('v2f', v2f_data, 'c3f', c3f_data)
def test_v2f_c4f(self):
self.generic_test('v2f', v2f_data, 'c4f', c4f_data)
def test_v3f_c3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data)
def test_v3f_c4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data)
def test_v2f_t2f(self):
self.generic_test('v2f', v2f_data, None, None, 't2f', t2f_data)
def test_v3f_c3f_t2f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't2f', t2f_data)
def test_v3f_c3f_t3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't3f', t3f_data)
def test_v3f_c4f_t4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data, 't4f', t4f_data)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# $Id:$
import unittest
import pyglet
from graphics_common import *
__noninteractive = True
class TEST_CASE(unittest.TestCase):
def check(self, expected, result, dimensions):
if len(expected) != len(result) * dimensions / 4:
self.fail('Incorrect number of vertices in feedback array')
for d in range(2): # Don't check Z or W
for e, r in zip(expected[d::dimensions], result[d::4]):
if abs(e - r) > 0.01:
self.fail('Feedback array is in error: %r, %r' % \
(e, r))
def generic_test(self, v_fmt, v_data,
c_fmt=None, c_data=None,
t_fmt=None, t_data=None):
data = [(v_fmt, v_data)]
n_v = int(v_fmt[1])
if c_fmt:
data.append((c_fmt, c_data))
n_c = int(c_fmt[1])
if t_fmt:
data.append((t_fmt, t_data))
n_t = int(t_fmt[1])
vertices, colors, tex_coords = get_feedback(lambda: \
pyglet.graphics.draw(n_vertices, GL_TRIANGLES, *data))
self.check(v_data, vertices, n_v)
if c_fmt:
self.check(c_data, colors, n_c)
if t_fmt:
self.check(t_data, tex_coords, n_t)
def test_v2f(self):
self.generic_test('v2f', v2f_data)
def test_v3f(self):
self.generic_test('v3f', v3f_data)
def test_v2f_c3f(self):
self.generic_test('v2f', v2f_data, 'c3f', c3f_data)
def test_v2f_c4f(self):
self.generic_test('v2f', v2f_data, 'c4f', c4f_data)
def test_v3f_c3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data)
def test_v3f_c4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data)
def test_v2f_t2f(self):
self.generic_test('v2f', v2f_data, None, None, 't2f', t2f_data)
def test_v3f_c3f_t2f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't2f', t2f_data)
def test_v3f_c3f_t3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't3f', t3f_data)
def test_v3f_c4f_t4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data, 't4f', t4f_data)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# $Id:$
import random
import unittest
from pyglet.graphics import allocation
__noninteractive = True
class Region(object):
def __init__(self, start, size):
self.start = start
self.size = size
def __repr__(self):
return 'Region(%r, %r)' % (self.start, self.size)
class RegionAllocator(object):
def __init__(self, capacity):
self.allocator = allocation.Allocator(capacity)
self.regions = []
def check_region(self, region):
region_end = region.start + region.size
for other in self.regions:
if region is other:
continue
other_end = other.start + other.size
if (other.start < region.start and other_end > region.start) or \
(other.start < region_end and other_end > region_end):
fixture.fail('%r overlaps with %r' % (
region, other))
def check_coverage(self):
starts, sizes = self.allocator.get_allocated_regions()
if len(starts) != len(sizes):
fixture.fail('Length of starts (%d) does not match sizes (%d)' % \
(len(starts), len(sizes)))
if not starts and not self.regions:
return
self.regions.sort(key=lambda r: r.start)
regions = iter(self.regions)
blocks = iter(zip(starts, sizes))
block_start, block_size = blocks.next()
block_used = False
try:
while True:
region = regions.next()
block_used = True
if region.start < block_start:
fixture.fail('Start of %r was not covered at %d' % (
region, block_start))
elif region.start > block_start:
fixture.fail('Uncovered block from %d to %r' % (
block_start, region))
block_start += region.size
block_size -= region.size
if block_size < 0:
fixture.fail('%r extended past end of block by %d' % \
(region, -block_size))
elif block_size == 0:
block_start, block_size = blocks.next()
block_used = False
except StopIteration:
pass
if not block_used:
fixture.fail('Uncovered block(s) from %d' % block_start)
try:
block_start, block_size = blocks.next()
fixture.fail('Uncovered block(s) from %d' % block_start)
except StopIteration:
pass
try:
region = regions.next()
fixture.fail('%r was not covered')
except StopIteration:
pass
def check_redundancy(self):
# Ensure there are no adjacent blocks (they should have been merged)
starts, sizes = self.allocator.get_allocated_regions()
last = -1
for start, size in zip(starts, sizes):
if start < last:
fixture.fail('Block at %d is out of order' % start)
if start == last:
fixture.fail('Block at %d is redundant' % start)
last = start + size
def alloc(self, size):
start = self.allocator.alloc(size)
region = Region(start, size)
self.check_region(region)
self.regions.append(region)
self.check_coverage()
self.check_redundancy()
return region
def dealloc(self, region):
assert region in self.regions
self.allocator.dealloc(region.start, region.size)
self.regions.remove(region)
self.check_coverage()
self.check_redundancy()
def realloc(self, region, size):
assert region in self.regions
region.start = self.allocator.realloc(region.start, region.size, size)
region.size = size
self.check_region(region)
self.check_coverage()
self.check_redundancy()
def force_alloc(self, size):
try:
return self.alloc(size)
except allocation.AllocatorMemoryException, e:
self.allocator.set_capacity(e.requested_capacity)
return self.alloc(size)
def force_realloc(self, region, size):
try:
self.realloc(region, size)
except allocation.AllocatorMemoryException, e:
self.allocator.set_capacity(e.requested_capacity)
self.realloc(region, size)
def get_free_size(self):
return self.allocator.get_free_size()
capacity = property(lambda self: self.allocator.capacity)
class TestAllocation(unittest.TestCase):
def setUp(self):
global fixture
fixture = self
def test_alloc1(self):
capacity = 10
allocator = RegionAllocator(capacity)
for i in range(capacity):
allocator.alloc(1)
def test_alloc2(self):
capacity = 10
allocator = RegionAllocator(capacity)
for i in range(capacity//2):
allocator.alloc(2)
def test_alloc3(self):
capacity = 10
allocator = RegionAllocator(capacity)
for i in range(capacity//3):
allocator.alloc(3)
def test_alloc_mix1_2(self):
allocs = [1, 2] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
for alloc in allocs:
allocator.alloc(alloc)
def test_alloc_mix5_3_7(self):
allocs = [5, 3, 7] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
for alloc in allocs:
allocator.alloc(alloc)
def test_dealloc_1_order_all(self):
capacity = 10
allocator = RegionAllocator(capacity)
regions = []
for i in range(capacity):
regions.append(allocator.alloc(1))
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_1_order(self):
capacity = 15
allocator = RegionAllocator(capacity)
regions = []
for i in range(10):
regions.append(allocator.alloc(1))
for region in regions:
allocator.dealloc(region)
def test_dealloc_1_reverse_all(self):
capacity = 10
allocator = RegionAllocator(capacity)
regions = []
for i in range(capacity):
regions.append(allocator.alloc(1))
for region in regions[::-1]:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_1_reverse(self):
capacity = 15
allocator = RegionAllocator(capacity)
regions = []
for i in range(10):
regions.append(allocator.alloc(1))
for region in regions[::-1]:
allocator.dealloc(region)
def test_dealloc_mix1_2_order(self):
allocs = [1, 2] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
regions = []
for alloc in allocs:
regions.append(allocator.alloc(alloc))
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_mix5_3_7_order(self):
allocs = [5, 3, 7] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
regions = []
for alloc in allocs:
regions.append(allocator.alloc(alloc))
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_1_outoforder(self):
random.seed(1)
capacity = 15
allocator = RegionAllocator(capacity)
regions = []
for i in range(capacity):
regions.append(allocator.alloc(1))
random.shuffle(regions)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_mix1_2_outoforder(self):
random.seed(1)
allocs = [1, 2] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
regions = []
for alloc in allocs:
regions.append(allocator.alloc(alloc))
random.shuffle(regions)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_mix5_3_7_outoforder(self):
random.seed(1)
allocs = [5, 3, 7] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
regions = []
for alloc in allocs:
regions.append(allocator.alloc(alloc))
random.shuffle(regions)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def mixed_alloc_dealloc_list(self, choices, count=10, seed=1):
random.seed(seed)
allocs = []
live = []
j = 0
for i in range(count):
if live:
if random.random() < .5:
allocs.append(random.choice(choices))
live.append(j)
j += 1
else:
k = random.choice(live)
live.remove(k)
allocs.append(-k)
else:
allocs.append(random.choice(choices))
live.append(j)
j += 1
for j in live:
allocs.append(-j)
return allocs
def test_mix_alloc_dealloc1(self):
allocs = self.mixed_alloc_dealloc_list([1])
capacity = sum([a for a in allocs if a > 0])
allocator= RegionAllocator(capacity)
regions = []
for alloc in allocs:
if alloc > 0:
regions.append(allocator.alloc(alloc))
else:
region = regions[abs(alloc)]
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_mix_alloc_dealloc5_3_7(self):
allocs = self.mixed_alloc_dealloc_list([5, 3, 7], count=50)
capacity = sum([a for a in allocs if a > 0])
allocator= RegionAllocator(capacity)
regions = []
for alloc in allocs:
if alloc > 0:
regions.append(allocator.alloc(alloc))
else:
region = regions[abs(alloc)]
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_realloc1_2(self):
allocator = RegionAllocator(30)
regions = []
for i in range(10):
regions.append(allocator.alloc(1))
for region in regions:
allocator.realloc(region, 2)
for region in regions:
allocator.dealloc(region)
def test_realloc2_1(self):
allocator = RegionAllocator(20)
regions = []
for i in range(10):
regions.append(allocator.alloc(2))
for region in regions:
allocator.realloc(region, 1)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_realloc_2_1_2(self):
allocator = RegionAllocator(30)
regions = []
for i in range(10):
regions.append(allocator.alloc(2))
for region in regions:
allocator.realloc(region, 1)
for region in regions:
allocator.realloc(region, 2)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_realloc_3_1_5_4_6(self):
allocator = RegionAllocator(1000)
regions = []
for i in range(10):
regions.append(allocator.alloc(3))
for region in regions:
allocator.realloc(region, 1)
for region in regions:
allocator.realloc(region, 5)
for region in regions:
allocator.realloc(region, 4)
for region in regions:
allocator.realloc(region, 6)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_realloc_3_1_5_4_6_sequential(self):
allocator = RegionAllocator(1000)
regions = []
for i in range(10):
regions.append(allocator.alloc(3))
for region in regions:
allocator.realloc(region, 1)
allocator.realloc(region, 5)
allocator.realloc(region, 4)
allocator.realloc(region, 6)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_resize1(self):
allocator = RegionAllocator(1)
regions = []
for i in range(10):
regions.append(allocator.force_alloc(3))
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_mix_resize(self):
# Try a bunch of stuff. There is not much method to this madness.
allocator = RegionAllocator(1)
regions = []
for i in range(10):
regions.append(allocator.force_alloc(3))
for region in regions[:5]:
#import pdb; pdb.set_trace()
allocator.force_realloc(region, 8)
for i in range(10):
regions.append(allocator.force_alloc(i + 1))
for region in regions[5:15]:
allocator.force_realloc(region, 5)
for region in regions[3:18:2]:
allocator.dealloc(region)
regions.remove(region)
for i in range(5):
regions.append(allocator.force_alloc(3))
for region in regions[-10:]:
allocator.force_realloc(region, 6)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import pyglet
from graphics_common import *
__noninteractive = True
class TEST_CASE(unittest.TestCase):
def check(self, expected, result, dimensions):
if len(expected) != len(result) * dimensions / 4:
self.fail('Incorrect number of vertices in feedback array')
for d in range(2):
for e, r in zip(expected[d::dimensions], result[d::4]):
if abs(e - r) > 0.01:
self.fail('Feedback array is in error: %r, %r' % \
(e, r))
def generic_test(self, v_fmt, v_data,
c_fmt=None, c_data=None,
t_fmt=None, t_data=None):
data = [(v_fmt, v_data)]
n_v = int(v_fmt[1])
if c_fmt:
data.append((c_fmt, c_data))
n_c = int(c_fmt[1])
if t_fmt:
data.append((t_fmt, t_data))
n_t = int(t_fmt[1])
vertices, colors, tex_coords = get_feedback(lambda: \
pyglet.graphics.draw_indexed(n_vertices, GL_TRIANGLES, index_data,
*data))
self.check(get_ordered_data(v_data, n_v), vertices, n_v)
if c_fmt:
self.check(get_ordered_data(c_data, n_c), colors, n_c)
if t_fmt:
self.check(get_ordered_data(t_data, n_t), tex_coords, n_t)
def test_v2f(self):
self.generic_test('v2f', v2f_data)
def test_v3f(self):
self.generic_test('v3f', v3f_data)
def test_v2f_c3f(self):
self.generic_test('v2f', v2f_data, 'c3f', c3f_data)
def test_v2f_c4f(self):
self.generic_test('v2f', v2f_data, 'c4f', c4f_data)
def test_v3f_c3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data)
def test_v3f_c4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data)
def test_v2f_t2f(self):
self.generic_test('v2f', v2f_data, None, None, 't2f', t2f_data)
def test_v3f_c3f_t2f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't2f', t2f_data)
def test_v3f_c3f_t3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't3f', t3f_data)
def test_v3f_c4f_t4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data, 't4f', t4f_data)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from operator import add
import random
from pyglet.gl import *
n_vertices = 42
v3f_data = [v/float(n_vertices*3 + 10) for v in range(n_vertices * 3)]
v2f_data = reduce(add, zip(v3f_data[::3], v3f_data[1::3]))
c4f_data = [v/float(n_vertices*4) for v in range(n_vertices * 4)]
c3f_data = reduce(add, zip(c4f_data[::4], c4f_data[1::4], c4f_data[2::4]))
t4f_data = [v/float(n_vertices*4 + 5) for v in range(n_vertices * 4)]
t3f_data = reduce(add, zip(t4f_data[::4], t4f_data[1::4], t4f_data[2::4]))
t2f_data = reduce(add, zip(t3f_data[::3], t3f_data[1::3]))
index_data = range(n_vertices)
random.seed(1)
random.shuffle(index_data)
def get_ordered_data(data, dimensions):
ordered = []
for i in index_data:
ordered.extend(data[i * dimensions:(i+1)*dimensions])
return ordered
feedback_buffer = (GLfloat * 8096)()
def get_feedback(func):
# Project in clip coords
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, 1, 0, 1, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glFeedbackBuffer(len(feedback_buffer), GL_4D_COLOR_TEXTURE, feedback_buffer)
glRenderMode(GL_FEEDBACK)
func()
size = glRenderMode(GL_RENDER)
buffer = feedback_buffer[:size]
vertices = []
colors = []
tex_coords = []
while buffer:
token = int(buffer.pop(0))
assert token == GL_POLYGON_TOKEN
n = int(buffer.pop(0))
for i in range(n):
vertices.extend(buffer[:4])
colors.extend(buffer[4:8])
tex_coords.extend(buffer[8:12])
del buffer[:12]
return vertices, colors, tex_coords
import sys
print >> sys.stderr, 'Note: Graphics tests fail with recent nvidia drivers'
print >> sys.stderr, ' due to reordering and optimisation of vertices'
print >> sys.stderr, ' before they are placed in the feedback queue.'
| Python |
#!/usr/bin/python
# $Id:$
import unittest
import pyglet
from graphics_common import *
__noninteractive = True
class TEST_CASE(unittest.TestCase):
def check(self, expected, result, dimensions):
if len(expected) != len(result) * dimensions / 4:
self.fail('Incorrect number of vertices in feedback array')
for d in range(2):
for e, r in zip(expected[d::dimensions], result[d::4]):
if abs(e - r) > 0.01:
self.fail('Feedback array is in error: %r, %r' % \
(e, r))
def generic_test(self, v_fmt, v_data,
c_fmt=None, c_data=None,
t_fmt=None, t_data=None):
data = [(v_fmt, v_data)]
n_v = int(v_fmt[1])
if c_fmt:
data.append((c_fmt, c_data))
n_c = int(c_fmt[1])
if t_fmt:
data.append((t_fmt, t_data))
n_t = int(t_fmt[1])
vertex_list = pyglet.graphics.vertex_list(n_vertices, *data)
vertices, colors, tex_coords = get_feedback(lambda: \
vertex_list.draw(GL_TRIANGLES))
self.check(v_data, vertices, n_v)
if c_fmt:
self.check(c_data, colors, n_c)
if t_fmt:
self.check(t_data, tex_coords, n_t)
def test_v2f(self):
self.generic_test('v2f', v2f_data)
def test_v3f(self):
self.generic_test('v3f', v3f_data)
def test_v2f_c3f(self):
self.generic_test('v2f', v2f_data, 'c3f', c3f_data)
def test_v2f_c4f(self):
self.generic_test('v2f', v2f_data, 'c4f', c4f_data)
def test_v3f_c3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data)
def test_v3f_c4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data)
def test_v2f_t2f(self):
self.generic_test('v2f', v2f_data, None, None, 't2f', t2f_data)
def test_v3f_c3f_t2f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't2f', t2f_data)
def test_v3f_c3f_t3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't3f', t3f_data)
def test_v3f_c4f_t4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data, 't4f', t4f_data)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Draws a full-window quad with two texture units enabled and multi
texcoords. Texture unit 0 is a checker pattern of yellow and cyan with
env mode replace. Texture unit 1 is a checker pattern of cyan and yellow,
with env mode modulate. The result should be flat green (with some variation
in the center cross).
The test will correctly detect the asbence of multitexturing, or if texture
coords are not supplied for a unit, but will still pass if the texture
coordinates for each unit are swapped (the tex coords are identical).
'''
__noninteractive = True
import unittest
import pyglet
from pyglet.gl import *
class TEST_CASE(unittest.TestCase):
def test_multitexture(self):
window = pyglet.window.Window(width=64, height=64)
window.dispatch_events()
w = window.width
h = window.height
pattern0 = pyglet.image.CheckerImagePattern(
(255, 255, 0, 255), (0, 255, 255, 255))
texture0 = pattern0.create_image(64, 64).get_texture()
pattern1 = pyglet.image.CheckerImagePattern(
(0, 255, 255, 255), (255, 255, 0, 255))
texture1 = pattern1.create_image(64, 64).get_texture()
batch = pyglet.graphics.Batch()
batch.add(4, GL_QUADS, None,
('v2i', [0, 0, w, 0, w, h, 0, h]),
('0t3f', texture1.tex_coords),
('1t3f', texture0.tex_coords)
)
glActiveTexture(GL_TEXTURE0)
glEnable(texture0.target)
glBindTexture(texture0.target, texture0.id)
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glActiveTexture(GL_TEXTURE1)
glEnable(texture1.target)
glBindTexture(texture1.target, texture1.id)
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
batch.draw()
self.assertEqual(self.sample(2, 2), (0, 255, 0))
self.assertEqual(self.sample(62, 2), (0, 255, 0))
self.assertEqual(self.sample(62, 62), (0, 255, 0))
self.assertEqual(self.sample(2, 62), (0, 255, 0))
window.close()
def sample(self, x, y):
color_buffer = pyglet.image.get_buffer_manager().get_color_buffer()
buffer = color_buffer.get_image_data()
data = buffer.get_data('RGB', buffer.pitch)
i = y * buffer.pitch + x * 3
r, g, b = data[i:i+3]
if type(r) is str:
r, g, b = map(ord, (r, g, b))
return r, g, b
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# $Id:$
import random
import unittest
from pyglet.graphics import allocation
__noninteractive = True
class Region(object):
def __init__(self, start, size):
self.start = start
self.size = size
def __repr__(self):
return 'Region(%r, %r)' % (self.start, self.size)
class RegionAllocator(object):
def __init__(self, capacity):
self.allocator = allocation.Allocator(capacity)
self.regions = []
def check_region(self, region):
region_end = region.start + region.size
for other in self.regions:
if region is other:
continue
other_end = other.start + other.size
if (other.start < region.start and other_end > region.start) or \
(other.start < region_end and other_end > region_end):
fixture.fail('%r overlaps with %r' % (
region, other))
def check_coverage(self):
starts, sizes = self.allocator.get_allocated_regions()
if len(starts) != len(sizes):
fixture.fail('Length of starts (%d) does not match sizes (%d)' % \
(len(starts), len(sizes)))
if not starts and not self.regions:
return
self.regions.sort(key=lambda r: r.start)
regions = iter(self.regions)
blocks = iter(zip(starts, sizes))
block_start, block_size = blocks.next()
block_used = False
try:
while True:
region = regions.next()
block_used = True
if region.start < block_start:
fixture.fail('Start of %r was not covered at %d' % (
region, block_start))
elif region.start > block_start:
fixture.fail('Uncovered block from %d to %r' % (
block_start, region))
block_start += region.size
block_size -= region.size
if block_size < 0:
fixture.fail('%r extended past end of block by %d' % \
(region, -block_size))
elif block_size == 0:
block_start, block_size = blocks.next()
block_used = False
except StopIteration:
pass
if not block_used:
fixture.fail('Uncovered block(s) from %d' % block_start)
try:
block_start, block_size = blocks.next()
fixture.fail('Uncovered block(s) from %d' % block_start)
except StopIteration:
pass
try:
region = regions.next()
fixture.fail('%r was not covered')
except StopIteration:
pass
def check_redundancy(self):
# Ensure there are no adjacent blocks (they should have been merged)
starts, sizes = self.allocator.get_allocated_regions()
last = -1
for start, size in zip(starts, sizes):
if start < last:
fixture.fail('Block at %d is out of order' % start)
if start == last:
fixture.fail('Block at %d is redundant' % start)
last = start + size
def alloc(self, size):
start = self.allocator.alloc(size)
region = Region(start, size)
self.check_region(region)
self.regions.append(region)
self.check_coverage()
self.check_redundancy()
return region
def dealloc(self, region):
assert region in self.regions
self.allocator.dealloc(region.start, region.size)
self.regions.remove(region)
self.check_coverage()
self.check_redundancy()
def realloc(self, region, size):
assert region in self.regions
region.start = self.allocator.realloc(region.start, region.size, size)
region.size = size
self.check_region(region)
self.check_coverage()
self.check_redundancy()
def force_alloc(self, size):
try:
return self.alloc(size)
except allocation.AllocatorMemoryException, e:
self.allocator.set_capacity(e.requested_capacity)
return self.alloc(size)
def force_realloc(self, region, size):
try:
self.realloc(region, size)
except allocation.AllocatorMemoryException, e:
self.allocator.set_capacity(e.requested_capacity)
self.realloc(region, size)
def get_free_size(self):
return self.allocator.get_free_size()
capacity = property(lambda self: self.allocator.capacity)
class TestAllocation(unittest.TestCase):
def setUp(self):
global fixture
fixture = self
def test_alloc1(self):
capacity = 10
allocator = RegionAllocator(capacity)
for i in range(capacity):
allocator.alloc(1)
def test_alloc2(self):
capacity = 10
allocator = RegionAllocator(capacity)
for i in range(capacity//2):
allocator.alloc(2)
def test_alloc3(self):
capacity = 10
allocator = RegionAllocator(capacity)
for i in range(capacity//3):
allocator.alloc(3)
def test_alloc_mix1_2(self):
allocs = [1, 2] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
for alloc in allocs:
allocator.alloc(alloc)
def test_alloc_mix5_3_7(self):
allocs = [5, 3, 7] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
for alloc in allocs:
allocator.alloc(alloc)
def test_dealloc_1_order_all(self):
capacity = 10
allocator = RegionAllocator(capacity)
regions = []
for i in range(capacity):
regions.append(allocator.alloc(1))
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_1_order(self):
capacity = 15
allocator = RegionAllocator(capacity)
regions = []
for i in range(10):
regions.append(allocator.alloc(1))
for region in regions:
allocator.dealloc(region)
def test_dealloc_1_reverse_all(self):
capacity = 10
allocator = RegionAllocator(capacity)
regions = []
for i in range(capacity):
regions.append(allocator.alloc(1))
for region in regions[::-1]:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_1_reverse(self):
capacity = 15
allocator = RegionAllocator(capacity)
regions = []
for i in range(10):
regions.append(allocator.alloc(1))
for region in regions[::-1]:
allocator.dealloc(region)
def test_dealloc_mix1_2_order(self):
allocs = [1, 2] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
regions = []
for alloc in allocs:
regions.append(allocator.alloc(alloc))
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_mix5_3_7_order(self):
allocs = [5, 3, 7] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
regions = []
for alloc in allocs:
regions.append(allocator.alloc(alloc))
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_1_outoforder(self):
random.seed(1)
capacity = 15
allocator = RegionAllocator(capacity)
regions = []
for i in range(capacity):
regions.append(allocator.alloc(1))
random.shuffle(regions)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_mix1_2_outoforder(self):
random.seed(1)
allocs = [1, 2] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
regions = []
for alloc in allocs:
regions.append(allocator.alloc(alloc))
random.shuffle(regions)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_dealloc_mix5_3_7_outoforder(self):
random.seed(1)
allocs = [5, 3, 7] * 5
capacity = sum(allocs)
allocator = RegionAllocator(capacity)
regions = []
for alloc in allocs:
regions.append(allocator.alloc(alloc))
random.shuffle(regions)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def mixed_alloc_dealloc_list(self, choices, count=10, seed=1):
random.seed(seed)
allocs = []
live = []
j = 0
for i in range(count):
if live:
if random.random() < .5:
allocs.append(random.choice(choices))
live.append(j)
j += 1
else:
k = random.choice(live)
live.remove(k)
allocs.append(-k)
else:
allocs.append(random.choice(choices))
live.append(j)
j += 1
for j in live:
allocs.append(-j)
return allocs
def test_mix_alloc_dealloc1(self):
allocs = self.mixed_alloc_dealloc_list([1])
capacity = sum([a for a in allocs if a > 0])
allocator= RegionAllocator(capacity)
regions = []
for alloc in allocs:
if alloc > 0:
regions.append(allocator.alloc(alloc))
else:
region = regions[abs(alloc)]
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_mix_alloc_dealloc5_3_7(self):
allocs = self.mixed_alloc_dealloc_list([5, 3, 7], count=50)
capacity = sum([a for a in allocs if a > 0])
allocator= RegionAllocator(capacity)
regions = []
for alloc in allocs:
if alloc > 0:
regions.append(allocator.alloc(alloc))
else:
region = regions[abs(alloc)]
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_realloc1_2(self):
allocator = RegionAllocator(30)
regions = []
for i in range(10):
regions.append(allocator.alloc(1))
for region in regions:
allocator.realloc(region, 2)
for region in regions:
allocator.dealloc(region)
def test_realloc2_1(self):
allocator = RegionAllocator(20)
regions = []
for i in range(10):
regions.append(allocator.alloc(2))
for region in regions:
allocator.realloc(region, 1)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_realloc_2_1_2(self):
allocator = RegionAllocator(30)
regions = []
for i in range(10):
regions.append(allocator.alloc(2))
for region in regions:
allocator.realloc(region, 1)
for region in regions:
allocator.realloc(region, 2)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_realloc_3_1_5_4_6(self):
allocator = RegionAllocator(1000)
regions = []
for i in range(10):
regions.append(allocator.alloc(3))
for region in regions:
allocator.realloc(region, 1)
for region in regions:
allocator.realloc(region, 5)
for region in regions:
allocator.realloc(region, 4)
for region in regions:
allocator.realloc(region, 6)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_realloc_3_1_5_4_6_sequential(self):
allocator = RegionAllocator(1000)
regions = []
for i in range(10):
regions.append(allocator.alloc(3))
for region in regions:
allocator.realloc(region, 1)
allocator.realloc(region, 5)
allocator.realloc(region, 4)
allocator.realloc(region, 6)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_resize1(self):
allocator = RegionAllocator(1)
regions = []
for i in range(10):
regions.append(allocator.force_alloc(3))
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
def test_mix_resize(self):
# Try a bunch of stuff. There is not much method to this madness.
allocator = RegionAllocator(1)
regions = []
for i in range(10):
regions.append(allocator.force_alloc(3))
for region in regions[:5]:
#import pdb; pdb.set_trace()
allocator.force_realloc(region, 8)
for i in range(10):
regions.append(allocator.force_alloc(i + 1))
for region in regions[5:15]:
allocator.force_realloc(region, 5)
for region in regions[3:18:2]:
allocator.dealloc(region)
regions.remove(region)
for i in range(5):
regions.append(allocator.force_alloc(3))
for region in regions[-10:]:
allocator.force_realloc(region, 6)
for region in regions:
allocator.dealloc(region)
self.assertTrue(allocator.get_free_size() == allocator.capacity)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# $Id:$
import unittest
import pyglet
from graphics_common import *
__noninteractive = True
class TEST_CASE(unittest.TestCase):
def check(self, expected, result, dimensions):
if len(expected) != len(result) * dimensions / 4:
self.fail('Incorrect number of vertices in feedback array')
for d in range(2): # Don't check Z or W
for e, r in zip(expected[d::dimensions], result[d::4]):
if abs(e - r) > 0.01:
self.fail('Feedback array is in error: %r, %r' % \
(e, r))
def generic_test(self, v_fmt, v_data,
c_fmt=None, c_data=None,
t_fmt=None, t_data=None):
data = [(v_fmt, v_data)]
n_v = int(v_fmt[1])
if c_fmt:
data.append((c_fmt, c_data))
n_c = int(c_fmt[1])
if t_fmt:
data.append((t_fmt, t_data))
n_t = int(t_fmt[1])
vertices, colors, tex_coords = get_feedback(lambda: \
pyglet.graphics.draw(n_vertices, GL_TRIANGLES, *data))
self.check(v_data, vertices, n_v)
if c_fmt:
self.check(c_data, colors, n_c)
if t_fmt:
self.check(t_data, tex_coords, n_t)
def test_v2f(self):
self.generic_test('v2f', v2f_data)
def test_v3f(self):
self.generic_test('v3f', v3f_data)
def test_v2f_c3f(self):
self.generic_test('v2f', v2f_data, 'c3f', c3f_data)
def test_v2f_c4f(self):
self.generic_test('v2f', v2f_data, 'c4f', c4f_data)
def test_v3f_c3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data)
def test_v3f_c4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data)
def test_v2f_t2f(self):
self.generic_test('v2f', v2f_data, None, None, 't2f', t2f_data)
def test_v3f_c3f_t2f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't2f', t2f_data)
def test_v3f_c3f_t3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't3f', t3f_data)
def test_v3f_c4f_t4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data, 't4f', t4f_data)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import pyglet
from graphics_common import *
__noninteractive = True
class TEST_CASE(unittest.TestCase):
def check(self, expected, result, dimensions):
if len(expected) != len(result) * dimensions / 4:
self.fail('Incorrect number of vertices in feedback array')
for d in range(2):
for e, r in zip(expected[d::dimensions], result[d::4]):
if abs(e - r) > 0.01:
self.fail('Feedback array is in error: %r, %r' % \
(e, r))
def generic_test(self, v_fmt, v_data,
c_fmt=None, c_data=None,
t_fmt=None, t_data=None):
data = [(v_fmt, v_data)]
n_v = int(v_fmt[1])
if c_fmt:
data.append((c_fmt, c_data))
n_c = int(c_fmt[1])
if t_fmt:
data.append((t_fmt, t_data))
n_t = int(t_fmt[1])
vertex_list = pyglet.graphics.vertex_list_indexed(
n_vertices, index_data, *data)
vertices, colors, tex_coords = get_feedback(lambda: \
vertex_list.draw(GL_TRIANGLES))
self.check(get_ordered_data(v_data, n_v), vertices, n_v)
if c_fmt:
self.check(get_ordered_data(c_data, n_c), colors, n_c)
if t_fmt:
self.check(get_ordered_data(t_data, n_t), tex_coords, n_t)
def test_v2f(self):
self.generic_test('v2f', v2f_data)
def test_v3f(self):
self.generic_test('v3f', v3f_data)
def test_v2f_c3f(self):
self.generic_test('v2f', v2f_data, 'c3f', c3f_data)
def test_v2f_c4f(self):
self.generic_test('v2f', v2f_data, 'c4f', c4f_data)
def test_v3f_c3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data)
def test_v3f_c4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data)
def test_v2f_t2f(self):
self.generic_test('v2f', v2f_data, None, None, 't2f', t2f_data)
def test_v3f_c3f_t2f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't2f', t2f_data)
def test_v3f_c3f_t3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't3f', t3f_data)
def test_v3f_c4f_t4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data, 't4f', t4f_data)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import pyglet
from graphics_common import *
__noninteractive = True
class TEST_CASE(unittest.TestCase):
def check(self, expected, result, dimensions):
if len(expected) != len(result) * dimensions / 4:
self.fail('Incorrect number of vertices in feedback array')
for d in range(2):
for e, r in zip(expected[d::dimensions], result[d::4]):
if abs(e - r) > 0.01:
self.fail('Feedback array is in error: %r, %r' % \
(e, r))
def generic_test(self, v_fmt, v_data,
c_fmt=None, c_data=None,
t_fmt=None, t_data=None):
data = [(v_fmt, v_data)]
n_v = int(v_fmt[1])
if c_fmt:
data.append((c_fmt, c_data))
n_c = int(c_fmt[1])
if t_fmt:
data.append((t_fmt, t_data))
n_t = int(t_fmt[1])
vertices, colors, tex_coords = get_feedback(lambda: \
pyglet.graphics.draw_indexed(n_vertices, GL_TRIANGLES, index_data,
*data))
self.check(get_ordered_data(v_data, n_v), vertices, n_v)
if c_fmt:
self.check(get_ordered_data(c_data, n_c), colors, n_c)
if t_fmt:
self.check(get_ordered_data(t_data, n_t), tex_coords, n_t)
def test_v2f(self):
self.generic_test('v2f', v2f_data)
def test_v3f(self):
self.generic_test('v3f', v3f_data)
def test_v2f_c3f(self):
self.generic_test('v2f', v2f_data, 'c3f', c3f_data)
def test_v2f_c4f(self):
self.generic_test('v2f', v2f_data, 'c4f', c4f_data)
def test_v3f_c3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data)
def test_v3f_c4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data)
def test_v2f_t2f(self):
self.generic_test('v2f', v2f_data, None, None, 't2f', t2f_data)
def test_v3f_c3f_t2f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't2f', t2f_data)
def test_v3f_c3f_t3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't3f', t3f_data)
def test_v3f_c4f_t4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data, 't4f', t4f_data)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from operator import add
import random
from pyglet.gl import *
n_vertices = 42
v3f_data = [v/float(n_vertices*3 + 10) for v in range(n_vertices * 3)]
v2f_data = reduce(add, zip(v3f_data[::3], v3f_data[1::3]))
c4f_data = [v/float(n_vertices*4) for v in range(n_vertices * 4)]
c3f_data = reduce(add, zip(c4f_data[::4], c4f_data[1::4], c4f_data[2::4]))
t4f_data = [v/float(n_vertices*4 + 5) for v in range(n_vertices * 4)]
t3f_data = reduce(add, zip(t4f_data[::4], t4f_data[1::4], t4f_data[2::4]))
t2f_data = reduce(add, zip(t3f_data[::3], t3f_data[1::3]))
index_data = range(n_vertices)
random.seed(1)
random.shuffle(index_data)
def get_ordered_data(data, dimensions):
ordered = []
for i in index_data:
ordered.extend(data[i * dimensions:(i+1)*dimensions])
return ordered
feedback_buffer = (GLfloat * 8096)()
def get_feedback(func):
# Project in clip coords
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, 1, 0, 1, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glFeedbackBuffer(len(feedback_buffer), GL_4D_COLOR_TEXTURE, feedback_buffer)
glRenderMode(GL_FEEDBACK)
func()
size = glRenderMode(GL_RENDER)
buffer = feedback_buffer[:size]
vertices = []
colors = []
tex_coords = []
while buffer:
token = int(buffer.pop(0))
assert token == GL_POLYGON_TOKEN
n = int(buffer.pop(0))
for i in range(n):
vertices.extend(buffer[:4])
colors.extend(buffer[4:8])
tex_coords.extend(buffer[8:12])
del buffer[:12]
return vertices, colors, tex_coords
import sys
print >> sys.stderr, 'Note: Graphics tests fail with recent nvidia drivers'
print >> sys.stderr, ' due to reordering and optimisation of vertices'
print >> sys.stderr, ' before they are placed in the feedback queue.'
| Python |
#!/usr/bin/python
# $Id:$
import unittest
import pyglet
from graphics_common import *
__noninteractive = True
class TEST_CASE(unittest.TestCase):
def check(self, expected, result, dimensions):
if len(expected) != len(result) * dimensions / 4:
self.fail('Incorrect number of vertices in feedback array')
for d in range(2): # Don't check Z or W
for e, r in zip(expected[d::dimensions], result[d::4]):
if abs(e - r) > 0.01:
self.fail('Feedback array is in error: %r, %r' % \
(e, r))
def generic_test(self, v_fmt, v_data,
c_fmt=None, c_data=None,
t_fmt=None, t_data=None):
data = [(v_fmt, v_data)]
n_v = int(v_fmt[1])
if c_fmt:
data.append((c_fmt, c_data))
n_c = int(c_fmt[1])
if t_fmt:
data.append((t_fmt, t_data))
n_t = int(t_fmt[1])
vertices, colors, tex_coords = get_feedback(lambda: \
pyglet.graphics.draw(n_vertices, GL_TRIANGLES, *data))
self.check(v_data, vertices, n_v)
if c_fmt:
self.check(c_data, colors, n_c)
if t_fmt:
self.check(t_data, tex_coords, n_t)
def test_v2f(self):
self.generic_test('v2f', v2f_data)
def test_v3f(self):
self.generic_test('v3f', v3f_data)
def test_v2f_c3f(self):
self.generic_test('v2f', v2f_data, 'c3f', c3f_data)
def test_v2f_c4f(self):
self.generic_test('v2f', v2f_data, 'c4f', c4f_data)
def test_v3f_c3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data)
def test_v3f_c4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data)
def test_v2f_t2f(self):
self.generic_test('v2f', v2f_data, None, None, 't2f', t2f_data)
def test_v3f_c3f_t2f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't2f', t2f_data)
def test_v3f_c3f_t3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't3f', t3f_data)
def test_v3f_c4f_t4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data, 't4f', t4f_data)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# $Id:$
import unittest
import pyglet
from graphics_common import *
__noninteractive = True
class TEST_CASE(unittest.TestCase):
def check(self, expected, result, dimensions):
if len(expected) != len(result) * dimensions / 4:
self.fail('Incorrect number of vertices in feedback array')
for d in range(2):
for e, r in zip(expected[d::dimensions], result[d::4]):
if abs(e - r) > 0.01:
self.fail('Feedback array is in error: %r, %r' % \
(e, r))
def generic_test(self, v_fmt, v_data,
c_fmt=None, c_data=None,
t_fmt=None, t_data=None):
data = [(v_fmt, v_data)]
n_v = int(v_fmt[1])
if c_fmt:
data.append((c_fmt, c_data))
n_c = int(c_fmt[1])
if t_fmt:
data.append((t_fmt, t_data))
n_t = int(t_fmt[1])
vertex_list = pyglet.graphics.vertex_list(n_vertices, *data)
vertices, colors, tex_coords = get_feedback(lambda: \
vertex_list.draw(GL_TRIANGLES))
self.check(v_data, vertices, n_v)
if c_fmt:
self.check(c_data, colors, n_c)
if t_fmt:
self.check(t_data, tex_coords, n_t)
def test_v2f(self):
self.generic_test('v2f', v2f_data)
def test_v3f(self):
self.generic_test('v3f', v3f_data)
def test_v2f_c3f(self):
self.generic_test('v2f', v2f_data, 'c3f', c3f_data)
def test_v2f_c4f(self):
self.generic_test('v2f', v2f_data, 'c4f', c4f_data)
def test_v3f_c3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data)
def test_v3f_c4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data)
def test_v2f_t2f(self):
self.generic_test('v2f', v2f_data, None, None, 't2f', t2f_data)
def test_v3f_c3f_t2f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't2f', t2f_data)
def test_v3f_c3f_t3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't3f', t3f_data)
def test_v3f_c4f_t4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data, 't4f', t4f_data)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# $Id:$
import unittest
import pyglet
from graphics_common import *
__noninteractive = True
class TEST_CASE(unittest.TestCase):
def check(self, expected, result, dimensions):
if len(expected) != len(result) * dimensions / 4:
self.fail('Incorrect number of vertices in feedback array')
for d in range(2): # Don't check Z or W
for e, r in zip(expected[d::dimensions], result[d::4]):
if abs(e - r) > 0.01:
self.fail('Feedback array is in error: %r, %r' % \
(e, r))
def generic_test(self, v_fmt, v_data,
c_fmt=None, c_data=None,
t_fmt=None, t_data=None):
data = [(v_fmt, v_data)]
n_v = int(v_fmt[1])
if c_fmt:
data.append((c_fmt, c_data))
n_c = int(c_fmt[1])
if t_fmt:
data.append((t_fmt, t_data))
n_t = int(t_fmt[1])
vertices, colors, tex_coords = get_feedback(lambda: \
pyglet.graphics.draw(n_vertices, GL_TRIANGLES, *data))
self.check(v_data, vertices, n_v)
if c_fmt:
self.check(c_data, colors, n_c)
if t_fmt:
self.check(t_data, tex_coords, n_t)
def test_v2f(self):
self.generic_test('v2f', v2f_data)
def test_v3f(self):
self.generic_test('v3f', v3f_data)
def test_v2f_c3f(self):
self.generic_test('v2f', v2f_data, 'c3f', c3f_data)
def test_v2f_c4f(self):
self.generic_test('v2f', v2f_data, 'c4f', c4f_data)
def test_v3f_c3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data)
def test_v3f_c4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data)
def test_v2f_t2f(self):
self.generic_test('v2f', v2f_data, None, None, 't2f', t2f_data)
def test_v3f_c3f_t2f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't2f', t2f_data)
def test_v3f_c3f_t3f(self):
self.generic_test('v3f', v3f_data, 'c3f', c3f_data, 't3f', t3f_data)
def test_v3f_c4f_t4f(self):
self.generic_test('v3f', v3f_data, 'c4f', c4f_data, 't4f', t4f_data)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Draws a full-window quad with two texture units enabled and multi
texcoords. Texture unit 0 is a checker pattern of yellow and cyan with
env mode replace. Texture unit 1 is a checker pattern of cyan and yellow,
with env mode modulate. The result should be flat green (with some variation
in the center cross).
The test will correctly detect the asbence of multitexturing, or if texture
coords are not supplied for a unit, but will still pass if the texture
coordinates for each unit are swapped (the tex coords are identical).
'''
__noninteractive = True
import unittest
import pyglet
from pyglet.gl import *
class TEST_CASE(unittest.TestCase):
def test_multitexture(self):
window = pyglet.window.Window(width=64, height=64)
window.dispatch_events()
w = window.width
h = window.height
pattern0 = pyglet.image.CheckerImagePattern(
(255, 255, 0, 255), (0, 255, 255, 255))
texture0 = pattern0.create_image(64, 64).get_texture()
pattern1 = pyglet.image.CheckerImagePattern(
(0, 255, 255, 255), (255, 255, 0, 255))
texture1 = pattern1.create_image(64, 64).get_texture()
batch = pyglet.graphics.Batch()
batch.add(4, GL_QUADS, None,
('v2i', [0, 0, w, 0, w, h, 0, h]),
('0t3f', texture1.tex_coords),
('1t3f', texture0.tex_coords)
)
glActiveTexture(GL_TEXTURE0)
glEnable(texture0.target)
glBindTexture(texture0.target, texture0.id)
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glActiveTexture(GL_TEXTURE1)
glEnable(texture1.target)
glBindTexture(texture1.target, texture1.id)
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
batch.draw()
self.assertEqual(self.sample(2, 2), (0, 255, 0))
self.assertEqual(self.sample(62, 2), (0, 255, 0))
self.assertEqual(self.sample(62, 62), (0, 255, 0))
self.assertEqual(self.sample(2, 62), (0, 255, 0))
window.close()
def sample(self, x, y):
color_buffer = pyglet.image.get_buffer_manager().get_color_buffer()
buffer = color_buffer.get_image_data()
data = buffer.get_data('RGB', buffer.pitch)
i = y * buffer.pitch + x * 3
r, g, b = data[i:i+3]
if type(r) is str:
r, g, b = map(ord, (r, g, b))
return r, g, b
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import shutil
import sys
# Bump pyglet/__init__.py version as well.
VERSION = '1.2alpha1'
long_description = '''pyglet provides an object-oriented programming
interface for developing games and other visually-rich applications
for Windows, Mac OS X and Linux.'''
setup_info = dict(
# Metadata
name='pyglet',
version=VERSION,
author='Alex Holkner',
author_email='Alex.Holkner@gmail.com',
url='http://www.pyglet.org/',
download_url='http://pypi.python.org/pypi/pyglet',
description='Cross-platform windowing and multimedia library',
long_description=long_description,
license='BSD',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: MacOS X',
'Environment :: Win32 (MS Windows)',
'Environment :: X11 Applications',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows', # XP
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Topic :: Games/Entertainment',
'Topic :: Software Development :: Libraries :: Python Modules',
],
# Package info
packages=[
'pyglet',
'pyglet.app',
'pyglet.canvas',
'pyglet.font',
'pyglet.gl',
'pyglet.graphics',
'pyglet.image',
'pyglet.image.codecs',
'pyglet.input',
'pyglet.libs',
'pyglet.libs.darwin',
'pyglet.libs.darwin.cocoapy',
'pyglet.libs.win32',
'pyglet.libs.x11',
'pyglet.media',
'pyglet.media.drivers',
'pyglet.media.drivers.directsound',
'pyglet.media.drivers.openal',
'pyglet.media.drivers.pulse',
'pyglet.text',
'pyglet.text.formats',
'pyglet.window',
'pyglet.window.carbon',
'pyglet.window.cocoa',
'pyglet.window.win32',
'pyglet.window.xlib',
],
)
setuptools_info = dict(
zip_safe=True,
)
if 'bdist_egg' in sys.argv or 'develop' in sys.argv:
from setuptools import setup
_have_setuptools = True
# Don't walk SVN tree for default manifest
from setuptools.command import egg_info
from setuptools.command import sdist
egg_info.walk_revctrl = lambda: []
sdist.walk_revctrl = lambda: []
# Insert additional command-line arguments into install_lib when
# bdist_egg calls it, to compile byte-code with optimizations.
# This is a dirty hack.
from setuptools.command import bdist_egg
old_call_command = bdist_egg.bdist_egg.call_command
def call_command(self, *args, **kwargs):
if args[0] == 'install_lib':
kwargs['optimize'] = 2
kwargs['compile'] = False
cmd = old_call_command(self, *args, **kwargs)
return cmd
bdist_egg.bdist_egg.call_command = call_command
elif 'bdist_mpkg' in sys.argv:
from setuptools import setup
_have_setuptools = True
from bdist_mpkg_pyglet import plists, pkg, cmd_bdist_mpkg, tools
# Check for ctypes if installing into Python 2.4
def ctypes_requirement(pkgname, prefix):
prefix = os.path.join(prefix, 'ctypes')
title = '%s requires ctypes 1.0 or later to install with Python 2.4' \
% pkgname
kw = dict(
LabelKey='ctypes',
TitleKey=title,
MessageKey=title,
)
return plists.path_requirement(prefix, **kw)
# Subclass bdist_mpkg
class pyglet_bdist_mpkg(cmd_bdist_mpkg.bdist_mpkg):
# Don't include platform or python version in mpkg name (aesthetics)
def finalize_package_data(self):
cmd_bdist_mpkg.bdist_mpkg.finalize_package_data(self)
self.metapackagename = '-'.join([self.get_name(),
self.get_version()]) + '.mpkg'
self.pseudoinstall_root = self.get_pseudoinstall_root()
self.packagesdir = os.path.join(
self.get_metapackage(),
self.component_directory
)
def get_metapackage_info(self):
info = dict(cmd_bdist_mpkg.bdist_mpkg.get_metapackage_info(self))
info.update(dict(
# Set background image alignment
IFPkgFlagBackgroundScaling='none',
IFPkgFlagBackgroundAlignment='topleft',
# Remove specific Python version requirement from metapackage,
# is per-package now.
IFRequirementDicts=[],
))
return info
# Override how packages are made. purelib forces creation of a
# separate package for each required python version, all symlinked to
# the same Archive.bom.
def make_scheme_package(self, scheme):
assert scheme == 'purelib'
# Make AVbin package
pkgname = 'AVbin'
pkgfile = pkgname + '.pkg'
self.packages.append((pkgfile, self.get_scheme_status(scheme)))
pkgdir = os.path.join(self.packagesdir, pkgfile)
self.mkpath(pkgdir)
version = self.get_scheme_version(scheme)
info = dict(self.get_scheme_info(scheme))
description = 'AVbin audio and video support (recommended)'
files = list(tools.walk_files('build/avbin'))
common = 'build/avbin'
prefix = '/usr/local/lib'
pkg.make_package(self,
pkgname, version,
files, common, prefix,
pkgdir,
info, description)
# pyglet packages
files, common, prefix = self.get_scheme_root(scheme)
def add_package(python_dir, package_dir,
pyver, pkgname, description):
scheme_prefix = package_dir
pkgfile = pkgname + '.pkg'
self.packages.append((pkgfile, self.get_scheme_status(scheme)))
pkgdir = os.path.join(self.packagesdir, pkgfile)
self.mkpath(pkgdir)
version = self.get_scheme_version(scheme)
requirements = [
plists.python_requirement(self.get_name(),
prefix=python_dir,
version=pyver)]
if pyver == '2.4':
requirements.append(ctypes_requirement(self.get_name(),
prefix=scheme_prefix))
info = dict(self.get_scheme_info(scheme))
info.update(dict(
IFRequirementDicts=requirements,
))
pkg.make_package(self,
pkgname, version,
files, common, scheme_prefix,
pkgdir,
info,
description,
)
# Move the archive up to the metapackage and symlink to it
pkgfile = os.path.join(pkgdir, 'Contents/Archive.pax.gz')
shutil.move(pkgfile,
os.path.join(pkgdir, '../../Archive.pax.gz'))
os.symlink('../../../Archive.pax.gz', pkgfile)
pkgfile = os.path.join(pkgdir, 'Contents/Archive.bom')
shutil.move(pkgfile,
os.path.join(pkgdir, '../../Archive.bom'))
os.symlink('../../../Archive.bom', pkgfile)
self.scheme_hook(scheme, pkgname, version, files, common,
prefix, pkgdir)
add_package(
'/System/Library/Frameworks/Python.framework/Versions/2.5',
'/Library/Python/2.5/site-packages',
'2.5', 'pyglet-syspy2.5',
'pyglet for Python 2.5 in /System/Library')
add_package(
'/System/Library/Frameworks/Python.framework/Versions/2.6',
'/Library/Python/2.6/site-packages',
'2.6', 'pyglet-syspy2.6',
'pyglet for Python 2.6 in /System/Library')
add_package(
'/Library/Frameworks/Python.framework/Versions/2.4',
'/Library/Frameworks/Python.framework/Versions/2.4' \
'/lib/python2.4/site-packages',
'2.4', 'pyglet-py2.4',
'pyglet for Python 2.4 in /Library')
add_package(
'/Library/Frameworks/Python.framework/Versions/2.5',
'/Library/Frameworks/Python.framework/Versions/2.5' \
'/lib/python2.5/site-packages',
'2.5', 'pyglet-py2.5',
'pyglet for Python 2.5 in /Library')
add_package(
'/Library/Frameworks/Python.framework/Versions/2.6',
'/Library/Frameworks/Python.framework/Versions/2.6' \
'/lib/python2.6/site-packages',
'2.6', 'pyglet-py2.6',
'pyglet for Python 2.6 in /Library')
add_package(
'/opt/local/',
'/opt/local/lib/python2.4/site-packages',
'2.4', 'pyglet-macports-py2.4',
'pyglet for MacPorts Python 2.4 in /opt/local')
add_package(
'/opt/local/',
'/opt/local/lib/python2.5/site-packages',
'2.5', 'pyglet-macports-py2.5',
'pyglet for MacPorts Python 2.5 in /opt/local')
add_package(
'/opt/local/',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.6' \
'/lib/python2.6/site-packages',
'2.6', 'pyglet-macports-py2.6',
'pyglet for MacPorts Python 2.6 in /opt/local')
# Don't build to an absolute path, assume within site-packages (makes
# it easier to symlink the same archive for all packages)
def get_scheme_install_prefix(self, scheme):
return scheme
# Don't byte compile (waste of space, try to do it in postflight TODO).
def byte_compile(self):
pass
setuptools_info.update(dict(
cmdclass={'bdist_mpkg': pyglet_bdist_mpkg,}
))
else:
from distutils.core import setup
_have_setuptools = False
if _have_setuptools:
# Additional dict values for setuptools
setup_info.update(setuptools_info)
install_requires = []
if sys.version_info < (2, 5, 0):
install_requires.append('ctypes')
setup_info.update(dict(
install_requires=install_requires,
))
if sys.version_info >= (3,):
# Automatically run 2to3 when using Python 3
if _have_setuptools:
setup_info["use_2to3"] = True
else:
from distutils.command.build_py import build_py_2to3
setup_info["cmdclass"] = {"build_py" : build_py_2to3}
setup(**setup_info)
| Python |
#!/usr/bin/python
# $Id:$
'''Display font information.
Usage::
inspect_font.py <filename> [<filename> ...]
'''
import sys
from pyglet.font import ttf
def inspect_font(filename):
try:
info = ttf.TruetypeInfo(filename)
print '%s:' % filename,
print info.get_name('family'),
print 'bold=%r' % info.is_bold(),
print 'italic=%r' % info.is_italic(),
except:
print '''%s could not be identified. It is probably not a TrueType or
OpenType font. However, pyglet may still be able to load it
on some platforms.''' % filename
if __name__ == '__main__':
if len(sys.argv) < 2:
print __doc__
for filename in sys.argv[1:]:
inspect_font(filename)
| Python |
#!/usr/bin/python
# $Id:$
'''Display font information.
Usage::
inspect_font.py <filename> [<filename> ...]
'''
import sys
from pyglet.font import ttf
def inspect_font(filename):
try:
info = ttf.TruetypeInfo(filename)
print '%s:' % filename,
print info.get_name('family'),
print 'bold=%r' % info.is_bold(),
print 'italic=%r' % info.is_italic(),
except:
print '''%s could not be identified. It is probably not a TrueType or
OpenType font. However, pyglet may still be able to load it
on some platforms.''' % filename
if __name__ == '__main__':
if len(sys.argv) < 2:
print __doc__
for filename in sys.argv[1:]:
inspect_font(filename)
| 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.
# ----------------------------------------------------------------------------
'''Display positioned, scaled and rotated images.
A sprite is an instance of an image displayed on-screen. Multiple sprites can
display the same image at different positions on the screen. Sprites can also
be scaled larger or smaller, rotated at any angle and drawn at a fractional
opacity.
The following complete example loads a ``"ball.png"`` image and creates a
sprite for that image. The sprite is then drawn in the window's
draw event handler::
import pyglet
ball_image = pyglet.image.load('ball.png')
ball = pyglet.sprite.Sprite(ball_image, x=50, y=50)
window = pyglet.window.Window()
@window.event
def on_draw():
ball.draw()
pyglet.app.run()
The sprite can be moved by modifying the ``x`` and ``y`` properties. Other
properties determine the sprite's rotation, scale and opacity.
The sprite's positioning, rotation and scaling all honor the original
image's anchor (anchor_x, anchor_y).
Drawing multiple sprites
========================
Sprites can be "batched" together and drawn at once more quickly than if each
of their ``draw`` methods were called individually. The following example
creates one hundred ball sprites and adds each of them to a `Batch`. The
entire batch of sprites is then drawn in one call::
batch = pyglet.graphics.Batch()
ball_sprites = []
for i in range(100):
x, y = i * 10, 50
ball_sprites.append(pyglet.sprite.Sprite(ball_image, x, y, batch=batch))
@window.event
def on_draw():
batch.draw()
Sprites can be freely modified in any way even after being added to a batch,
however a sprite can belong to at most one batch. See the documentation for
`pyglet.graphics` for more details on batched rendering, and grouping of
sprites within batches.
:since: pyglet 1.1
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import math
import sys
from pyglet.gl import *
from pyglet import clock
from pyglet import event
from pyglet import graphics
from pyglet import image
_is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc
class SpriteGroup(graphics.Group):
'''Shared sprite rendering group.
The group is automatically coalesced with other sprite groups sharing the
same parent group, texture and blend parameters.
'''
def __init__(self, texture, blend_src, blend_dest, parent=None):
'''Create a sprite group.
The group is created internally within `Sprite`; applications usually
do not need to explicitly create it.
:Parameters:
`texture` : `Texture`
The (top-level) texture containing the sprite image.
`blend_src` : int
OpenGL blend source mode; for example,
``GL_SRC_ALPHA``.
`blend_dest` : int
OpenGL blend destination mode; for example,
``GL_ONE_MINUS_SRC_ALPHA``.
`parent` : `Group`
Optional parent group.
'''
super(SpriteGroup, self).__init__(parent)
self.texture = texture
self.blend_src = blend_src
self.blend_dest = blend_dest
def set_state(self):
glEnable(self.texture.target)
glBindTexture(self.texture.target, self.texture.id)
glPushAttrib(GL_COLOR_BUFFER_BIT)
glEnable(GL_BLEND)
glBlendFunc(self.blend_src, self.blend_dest)
def unset_state(self):
glPopAttrib()
glDisable(self.texture.target)
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.texture)
def __eq__(self, other):
return (other.__class__ is self.__class__ and
self.parent is other.parent and
self.texture.target == other.texture.target and
self.texture.id == other.texture.id and
self.blend_src == other.blend_src and
self.blend_dest == other.blend_dest)
def __hash__(self):
return hash((id(self.parent),
self.texture.id, self.texture.target,
self.blend_src, self.blend_dest))
class Sprite(event.EventDispatcher):
'''Instance of an on-screen image.
See the module documentation for usage.
'''
_batch = None
_animation = None
_rotation = 0
_opacity = 255
_rgb = (255, 255, 255)
_scale = 1.0
_visible = True
_vertex_list = None
def __init__(self,
img, x=0, y=0,
blend_src=GL_SRC_ALPHA,
blend_dest=GL_ONE_MINUS_SRC_ALPHA,
batch=None,
group=None,
usage='dynamic'):
'''Create a sprite.
:Parameters:
`img` : `AbstractImage` or `Animation`
Image or animation to display.
`x` : int
X coordinate of the sprite.
`y` : int
Y coordinate of the sprite.
`blend_src` : int
OpenGL blend source mode. The default is suitable for
compositing sprites drawn from back-to-front.
`blend_dest` : int
OpenGL blend destination mode. The default is suitable for
compositing sprites drawn from back-to-front.
`batch` : `Batch`
Optional batch to add the sprite to.
`group` : `Group`
Optional parent group of the sprite.
`usage` : str
Vertex buffer object usage hint, one of ``"none"`` (default),
``"stream"``, ``"dynamic"`` or ``"static"``. Applies
only to vertex data.
'''
if batch is not None:
self._batch = batch
self._x = x
self._y = y
if isinstance(img, image.Animation):
self._animation = img
self._frame_index = 0
self._texture = img.frames[0].image.get_texture()
self._next_dt = img.frames[0].duration
if self._next_dt:
clock.schedule_once(self._animate, self._next_dt)
else:
self._texture = img.get_texture()
self._group = SpriteGroup(self._texture, blend_src, blend_dest, group)
self._usage = usage
self._create_vertex_list()
def __del__(self):
try:
if self._vertex_list is not None:
self._vertex_list.delete()
except:
pass
def delete(self):
'''Force immediate removal of the sprite from video memory.
This is often necessary when using batches, as the Python garbage
collector will not necessarily call the finalizer as soon as the
sprite is garbage.
'''
if self._animation:
clock.unschedule(self._animate)
self._vertex_list.delete()
self._vertex_list = None
self._texture = None
# Easy way to break circular reference, speeds up GC
self._group = None
def _animate(self, dt):
self._frame_index += 1
if self._frame_index >= len(self._animation.frames):
self._frame_index = 0
self.dispatch_event('on_animation_end')
if self._vertex_list is None:
return # Deleted in event handler.
frame = self._animation.frames[self._frame_index]
self._set_texture(frame.image.get_texture())
if frame.duration is not None:
duration = frame.duration - (self._next_dt - dt)
duration = min(max(0, duration), frame.duration)
clock.schedule_once(self._animate, duration)
self._next_dt = duration
else:
self.dispatch_event('on_animation_end')
def _set_batch(self, batch):
if self._batch == batch:
return
if batch is not None and self._batch is not None:
self._batch.migrate(self._vertex_list, GL_QUADS, self._group, batch)
self._batch = batch
else:
self._vertex_list.delete()
self._batch = batch
self._create_vertex_list()
def _get_batch(self):
return self._batch
batch = property(_get_batch, _set_batch,
doc='''Graphics batch.
The sprite can be migrated from one batch to another, or removed from its
batch (for individual drawing). Note that this can be an expensive
operation.
:type: `Batch`
''')
def _set_group(self, group):
if self._group.parent == group:
return
self._group = SpriteGroup(self._texture,
self._group.blend_src,
self._group.blend_dest,
group)
if self._batch is not None:
self._batch.migrate(self._vertex_list, GL_QUADS, self._group,
self._batch)
def _get_group(self):
return self._group.parent
group = property(_get_group, _set_group,
doc='''Parent graphics group.
The sprite can change its rendering group, however this can be an
expensive operation.
:type: `Group`
''')
def _get_image(self):
if self._animation:
return self._animation
return self._texture
def _set_image(self, img):
if self._animation is not None:
clock.unschedule(self._animate)
self._animation = None
if isinstance(img, image.Animation):
self._animation = img
self._frame_index = 0
self._set_texture(img.frames[0].image.get_texture())
self._next_dt = img.frames[0].duration
if self._next_dt:
clock.schedule_once(self._animate, self._next_dt)
else:
self._set_texture(img.get_texture())
self._update_position()
image = property(_get_image, _set_image,
doc='''Image or animation to display.
:type: `AbstractImage` or `Animation`
''')
def _set_texture(self, texture):
if texture.id is not self._texture.id:
self._group = SpriteGroup(texture,
self._group.blend_src,
self._group.blend_dest,
self._group.parent)
if self._batch is None:
self._vertex_list.tex_coords[:] = texture.tex_coords
else:
self._vertex_list.delete()
self._texture = texture
self._create_vertex_list()
else:
self._vertex_list.tex_coords[:] = texture.tex_coords
self._texture = texture
def _create_vertex_list(self):
if self._batch is None:
self._vertex_list = graphics.vertex_list(4,
'v2i/%s' % self._usage,
'c4B', ('t3f', self._texture.tex_coords))
else:
self._vertex_list = self._batch.add(4, GL_QUADS, self._group,
'v2i/%s' % self._usage,
'c4B', ('t3f', self._texture.tex_coords))
self._update_position()
self._update_color()
def _update_position(self):
img = self._texture
if not self._visible:
self._vertex_list.vertices[:] = [0, 0, 0, 0, 0, 0, 0, 0]
elif self._rotation:
x1 = -img.anchor_x * self._scale
y1 = -img.anchor_y * self._scale
x2 = x1 + img.width * self._scale
y2 = y1 + img.height * self._scale
x = self._x
y = self._y
r = -math.radians(self._rotation)
cr = math.cos(r)
sr = math.sin(r)
ax = int(x1 * cr - y1 * sr + x)
ay = int(x1 * sr + y1 * cr + y)
bx = int(x2 * cr - y1 * sr + x)
by = int(x2 * sr + y1 * cr + y)
cx = int(x2 * cr - y2 * sr + x)
cy = int(x2 * sr + y2 * cr + y)
dx = int(x1 * cr - y2 * sr + x)
dy = int(x1 * sr + y2 * cr + y)
self._vertex_list.vertices[:] = [ax, ay, bx, by, cx, cy, dx, dy]
elif self._scale != 1.0:
x1 = int(self._x - img.anchor_x * self._scale)
y1 = int(self._y - img.anchor_y * self._scale)
x2 = int(x1 + img.width * self._scale)
y2 = int(y1 + img.height * self._scale)
self._vertex_list.vertices[:] = [x1, y1, x2, y1, x2, y2, x1, y2]
else:
x1 = int(self._x - img.anchor_x)
y1 = int(self._y - img.anchor_y)
x2 = x1 + img.width
y2 = y1 + img.height
self._vertex_list.vertices[:] = [x1, y1, x2, y1, x2, y2, x1, y2]
def _update_color(self):
r, g, b = self._rgb
self._vertex_list.colors[:] = [r, g, b, int(self._opacity)] * 4
def set_position(self, x, y):
'''Set the X and Y coordinates of the sprite simultaneously.
:Parameters:
`x` : int
X coordinate of the sprite.
`y` : int
Y coordinate of the sprite.
'''
self._x = x
self._y = y
self._update_position()
position = property(lambda self: (self._x, self._y),
lambda self, t: self.set_position(*t),
doc='''The (x, y) coordinates of the sprite.
:type: (int, int)
''')
def _set_x(self, x):
self._x = x
self._update_position()
x = property(lambda self: self._x, _set_x,
doc='''X coordinate of the sprite.
:type: int
''')
def _set_y(self, y):
self._y = y
self._update_position()
y = property(lambda self: self._y, _set_y,
doc='''Y coordinate of the sprite.
:type: int
''')
def _set_rotation(self, rotation):
self._rotation = rotation
self._update_position()
rotation = property(lambda self: self._rotation, _set_rotation,
doc='''Clockwise rotation of the sprite, in degrees.
The sprite image will be rotated about its image's (anchor_x, anchor_y)
position.
:type: float
''')
def _set_scale(self, scale):
self._scale = scale
self._update_position()
scale = property(lambda self: self._scale, _set_scale,
doc='''Scaling factor.
A scaling factor of 1 (the default) has no effect. A scale of 2 will draw
the sprite at twice the native size of its image.
:type: float
''')
width = property(lambda self: int(self._texture.width * self._scale),
doc='''Scaled width of the sprite.
Read-only. Invariant under rotation.
:type: int
''')
height = property(lambda self: int(self._texture.height * self._scale),
doc='''Scaled height of the sprite.
Read-only. Invariant under rotation.
:type: int
''')
def _set_opacity(self, opacity):
self._opacity = opacity
self._update_color()
opacity = property(lambda self: self._opacity, _set_opacity,
doc='''Blend opacity.
This property sets the alpha component of the colour of the sprite's
vertices. With the default blend mode (see the constructor), this
allows the sprite to be drawn with fractional opacity, blending with the
background.
An opacity of 255 (the default) has no effect. An opacity of 128 will
make the sprite appear translucent.
:type: int
''')
def _set_color(self, rgb):
self._rgb = map(int, rgb)
self._update_color()
color = property(lambda self: self._rgb, _set_color,
doc='''Blend color.
This property sets the color of the sprite's vertices. This allows the
sprite to be drawn with a color tint.
The color is specified as an RGB tuple of integers ``(red, green, blue)``.
Each color component must be in the range 0 (dark) to 255 (saturated).
:type: (int, int, int)
''')
def _set_visible(self, visible):
self._visible = visible
self._update_position()
visible = property(lambda self: self._visible, _set_visible,
'''True if the sprite will be drawn.
:type: bool
''')
def draw(self):
'''Draw the sprite at its current position.
See the module documentation for hints on drawing multiple sprites
efficiently.
'''
self._group.set_state_recursive()
self._vertex_list.draw(GL_QUADS)
self._group.unset_state_recursive()
if _is_epydoc:
def on_animation_end(self):
'''The sprite animation reached the final frame.
The event is triggered only if the sprite has an animation, not an
image. For looping animations, the event is triggered each time
the animation loops.
:event:
'''
Sprite.register_event_type('on_animation_end')
| 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.
# ----------------------------------------------------------------------------
'''Compatibility tools
Various tools for simultaneous Python 2.x and Python 3.x support
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import sys
import itertools
if sys.version_info[0] == 2:
if sys.version_info[1] < 6:
#Pure Python implementation from
#http://docs.python.org/library/itertools.html#itertools.izip_longest
def izip_longest(*args, **kwds):
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue')
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError
fillers = itertools.repeat(fillvalue)
iters = [itertools.chain(it, sentinel(), fillers) for it in args]
try:
for tup in itertools.izip(*iters):
yield tup
except IndexError:
pass
else:
izip_longest = itertools.izip_longest
else:
izip_longest = itertools.zip_longest
if sys.version_info[0] >= 3:
import io
def asbytes(s):
if isinstance(s, bytes):
return s
elif isinstance(s, str):
return bytes(ord(c) for c in s)
else:
return bytes(s)
def asbytes_filename(s):
if isinstance(s, bytes):
return s
elif isinstance(s, str):
return s.encode(encoding=sys.getfilesystemencoding())
def asstr(s):
if isinstance(s, str):
return s
return s.decode("utf-8")
bytes_type = bytes
BytesIO = io.BytesIO
else:
import StringIO
asbytes = str
asbytes_filename = str
asstr = str
bytes_type = str
BytesIO = StringIO.StringIO
| 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$
"""
Implementation of the Truetype file format.
Typical applications will not need to use this module directly; look at
`pyglyph.font` instead.
References:
* http://developer.apple.com/fonts/TTRefMan/RM06
* http://www.microsoft.com/typography/otspec
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import codecs
import os
import mmap
import struct
class TruetypeInfo:
"""Information about a single Truetype face.
The class memory-maps the font file to read the tables, so
it is vital that you call the `close` method to avoid large memory
leaks. Once closed, you cannot call any of the ``get_*`` methods.
Not all tables have been implemented yet (or likely ever will).
Currently only the name and metric tables are read; in particular
there is no glyph or hinting information.
"""
_name_id_lookup = {
'copyright': 0,
'family': 1,
'subfamily': 2,
'identifier': 3,
'name': 4,
'version': 5,
'postscript': 6,
'trademark': 7,
'manufacturer': 8,
'designer': 9,
'description': 10,
'vendor-url': 11,
'designer-url': 12,
'license': 13,
'license-url': 14,
'preferred-family': 16,
'preferred-subfamily': 17,
'compatible-name': 18,
'sample': 19,
}
_platform_id_lookup = {
'unicode': 0,
'macintosh': 1,
'iso': 2,
'microsoft': 3,
'custom': 4
}
_microsoft_encoding_lookup = {
1: 'utf_16_be',
2: 'shift_jis',
4: 'big5',
6: 'johab',
10: 'utf_16_be'
}
_macintosh_encoding_lookup = {
0: 'mac_roman'
}
def __init__(self, filename):
"""Read the given TrueType file.
:Parameters:
`filename`
The name of any Windows, OS2 or Macintosh Truetype file.
The object must be closed (see `close`) after use.
An exception will be raised if the file does not exist or cannot
be read.
"""
if not filename: filename = ''
len = os.stat(filename).st_size
self._fileno = os.open(filename, os.O_RDONLY)
if hasattr(mmap, 'MAP_SHARED'):
self._data = mmap.mmap(self._fileno, len, mmap.MAP_SHARED,
mmap.PROT_READ)
else:
self._data = mmap.mmap(self._fileno, len, None, mmap.ACCESS_READ)
offsets = _read_offset_table(self._data, 0)
self._tables = {}
for table in _read_table_directory_entry.array(self._data,
offsets.size, offsets.num_tables):
self._tables[table.tag] = table
self._names = None
self._horizontal_metrics = None
self._character_advances = None
self._character_kernings = None
self._glyph_kernings = None
self._character_map = None
self._glyph_map = None
self._font_selection_flags = None
self.header = \
_read_head_table(self._data, self._tables['head'].offset)
self.horizontal_header = \
_read_horizontal_header(self._data, self._tables['hhea'].offset)
def get_font_selection_flags(self):
"""Return the font selection flags, as defined in OS/2 table"""
if not self._font_selection_flags:
OS2_table = \
_read_OS2_table(self._data, self._tables['OS/2'].offset)
self._font_selection_flags = OS2_table.fs_selection
return self._font_selection_flags
def is_bold(self):
"""Returns True iff the font describes itself as bold."""
return bool(self.get_font_selection_flags() & 0x20)
def is_italic(self):
"""Returns True iff the font describes itself as italic."""
return bool(self.get_font_selection_flags() & 0x1)
def get_names(self):
"""Returns a dictionary of names defined in the file.
The key of each item is a tuple of ``platform_id``, ``name_id``,
where each ID is the number as described in the Truetype format.
The value of each item is a tuple of
``encoding_id``, ``language_id``, ``value``, where ``value`` is
an encoded string.
"""
if self._names:
return self._names
naming_table = \
_read_naming_table(self._data, self._tables['name'].offset)
name_records = \
_read_name_record.array(self._data,
self._tables['name'].offset + naming_table.size,
naming_table.count)
storage = naming_table.string_offset + self._tables['name'].offset
self._names = {}
for record in name_records:
value = self._data[record.offset + storage:\
record.offset + storage + record.length]
key = record.platform_id, record.name_id
value = (record.encoding_id, record.language_id, value)
if not key in self._names:
self._names[key] = []
self._names[key].append(value)
return self._names
def get_name(self, name, platform=None, languages=None):
"""Returns the value of the given name in this font.
:Parameters:
`name`
Either an integer, representing the name_id desired (see
font format); or a string describing it, see below for
valid names.
`platform`
Platform for the requested name. Can be the integer ID,
or a string describing it. By default, the Microsoft
platform is searched first, then Macintosh.
`languages`
A list of language IDs to search. The first language
which defines the requested name will be used. By default,
all English dialects are searched.
If the name is not found, ``None`` is returned. If the name
is found, the value will be decoded and returned as a unicode
string. Currently only some common encodings are supported.
Valid names to request are (supply as a string)::
'copyright'
'family'
'subfamily'
'identifier'
'name'
'version'
'postscript'
'trademark'
'manufacturer'
'designer'
'description'
'vendor-url'
'designer-url'
'license'
'license-url'
'preferred-family'
'preferred-subfamily'
'compatible-name'
'sample'
Valid platforms to request are (supply as a string)::
'unicode'
'macintosh'
'iso'
'microsoft'
'custom'
"""
names = self.get_names()
if type(name) == str:
name = self._name_id_lookup[name]
if not platform:
for platform in ('microsoft','macintosh'):
value = self.get_name(name, platform, languages)
if value:
return value
if type(platform) == str:
platform = self._platform_id_lookup[platform]
if not (platform, name) in names:
return None
if platform == 3: # setup for microsoft
encodings = self._microsoft_encoding_lookup
if not languages:
# Default to english languages for microsoft
languages = (0x409,0x809,0xc09,0x1009,0x1409,0x1809)
elif platform == 1: # setup for macintosh
encodings = self.__macintosh_encoding_lookup
if not languages:
# Default to english for macintosh
languages = (0,)
for record in names[(platform, name)]:
if record[1] in languages and record[0] in encodings:
decoder = codecs.getdecoder(encodings[record[0]])
return decoder(record[2])[0]
return None
def get_horizontal_metrics(self):
"""Return all horizontal metric entries in table format."""
if not self._horizontal_metrics:
ar = _read_long_hor_metric.array(self._data,
self._tables['hmtx'].offset,
self.horizontal_header.number_of_h_metrics)
self._horizontal_metrics = ar
return self._horizontal_metrics
def get_character_advances(self):
"""Return a dictionary of character->advance.
They key of the dictionary is a unit-length unicode string,
and the value is a float giving the horizontal advance in
em.
"""
if self._character_advances:
return self._character_advances
ga = self.get_glyph_advances()
gmap = self.get_glyph_map()
self._character_advances = {}
for i in range(len(ga)):
if i in gmap and not gmap[i] in self._character_advances:
self._character_advances[gmap[i]] = ga[i]
return self._character_advances
def get_glyph_advances(self):
"""Return a dictionary of glyph->advance.
They key of the dictionary is the glyph index and the value is a float
giving the horizontal advance in em.
"""
hm = self.get_horizontal_metrics()
return [float(m.advance_width) / self.header.units_per_em for m in hm]
def get_character_kernings(self):
"""Return a dictionary of (left,right)->kerning
The key of the dictionary is a tuple of ``(left, right)``
where each element is a unit-length unicode string. The
value of the dictionary is the horizontal pairwise kerning
in em.
"""
if not self._character_kernings:
gmap = self.get_glyph_map()
kerns = self.get_glyph_kernings()
self._character_kernings = {}
for pair, value in kerns.items():
lglyph, rglyph = pair
lchar = lglyph in gmap and gmap[lglyph] or None
rchar = rglyph in gmap and gmap[rglyph] or None
if lchar and rchar:
self._character_kernings[(lchar, rchar)] = value
return self._character_kernings
def get_glyph_kernings(self):
"""Return a dictionary of (left,right)->kerning
The key of the dictionary is a tuple of ``(left, right)``
where each element is a glyph index. The value of the dictionary is
the horizontal pairwise kerning in em.
"""
if self._glyph_kernings:
return self._glyph_kernings
header = \
_read_kern_header_table(self._data, self._tables['kern'].offset)
offset = self._tables['kern'].offset + header.size
kernings = {}
for i in range(header.n_tables):
header = _read_kern_subtable_header(self._data, offset)
if header.coverage & header.horizontal_mask \
and not header.coverage & header.minimum_mask \
and not header.coverage & header.perpendicular_mask:
if header.coverage & header.format_mask == 0:
self._add_kernings_format0(kernings, offset + header.size)
offset += header.length
self._glyph_kernings = kernings
return kernings
def _add_kernings_format0(self, kernings, offset):
header = _read_kern_subtable_format0(self._data, offset)
kerning_pairs = _read_kern_subtable_format0Pair.array(self._data,
offset + header.size, header.n_pairs)
for pair in kerning_pairs:
if (pair.left, pair.right) in kernings:
kernings[(pair.left, pair.right)] += pair.value \
/ float(self.header.units_per_em)
else:
kernings[(pair.left, pair.right)] = pair.value \
/ float(self.header.units_per_em)
def get_glyph_map(self):
"""Calculate and return a reverse character map.
Returns a dictionary where the key is a glyph index and the
value is a unit-length unicode string.
"""
if self._glyph_map:
return self._glyph_map
cmap = self.get_character_map()
self._glyph_map = {}
for ch, glyph in cmap.items():
if not glyph in self._glyph_map:
self._glyph_map[glyph] = ch
return self._glyph_map
def get_character_map(self):
"""Return the character map.
Returns a dictionary where the key is a unit-length unicode
string and the value is a glyph index. Currently only
format 4 character maps are read.
"""
if self._character_map:
return self._character_map
cmap = _read_cmap_header(self._data, self._tables['cmap'].offset)
records = _read_cmap_encoding_record.array(self._data,
self._tables['cmap'].offset + cmap.size, cmap.num_tables)
self._character_map = {}
for record in records:
if record.platform_id == 3 and record.encoding_id == 1:
# Look at Windows Unicode charmaps only
offset = self._tables['cmap'].offset + record.offset
format_header = _read_cmap_format_header(self._data, offset)
if format_header.format == 4:
self._character_map = \
self._get_character_map_format4(offset)
break
return self._character_map
def _get_character_map_format4(self, offset):
# This is absolutely, without question, the *worst* file
# format ever. Whoever the fuckwit is that thought this up is
# a fuckwit.
header = _read_cmap_format4Header(self._data, offset)
seg_count = header.seg_count_x2 / 2
array_size = struct.calcsize('>%dH' % seg_count)
end_count = self._read_array('>%dH' % seg_count,
offset + header.size)
start_count = self._read_array('>%dH' % seg_count,
offset + header.size + array_size + 2)
id_delta = self._read_array('>%dh' % seg_count,
offset + header.size + array_size + 2 + array_size)
id_range_offset_address = \
offset + header.size + array_size + 2 + array_size + array_size
id_range_offset = self._read_array('>%dH' % seg_count,
id_range_offset_address)
character_map = {}
for i in range(0, seg_count):
if id_range_offset[i] != 0:
if id_range_offset[i] == 65535:
continue # Hack around a dodgy font (babelfish.ttf)
for c in range(start_count[i], end_count[i] + 1):
addr = id_range_offset[i] + 2*(c - start_count[i]) + \
id_range_offset_address + 2*i
g = struct.unpack('>H', self._data[addr:addr+2])[0]
if g != 0:
character_map[unichr(c)] = (g + id_delta[i]) % 65536
else:
for c in range(start_count[i], end_count[i] + 1):
g = (c + id_delta[i]) % 65536
if g != 0:
character_map[unichr(c)] = g
return character_map
def _read_array(self, format, offset):
size = struct.calcsize(format)
return struct.unpack(format, self._data[offset:offset+size])
def close(self):
"""Close the font file.
This is a good idea, since the entire file is memory mapped in
until this method is called. After closing cannot rely on the
``get_*`` methods.
"""
self._data.close()
os.close(self._fileno)
def _read_table(*entries):
""" Generic table constructor used for table formats listed at
end of file."""
fmt = '>'
names = []
for entry in entries:
name, type = entry.split(':')
names.append(name)
fmt += type
class _table_class:
size = struct.calcsize(fmt)
def __init__(self, data, offset):
items = struct.unpack(fmt, data[offset:offset+self.size])
self.pairs = zip(names, items)
for name, value in self.pairs:
setattr(self, name, value)
def __repr__(self):
s = '{' + ', '.join(['%s = %s' % (name, value) \
for name, value in self.pairs]) + '}'
return s
@staticmethod
def array(data, offset, count):
tables = []
for i in range(count):
tables.append(_table_class(data, offset))
offset += _table_class.size
return tables
return _table_class
# Table formats (see references)
_read_offset_table = _read_table('scalertype:I',
'num_tables:H',
'search_range:H',
'entry_selector:H',
'range_shift:H')
_read_table_directory_entry = _read_table('tag:4s',
'check_sum:I',
'offset:I',
'length:I')
_read_head_table = _read_table('version:i',
'font_revision:i',
'check_sum_adjustment:L',
'magic_number:L',
'flags:H',
'units_per_em:H',
'created:Q',
'modified:Q',
'x_min:h',
'y_min:h',
'x_max:h',
'y_max:h',
'mac_style:H',
'lowest_rec_p_pEM:H',
'font_direction_hint:h',
'index_to_loc_format:h',
'glyph_data_format:h')
_read_OS2_table = _read_table('version:H',
'x_avg_char_width:h',
'us_weight_class:H',
'us_width_class:H',
'fs_type:H',
'y_subscript_x_size:h',
'y_subscript_y_size:h',
'y_subscript_x_offset:h',
'y_subscript_y_offset:h',
'y_superscript_x_size:h',
'y_superscript_y_size:h',
'y_superscript_x_offset:h',
'y_superscript_y_offset:h',
'y_strikeout_size:h',
'y_strikeout_position:h',
's_family_class:h',
'panose1:B',
'panose2:B',
'panose3:B',
'panose4:B',
'panose5:B',
'panose6:B',
'panose7:B',
'panose8:B',
'panose9:B',
'panose10:B',
'ul_unicode_range1:L',
'ul_unicode_range2:L',
'ul_unicode_range3:L',
'ul_unicode_range4:L',
'ach_vend_id:I',
'fs_selection:H',
'us_first_char_index:H',
'us_last_char_index:H',
's_typo_ascender:h',
's_typo_descender:h',
's_typo_line_gap:h',
'us_win_ascent:H',
'us_win_descent:H',
'ul_code_page_range1:L',
'ul_code_page_range2:L',
'sx_height:h',
's_cap_height:h',
'us_default_char:H',
'us_break_char:H',
'us_max_context:H')
_read_kern_header_table = _read_table('version_num:H',
'n_tables:H')
_read_kern_subtable_header = _read_table('version:H',
'length:H',
'coverage:H')
_read_kern_subtable_header.horizontal_mask = 0x1
_read_kern_subtable_header.minimum_mask = 0x2
_read_kern_subtable_header.perpendicular_mask = 0x4
_read_kern_subtable_header.override_mask = 0x5
_read_kern_subtable_header.format_mask = 0xf0
_read_kern_subtable_format0 = _read_table('n_pairs:H',
'search_range:H',
'entry_selector:H',
'range_shift:H')
_read_kern_subtable_format0Pair = _read_table('left:H',
'right:H',
'value:h')
_read_cmap_header = _read_table('version:H',
'num_tables:H')
_read_cmap_encoding_record = _read_table('platform_id:H',
'encoding_id:H',
'offset:L')
_read_cmap_format_header = _read_table('format:H',
'length:H')
_read_cmap_format4Header = _read_table('format:H',
'length:H',
'language:H',
'seg_count_x2:H',
'search_range:H',
'entry_selector:H',
'range_shift:H')
_read_horizontal_header = _read_table('version:i',
'Advance:h',
'Descender:h',
'LineGap:h',
'advance_width_max:H',
'min_left_side_bearing:h',
'min_right_side_bearing:h',
'x_max_extent:h',
'caret_slope_rise:h',
'caret_slope_run:h',
'caret_offset:h',
'reserved1:h',
'reserved2:h',
'reserved3:h',
'reserved4:h',
'metric_data_format:h',
'number_of_h_metrics:H')
_read_long_hor_metric = _read_table('advance_width:H',
'lsb:h')
_read_naming_table = _read_table('format:H',
'count:H',
'string_offset:H')
_read_name_record = _read_table('platform_id:H',
'encoding_id:H',
'language_id:H',
'name_id:H',
'length:H',
'offset:H')
| 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.
# ----------------------------------------------------------------------------
'''
'''
# TODO Windows Vista: need to call SetProcessDPIAware? May affect GDI+ calls
# as well as font.
from ctypes import *
import ctypes
import math
from sys import byteorder
import pyglet
from pyglet.font import base
import pyglet.image
from pyglet.libs.win32.constants import *
from pyglet.libs.win32.types import *
from pyglet.libs.win32 import _gdi32 as gdi32, _user32 as user32
from pyglet.libs.win32 import _kernel32 as kernel32
from pyglet.compat import asbytes
_debug_font = pyglet.options['debug_font']
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')
_debug_dir = 'debug_font'
def _debug_filename(base, extension):
import os
if not os.path.exists(_debug_dir):
os.makedirs(_debug_dir)
name = '%s-%%d.%%s' % os.path.join(_debug_dir, base)
num = 1
while os.path.exists(name % (num, extension)):
num += 1
return name % (num, extension)
def _debug_image(image, name):
filename = _debug_filename(name, 'png')
image.save(filename)
_debug('Saved image %r to %s' % (image, filename))
_debug_logfile = None
def _debug(msg):
global _debug_logfile
if not _debug_logfile:
_debug_logfile = open(_debug_filename('log', 'txt'), 'wt')
_debug_logfile.write(msg + '\n')
class Win32GlyphRenderer(base.GlyphRenderer):
_bitmap = None
_dc = None
_bitmap_rect = None
def __init__(self, font):
super(Win32GlyphRenderer, self).__init__(font)
self.font = font
# Pessimistically round up width and height to 4 byte alignment
width = font.max_glyph_width
height = font.ascent - font.descent
width = (width | 0x3) + 1
height = (height | 0x3) + 1
self._create_bitmap(width, height)
gdi32.SelectObject(self._dc, self.font.hfont)
def _create_bitmap(self, width, height):
pass
def render(self, text):
raise NotImplementedError('abstract')
class GDIGlyphRenderer(Win32GlyphRenderer):
def __del__(self):
try:
if self._dc:
gdi32.DeleteDC(self._dc)
if self._bitmap:
gdi32.DeleteObject(self._bitmap)
except:
pass
def render(self, text):
# Attempt to get ABC widths (only for TrueType)
abc = ABC()
if gdi32.GetCharABCWidthsW(self._dc,
ord(text), ord(text), byref(abc)):
width = abc.abcB
lsb = abc.abcA
advance = abc.abcA + abc.abcB + abc.abcC
else:
width_buf = c_int()
gdi32.GetCharWidth32W(self._dc,
ord(text), ord(text), byref(width_buf))
width = width_buf.value
lsb = 0
advance = width
# Can't get glyph-specific dimensions, use whole line-height.
height = self._bitmap_height
image = self._get_image(text, width, height, lsb)
glyph = self.font.create_glyph(image)
glyph.set_bearings(-self.font.descent, lsb, advance)
if _debug_font:
_debug('%r.render(%s)' % (self, text))
_debug('abc.abcA = %r' % abc.abcA)
_debug('abc.abcB = %r' % abc.abcB)
_debug('abc.abcC = %r' % abc.abcC)
_debug('width = %r' % width)
_debug('height = %r' % height)
_debug('lsb = %r' % lsb)
_debug('advance = %r' % advance)
_debug_image(image, 'glyph_%s' % text)
_debug_image(self.font.textures[0], 'tex_%s' % text)
return glyph
def _get_image(self, text, width, height, lsb):
# There's no such thing as a greyscale bitmap format in GDI. We can
# create an 8-bit palette bitmap with 256 shades of grey, but
# unfortunately antialiasing will not work on such a bitmap. So, we
# use a 32-bit bitmap and use the red channel as OpenGL's alpha.
gdi32.SelectObject(self._dc, self._bitmap)
gdi32.SelectObject(self._dc, self.font.hfont)
gdi32.SetBkColor(self._dc, 0x0)
gdi32.SetTextColor(self._dc, 0x00ffffff)
gdi32.SetBkMode(self._dc, OPAQUE)
# Draw to DC
user32.FillRect(self._dc, byref(self._bitmap_rect), self._black)
gdi32.ExtTextOutA(self._dc, -lsb, 0, 0, None, text,
len(text), None)
gdi32.GdiFlush()
# Create glyph object and copy bitmap data to texture
image = pyglet.image.ImageData(width, height,
'AXXX', self._bitmap_data, self._bitmap_rect.right * 4)
return image
def _create_bitmap(self, width, height):
self._black = gdi32.GetStockObject(BLACK_BRUSH)
self._white = gdi32.GetStockObject(WHITE_BRUSH)
if self._dc:
gdi32.ReleaseDC(self._dc)
if self._bitmap:
gdi32.DeleteObject(self._bitmap)
pitch = width * 4
data = POINTER(c_byte * (height * pitch))()
info = BITMAPINFO()
info.bmiHeader.biSize = sizeof(info.bmiHeader)
info.bmiHeader.biWidth = width
info.bmiHeader.biHeight = height
info.bmiHeader.biPlanes = 1
info.bmiHeader.biBitCount = 32
info.bmiHeader.biCompression = BI_RGB
self._dc = gdi32.CreateCompatibleDC(None)
self._bitmap = gdi32.CreateDIBSection(None,
byref(info), DIB_RGB_COLORS, byref(data), None,
0)
# Spookiness: the above line causes a "not enough storage" error,
# even though that error cannot be generated according to docs,
# and everything works fine anyway. Call SetLastError to clear it.
kernel32.SetLastError(0)
self._bitmap_data = data.contents
self._bitmap_rect = RECT()
self._bitmap_rect.left = 0
self._bitmap_rect.right = width
self._bitmap_rect.top = 0
self._bitmap_rect.bottom = height
self._bitmap_height = height
if _debug_font:
_debug('%r._create_dc(%d, %d)' % (self, width, height))
_debug('_dc = %r' % self._dc)
_debug('_bitmap = %r' % self._bitmap)
_debug('pitch = %r' % pitch)
_debug('info.bmiHeader.biSize = %r' % info.bmiHeader.biSize)
class Win32Font(base.Font):
glyph_renderer_class = GDIGlyphRenderer
def __init__(self, name, size, bold=False, italic=False, dpi=None):
super(Win32Font, self).__init__()
self.logfont = self.get_logfont(name, size, bold, italic, dpi)
self.hfont = gdi32.CreateFontIndirectA(byref(self.logfont))
# Create a dummy DC for coordinate mapping
dc = user32.GetDC(0)
metrics = TEXTMETRIC()
gdi32.SelectObject(dc, self.hfont)
gdi32.GetTextMetricsA(dc, byref(metrics))
self.ascent = metrics.tmAscent
self.descent = -metrics.tmDescent
self.max_glyph_width = metrics.tmMaxCharWidth
@staticmethod
def get_logfont(name, size, bold, italic, dpi):
# Create a dummy DC for coordinate mapping
dc = user32.GetDC(0)
if dpi is None:
dpi = 96
logpixelsy = dpi
logfont = LOGFONT()
# Conversion of point size to device pixels
logfont.lfHeight = int(-size * logpixelsy // 72)
if bold:
logfont.lfWeight = FW_BOLD
else:
logfont.lfWeight = FW_NORMAL
logfont.lfItalic = italic
logfont.lfFaceName = asbytes(name)
logfont.lfQuality = ANTIALIASED_QUALITY
return logfont
@classmethod
def have_font(cls, name):
# CreateFontIndirect always returns a font... have to work out
# something with EnumFontFamily... TODO
return True
@classmethod
def add_font_data(cls, data):
numfonts = c_uint32()
gdi32.AddFontMemResourceEx(data, len(data), 0, byref(numfonts))
# --- GDI+ font rendering ---
from pyglet.image.codecs.gdiplus import PixelFormat32bppARGB, gdiplus, Rect
from pyglet.image.codecs.gdiplus import ImageLockModeRead, BitmapData
DriverStringOptionsCmapLookup = 1
DriverStringOptionsRealizedAdvance = 4
TextRenderingHintAntiAlias = 4
TextRenderingHintAntiAliasGridFit = 3
StringFormatFlagsDirectionRightToLeft = 0x00000001
StringFormatFlagsDirectionVertical = 0x00000002
StringFormatFlagsNoFitBlackBox = 0x00000004
StringFormatFlagsDisplayFormatControl = 0x00000020
StringFormatFlagsNoFontFallback = 0x00000400
StringFormatFlagsMeasureTrailingSpaces = 0x00000800
StringFormatFlagsNoWrap = 0x00001000
StringFormatFlagsLineLimit = 0x00002000
StringFormatFlagsNoClip = 0x00004000
class Rectf(ctypes.Structure):
_fields_ = [
('x', ctypes.c_float),
('y', ctypes.c_float),
('width', ctypes.c_float),
('height', ctypes.c_float),
]
class GDIPlusGlyphRenderer(Win32GlyphRenderer):
def _create_bitmap(self, width, height):
self._data = (ctypes.c_byte * (4 * width * height))()
self._bitmap = ctypes.c_void_p()
self._format = PixelFormat32bppARGB
gdiplus.GdipCreateBitmapFromScan0(width, height, width * 4,
self._format, self._data, ctypes.byref(self._bitmap))
self._graphics = ctypes.c_void_p()
gdiplus.GdipGetImageGraphicsContext(self._bitmap,
ctypes.byref(self._graphics))
gdiplus.GdipSetPageUnit(self._graphics, UnitPixel)
self._dc = user32.GetDC(0)
gdi32.SelectObject(self._dc, self.font.hfont)
gdiplus.GdipSetTextRenderingHint(self._graphics,
TextRenderingHintAntiAliasGridFit)
self._brush = ctypes.c_void_p()
gdiplus.GdipCreateSolidFill(0xffffffff, ctypes.byref(self._brush))
self._matrix = ctypes.c_void_p()
gdiplus.GdipCreateMatrix(ctypes.byref(self._matrix))
self._flags = (DriverStringOptionsCmapLookup |
DriverStringOptionsRealizedAdvance)
self._rect = Rect(0, 0, width, height)
self._bitmap_height = height
def render(self, text):
ch = ctypes.create_unicode_buffer(text)
len_ch = len(text)
# Layout rectangle; not clipped against so not terribly important.
width = 10000
height = self._bitmap_height
rect = Rectf(0, self._bitmap_height
- self.font.ascent + self.font.descent,
width, height)
# Set up GenericTypographic with 1 character measure range
generic = ctypes.c_void_p()
gdiplus.GdipStringFormatGetGenericTypographic(ctypes.byref(generic))
format = ctypes.c_void_p()
gdiplus.GdipCloneStringFormat(generic, ctypes.byref(format))
# Measure advance
bbox = Rectf()
flags = (StringFormatFlagsMeasureTrailingSpaces |
StringFormatFlagsNoClip |
StringFormatFlagsNoFitBlackBox)
gdiplus.GdipSetStringFormatFlags(format, flags)
gdiplus.GdipMeasureString(self._graphics, ch, len_ch,
self.font._gdipfont, ctypes.byref(rect), format,
ctypes.byref(bbox), None, None)
lsb = 0
advance = int(math.ceil(bbox.width))
# XXX HACK HACK HACK
# Windows GDI+ is a filthy broken toy. No way to measure the bounding
# box of a string, or to obtain LSB. What a joke.
#
# For historical note, GDI cannot be used because it cannot composite
# into a bitmap with alpha.
#
# It looks like MS have abandoned GDI and GDI+ and are finally
# supporting accurate text measurement with alpha composition in .NET
# 2.0 (WinForms) via the TextRenderer class; this has no C interface
# though, so we're entirely screwed.
#
# So anyway, this hack bumps up the width if the font is italic;
# this compensates for some common fonts. It's also a stupid waste of
# texture memory.
width = advance
if self.font.italic:
width += width // 2
# XXX END HACK HACK HACK
# Draw character to bitmap
gdiplus.GdipGraphicsClear(self._graphics, 0x00000000)
gdiplus.GdipDrawString(self._graphics, ch, len_ch,
self.font._gdipfont, ctypes.byref(rect), format,
self._brush)
gdiplus.GdipFlush(self._graphics, 1)
bitmap_data = BitmapData()
gdiplus.GdipBitmapLockBits(self._bitmap,
byref(self._rect), ImageLockModeRead, self._format,
byref(bitmap_data))
# Create buffer for RawImage
buffer = create_string_buffer(
bitmap_data.Stride * bitmap_data.Height)
memmove(buffer, bitmap_data.Scan0, len(buffer))
# Unlock data
gdiplus.GdipBitmapUnlockBits(self._bitmap, byref(bitmap_data))
image = pyglet.image.ImageData(width, height,
'BGRA', buffer, -bitmap_data.Stride)
glyph = self.font.create_glyph(image)
glyph.set_bearings(-self.font.descent, lsb, advance)
return glyph
FontStyleBold = 1
FontStyleItalic = 2
UnitPixel = 2
UnitPoint = 3
class GDIPlusFont(Win32Font):
glyph_renderer_class = GDIPlusGlyphRenderer
_private_fonts = None
_default_name = 'Arial'
def __init__(self, name, size, bold=False, italic=False, dpi=None):
if not name:
name = self._default_name
super(GDIPlusFont, self).__init__(name, size, bold, italic, dpi)
family = ctypes.c_void_p()
name = ctypes.c_wchar_p(name)
# Look in private collection first:
if self._private_fonts:
gdiplus.GdipCreateFontFamilyFromName(name,
self._private_fonts, ctypes.byref(family))
# Then in system collection:
if not family:
gdiplus.GdipCreateFontFamilyFromName(name,
None, ctypes.byref(family))
# Nothing found, use default font.
if not family:
name = self._default_name
gdiplus.GdipCreateFontFamilyFromName(ctypes.c_wchar_p(name),
None, ctypes.byref(family))
if dpi is None:
unit = UnitPoint
self.dpi = 96
else:
unit = UnitPixel
size = (size * dpi) // 72
self.dpi = dpi
style = 0
if bold:
style |= FontStyleBold
if italic:
style |= FontStyleItalic
self.italic = italic # XXX needed for HACK HACK HACK
self._gdipfont = ctypes.c_void_p()
gdiplus.GdipCreateFont(family, ctypes.c_float(size),
style, unit, ctypes.byref(self._gdipfont))
@classmethod
def add_font_data(cls, data):
super(GDIPlusFont, cls).add_font_data(data)
if not cls._private_fonts:
cls._private_fonts = ctypes.c_void_p()
gdiplus.GdipNewPrivateFontCollection(
ctypes.byref(cls._private_fonts))
gdiplus.GdipPrivateAddMemoryFont(cls._private_fonts, data, len(data))
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.