code
stringlengths
1
1.72M
language
stringclasses
1 value
'''Wrapper for Xi Generated with: tools/genwrappers.py xinput Do not modify this file. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * import pyglet.lib _lib = pyglet.lib.load_library('Xi') _int_types = (c_int16, c_int32) if hasattr(ctypes, 'c_int64'): # Some builds of ctypes apparently do not have c_int64 # defined; it's a pretty good bet that these builds do not # have 64-bit pointers. _int_types += (ctypes.c_int64,) for t in _int_types: if sizeof(t) == sizeof(c_size_t): c_ptrdiff_t = t class c_void(Structure): # c_void_p is a buggy return type, converting to int, so # POINTER(None) == c_void_p is actually written as # POINTER(c_void), so it can be treated as a real pointer. _fields_ = [('dummy', c_int)] import pyglet.libs.x11.xlib sz_xGetExtensionVersionReq = 8 # /usr/include/X11/extensions/XI.h:56 sz_xGetExtensionVersionReply = 32 # /usr/include/X11/extensions/XI.h:57 sz_xListInputDevicesReq = 4 # /usr/include/X11/extensions/XI.h:58 sz_xListInputDevicesReply = 32 # /usr/include/X11/extensions/XI.h:59 sz_xOpenDeviceReq = 8 # /usr/include/X11/extensions/XI.h:60 sz_xOpenDeviceReply = 32 # /usr/include/X11/extensions/XI.h:61 sz_xCloseDeviceReq = 8 # /usr/include/X11/extensions/XI.h:62 sz_xSetDeviceModeReq = 8 # /usr/include/X11/extensions/XI.h:63 sz_xSetDeviceModeReply = 32 # /usr/include/X11/extensions/XI.h:64 sz_xSelectExtensionEventReq = 12 # /usr/include/X11/extensions/XI.h:65 sz_xGetSelectedExtensionEventsReq = 8 # /usr/include/X11/extensions/XI.h:66 sz_xGetSelectedExtensionEventsReply = 32 # /usr/include/X11/extensions/XI.h:67 sz_xChangeDeviceDontPropagateListReq = 12 # /usr/include/X11/extensions/XI.h:68 sz_xGetDeviceDontPropagateListReq = 8 # /usr/include/X11/extensions/XI.h:69 sz_xGetDeviceDontPropagateListReply = 32 # /usr/include/X11/extensions/XI.h:70 sz_xGetDeviceMotionEventsReq = 16 # /usr/include/X11/extensions/XI.h:71 sz_xGetDeviceMotionEventsReply = 32 # /usr/include/X11/extensions/XI.h:72 sz_xChangeKeyboardDeviceReq = 8 # /usr/include/X11/extensions/XI.h:73 sz_xChangeKeyboardDeviceReply = 32 # /usr/include/X11/extensions/XI.h:74 sz_xChangePointerDeviceReq = 8 # /usr/include/X11/extensions/XI.h:75 sz_xChangePointerDeviceReply = 32 # /usr/include/X11/extensions/XI.h:76 sz_xGrabDeviceReq = 20 # /usr/include/X11/extensions/XI.h:77 sz_xGrabDeviceReply = 32 # /usr/include/X11/extensions/XI.h:78 sz_xUngrabDeviceReq = 12 # /usr/include/X11/extensions/XI.h:79 sz_xGrabDeviceKeyReq = 20 # /usr/include/X11/extensions/XI.h:80 sz_xGrabDeviceKeyReply = 32 # /usr/include/X11/extensions/XI.h:81 sz_xUngrabDeviceKeyReq = 16 # /usr/include/X11/extensions/XI.h:82 sz_xGrabDeviceButtonReq = 20 # /usr/include/X11/extensions/XI.h:83 sz_xGrabDeviceButtonReply = 32 # /usr/include/X11/extensions/XI.h:84 sz_xUngrabDeviceButtonReq = 16 # /usr/include/X11/extensions/XI.h:85 sz_xAllowDeviceEventsReq = 12 # /usr/include/X11/extensions/XI.h:86 sz_xGetDeviceFocusReq = 8 # /usr/include/X11/extensions/XI.h:87 sz_xGetDeviceFocusReply = 32 # /usr/include/X11/extensions/XI.h:88 sz_xSetDeviceFocusReq = 16 # /usr/include/X11/extensions/XI.h:89 sz_xGetFeedbackControlReq = 8 # /usr/include/X11/extensions/XI.h:90 sz_xGetFeedbackControlReply = 32 # /usr/include/X11/extensions/XI.h:91 sz_xChangeFeedbackControlReq = 12 # /usr/include/X11/extensions/XI.h:92 sz_xGetDeviceKeyMappingReq = 8 # /usr/include/X11/extensions/XI.h:93 sz_xGetDeviceKeyMappingReply = 32 # /usr/include/X11/extensions/XI.h:94 sz_xChangeDeviceKeyMappingReq = 8 # /usr/include/X11/extensions/XI.h:95 sz_xGetDeviceModifierMappingReq = 8 # /usr/include/X11/extensions/XI.h:96 sz_xSetDeviceModifierMappingReq = 8 # /usr/include/X11/extensions/XI.h:97 sz_xSetDeviceModifierMappingReply = 32 # /usr/include/X11/extensions/XI.h:98 sz_xGetDeviceButtonMappingReq = 8 # /usr/include/X11/extensions/XI.h:99 sz_xGetDeviceButtonMappingReply = 32 # /usr/include/X11/extensions/XI.h:100 sz_xSetDeviceButtonMappingReq = 8 # /usr/include/X11/extensions/XI.h:101 sz_xSetDeviceButtonMappingReply = 32 # /usr/include/X11/extensions/XI.h:102 sz_xQueryDeviceStateReq = 8 # /usr/include/X11/extensions/XI.h:103 sz_xQueryDeviceStateReply = 32 # /usr/include/X11/extensions/XI.h:104 sz_xSendExtensionEventReq = 16 # /usr/include/X11/extensions/XI.h:105 sz_xDeviceBellReq = 8 # /usr/include/X11/extensions/XI.h:106 sz_xSetDeviceValuatorsReq = 8 # /usr/include/X11/extensions/XI.h:107 sz_xSetDeviceValuatorsReply = 32 # /usr/include/X11/extensions/XI.h:108 sz_xGetDeviceControlReq = 8 # /usr/include/X11/extensions/XI.h:109 sz_xGetDeviceControlReply = 32 # /usr/include/X11/extensions/XI.h:110 sz_xChangeDeviceControlReq = 8 # /usr/include/X11/extensions/XI.h:111 sz_xChangeDeviceControlReply = 32 # /usr/include/X11/extensions/XI.h:112 Dont_Check = 0 # /usr/include/X11/extensions/XI.h:135 XInput_Initial_Release = 1 # /usr/include/X11/extensions/XI.h:136 XInput_Add_XDeviceBell = 2 # /usr/include/X11/extensions/XI.h:137 XInput_Add_XSetDeviceValuators = 3 # /usr/include/X11/extensions/XI.h:138 XInput_Add_XChangeDeviceControl = 4 # /usr/include/X11/extensions/XI.h:139 XInput_Add_DevicePresenceNotify = 5 # /usr/include/X11/extensions/XI.h:140 XI_Absent = 0 # /usr/include/X11/extensions/XI.h:142 XI_Present = 1 # /usr/include/X11/extensions/XI.h:143 XI_Initial_Release_Major = 1 # /usr/include/X11/extensions/XI.h:145 XI_Initial_Release_Minor = 0 # /usr/include/X11/extensions/XI.h:146 XI_Add_XDeviceBell_Major = 1 # /usr/include/X11/extensions/XI.h:148 XI_Add_XDeviceBell_Minor = 1 # /usr/include/X11/extensions/XI.h:149 XI_Add_XSetDeviceValuators_Major = 1 # /usr/include/X11/extensions/XI.h:151 XI_Add_XSetDeviceValuators_Minor = 2 # /usr/include/X11/extensions/XI.h:152 XI_Add_XChangeDeviceControl_Major = 1 # /usr/include/X11/extensions/XI.h:154 XI_Add_XChangeDeviceControl_Minor = 3 # /usr/include/X11/extensions/XI.h:155 XI_Add_DevicePresenceNotify_Major = 1 # /usr/include/X11/extensions/XI.h:157 XI_Add_DevicePresenceNotify_Minor = 4 # /usr/include/X11/extensions/XI.h:158 DEVICE_RESOLUTION = 1 # /usr/include/X11/extensions/XI.h:160 DEVICE_ABS_CALIB = 2 # /usr/include/X11/extensions/XI.h:161 DEVICE_CORE = 3 # /usr/include/X11/extensions/XI.h:162 DEVICE_ENABLE = 4 # /usr/include/X11/extensions/XI.h:163 DEVICE_ABS_AREA = 5 # /usr/include/X11/extensions/XI.h:164 NoSuchExtension = 1 # /usr/include/X11/extensions/XI.h:166 COUNT = 0 # /usr/include/X11/extensions/XI.h:168 CREATE = 1 # /usr/include/X11/extensions/XI.h:169 NewPointer = 0 # /usr/include/X11/extensions/XI.h:171 NewKeyboard = 1 # /usr/include/X11/extensions/XI.h:172 XPOINTER = 0 # /usr/include/X11/extensions/XI.h:174 XKEYBOARD = 1 # /usr/include/X11/extensions/XI.h:175 UseXKeyboard = 255 # /usr/include/X11/extensions/XI.h:177 IsXPointer = 0 # /usr/include/X11/extensions/XI.h:179 IsXKeyboard = 1 # /usr/include/X11/extensions/XI.h:180 IsXExtensionDevice = 2 # /usr/include/X11/extensions/XI.h:181 IsXExtensionKeyboard = 3 # /usr/include/X11/extensions/XI.h:182 IsXExtensionPointer = 4 # /usr/include/X11/extensions/XI.h:183 AsyncThisDevice = 0 # /usr/include/X11/extensions/XI.h:185 SyncThisDevice = 1 # /usr/include/X11/extensions/XI.h:186 ReplayThisDevice = 2 # /usr/include/X11/extensions/XI.h:187 AsyncOtherDevices = 3 # /usr/include/X11/extensions/XI.h:188 AsyncAll = 4 # /usr/include/X11/extensions/XI.h:189 SyncAll = 5 # /usr/include/X11/extensions/XI.h:190 FollowKeyboard = 3 # /usr/include/X11/extensions/XI.h:192 RevertToFollowKeyboard = 3 # /usr/include/X11/extensions/XI.h:194 DvAccelNum = 1 # /usr/include/X11/extensions/XI.h:197 DvAccelDenom = 2 # /usr/include/X11/extensions/XI.h:198 DvThreshold = 4 # /usr/include/X11/extensions/XI.h:199 DvKeyClickPercent = 1 # /usr/include/X11/extensions/XI.h:201 DvPercent = 2 # /usr/include/X11/extensions/XI.h:202 DvPitch = 4 # /usr/include/X11/extensions/XI.h:203 DvDuration = 8 # /usr/include/X11/extensions/XI.h:204 DvLed = 16 # /usr/include/X11/extensions/XI.h:205 DvLedMode = 32 # /usr/include/X11/extensions/XI.h:206 DvKey = 64 # /usr/include/X11/extensions/XI.h:207 DvAutoRepeatMode = 128 # /usr/include/X11/extensions/XI.h:208 DvString = 1 # /usr/include/X11/extensions/XI.h:210 DvInteger = 1 # /usr/include/X11/extensions/XI.h:212 DeviceMode = 1 # /usr/include/X11/extensions/XI.h:214 Relative = 0 # /usr/include/X11/extensions/XI.h:215 Absolute = 1 # /usr/include/X11/extensions/XI.h:216 ProximityState = 2 # /usr/include/X11/extensions/XI.h:218 InProximity = 0 # /usr/include/X11/extensions/XI.h:219 OutOfProximity = 2 # /usr/include/X11/extensions/XI.h:220 AddToList = 0 # /usr/include/X11/extensions/XI.h:222 DeleteFromList = 1 # /usr/include/X11/extensions/XI.h:223 KeyClass = 0 # /usr/include/X11/extensions/XI.h:225 ButtonClass = 1 # /usr/include/X11/extensions/XI.h:226 ValuatorClass = 2 # /usr/include/X11/extensions/XI.h:227 FeedbackClass = 3 # /usr/include/X11/extensions/XI.h:228 ProximityClass = 4 # /usr/include/X11/extensions/XI.h:229 FocusClass = 5 # /usr/include/X11/extensions/XI.h:230 OtherClass = 6 # /usr/include/X11/extensions/XI.h:231 KbdFeedbackClass = 0 # /usr/include/X11/extensions/XI.h:233 PtrFeedbackClass = 1 # /usr/include/X11/extensions/XI.h:234 StringFeedbackClass = 2 # /usr/include/X11/extensions/XI.h:235 IntegerFeedbackClass = 3 # /usr/include/X11/extensions/XI.h:236 LedFeedbackClass = 4 # /usr/include/X11/extensions/XI.h:237 BellFeedbackClass = 5 # /usr/include/X11/extensions/XI.h:238 _devicePointerMotionHint = 0 # /usr/include/X11/extensions/XI.h:240 _deviceButton1Motion = 1 # /usr/include/X11/extensions/XI.h:241 _deviceButton2Motion = 2 # /usr/include/X11/extensions/XI.h:242 _deviceButton3Motion = 3 # /usr/include/X11/extensions/XI.h:243 _deviceButton4Motion = 4 # /usr/include/X11/extensions/XI.h:244 _deviceButton5Motion = 5 # /usr/include/X11/extensions/XI.h:245 _deviceButtonMotion = 6 # /usr/include/X11/extensions/XI.h:246 _deviceButtonGrab = 7 # /usr/include/X11/extensions/XI.h:247 _deviceOwnerGrabButton = 8 # /usr/include/X11/extensions/XI.h:248 _noExtensionEvent = 9 # /usr/include/X11/extensions/XI.h:249 _devicePresence = 0 # /usr/include/X11/extensions/XI.h:251 DeviceAdded = 0 # /usr/include/X11/extensions/XI.h:253 DeviceRemoved = 1 # /usr/include/X11/extensions/XI.h:254 DeviceEnabled = 2 # /usr/include/X11/extensions/XI.h:255 DeviceDisabled = 3 # /usr/include/X11/extensions/XI.h:256 DeviceUnrecoverable = 4 # /usr/include/X11/extensions/XI.h:257 XI_BadDevice = 0 # /usr/include/X11/extensions/XI.h:259 XI_BadEvent = 1 # /usr/include/X11/extensions/XI.h:260 XI_BadMode = 2 # /usr/include/X11/extensions/XI.h:261 XI_DeviceBusy = 3 # /usr/include/X11/extensions/XI.h:262 XI_BadClass = 4 # /usr/include/X11/extensions/XI.h:263 XEventClass = c_ulong # /usr/include/X11/extensions/XI.h:272 class struct_anon_94(Structure): __slots__ = [ 'present', 'major_version', 'minor_version', ] struct_anon_94._fields_ = [ ('present', c_int), ('major_version', c_short), ('minor_version', c_short), ] XExtensionVersion = struct_anon_94 # /usr/include/X11/extensions/XI.h:285 _deviceKeyPress = 0 # /usr/include/X11/extensions/XInput.h:4897 _deviceKeyRelease = 1 # /usr/include/X11/extensions/XInput.h:4898 _deviceButtonPress = 0 # /usr/include/X11/extensions/XInput.h:4900 _deviceButtonRelease = 1 # /usr/include/X11/extensions/XInput.h:4901 _deviceMotionNotify = 0 # /usr/include/X11/extensions/XInput.h:4903 _deviceFocusIn = 0 # /usr/include/X11/extensions/XInput.h:4905 _deviceFocusOut = 1 # /usr/include/X11/extensions/XInput.h:4906 _proximityIn = 0 # /usr/include/X11/extensions/XInput.h:4908 _proximityOut = 1 # /usr/include/X11/extensions/XInput.h:4909 _deviceStateNotify = 0 # /usr/include/X11/extensions/XInput.h:4911 _deviceMappingNotify = 1 # /usr/include/X11/extensions/XInput.h:4912 _changeDeviceNotify = 2 # /usr/include/X11/extensions/XInput.h:4913 class struct_anon_95(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'state', 'keycode', 'same_screen', 'device_state', 'axes_count', 'first_axis', 'axis_data', ] Display = pyglet.window.xlib.xlib.Display Window = pyglet.window.xlib.xlib.Window XID = pyglet.window.xlib.xlib.XID Time = pyglet.window.xlib.xlib.Time struct_anon_95._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('deviceid', XID), ('root', Window), ('subwindow', Window), ('time', Time), ('x', c_int), ('y', c_int), ('x_root', c_int), ('y_root', c_int), ('state', c_uint), ('keycode', c_uint), ('same_screen', c_int), ('device_state', c_uint), ('axes_count', c_ubyte), ('first_axis', c_ubyte), ('axis_data', c_int * 6), ] XDeviceKeyEvent = struct_anon_95 # /usr/include/X11/extensions/XInput.h:5038 XDeviceKeyPressedEvent = XDeviceKeyEvent # /usr/include/X11/extensions/XInput.h:5040 XDeviceKeyReleasedEvent = XDeviceKeyEvent # /usr/include/X11/extensions/XInput.h:5041 class struct_anon_96(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'state', 'button', 'same_screen', 'device_state', 'axes_count', 'first_axis', 'axis_data', ] struct_anon_96._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('deviceid', XID), ('root', Window), ('subwindow', Window), ('time', Time), ('x', c_int), ('y', c_int), ('x_root', c_int), ('y_root', c_int), ('state', c_uint), ('button', c_uint), ('same_screen', c_int), ('device_state', c_uint), ('axes_count', c_ubyte), ('first_axis', c_ubyte), ('axis_data', c_int * 6), ] XDeviceButtonEvent = struct_anon_96 # /usr/include/X11/extensions/XInput.h:5070 XDeviceButtonPressedEvent = XDeviceButtonEvent # /usr/include/X11/extensions/XInput.h:5072 XDeviceButtonReleasedEvent = XDeviceButtonEvent # /usr/include/X11/extensions/XInput.h:5073 class struct_anon_97(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'state', 'is_hint', 'same_screen', 'device_state', 'axes_count', 'first_axis', 'axis_data', ] struct_anon_97._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('deviceid', XID), ('root', Window), ('subwindow', Window), ('time', Time), ('x', c_int), ('y', c_int), ('x_root', c_int), ('y_root', c_int), ('state', c_uint), ('is_hint', c_char), ('same_screen', c_int), ('device_state', c_uint), ('axes_count', c_ubyte), ('first_axis', c_ubyte), ('axis_data', c_int * 6), ] XDeviceMotionEvent = struct_anon_97 # /usr/include/X11/extensions/XInput.h:5103 class struct_anon_98(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'mode', 'detail', 'time', ] struct_anon_98._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('deviceid', XID), ('mode', c_int), ('detail', c_int), ('time', Time), ] XDeviceFocusChangeEvent = struct_anon_98 # /usr/include/X11/extensions/XInput.h:5128 XDeviceFocusInEvent = XDeviceFocusChangeEvent # /usr/include/X11/extensions/XInput.h:5130 XDeviceFocusOutEvent = XDeviceFocusChangeEvent # /usr/include/X11/extensions/XInput.h:5131 class struct_anon_99(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'state', 'same_screen', 'device_state', 'axes_count', 'first_axis', 'axis_data', ] struct_anon_99._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('deviceid', XID), ('root', Window), ('subwindow', Window), ('time', Time), ('x', c_int), ('y', c_int), ('x_root', c_int), ('y_root', c_int), ('state', c_uint), ('same_screen', c_int), ('device_state', c_uint), ('axes_count', c_ubyte), ('first_axis', c_ubyte), ('axis_data', c_int * 6), ] XProximityNotifyEvent = struct_anon_99 # /usr/include/X11/extensions/XInput.h:5159 XProximityInEvent = XProximityNotifyEvent # /usr/include/X11/extensions/XInput.h:5160 XProximityOutEvent = XProximityNotifyEvent # /usr/include/X11/extensions/XInput.h:5161 class struct_anon_100(Structure): __slots__ = [ 'class', 'length', ] struct_anon_100._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ] XInputClass = struct_anon_100 # /usr/include/X11/extensions/XInput.h:5178 class struct_anon_101(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'time', 'num_classes', 'data', ] struct_anon_101._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('deviceid', XID), ('time', Time), ('num_classes', c_int), ('data', c_char * 64), ] XDeviceStateNotifyEvent = struct_anon_101 # /usr/include/X11/extensions/XInput.h:5190 class struct_anon_102(Structure): __slots__ = [ 'class', 'length', 'num_valuators', 'mode', 'valuators', ] struct_anon_102._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_valuators', c_ubyte), ('mode', c_ubyte), ('valuators', c_int * 6), ] XValuatorStatus = struct_anon_102 # /usr/include/X11/extensions/XInput.h:5202 class struct_anon_103(Structure): __slots__ = [ 'class', 'length', 'num_keys', 'keys', ] struct_anon_103._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_keys', c_short), ('keys', c_char * 32), ] XKeyStatus = struct_anon_103 # /usr/include/X11/extensions/XInput.h:5213 class struct_anon_104(Structure): __slots__ = [ 'class', 'length', 'num_buttons', 'buttons', ] struct_anon_104._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_buttons', c_short), ('buttons', c_char * 32), ] XButtonStatus = struct_anon_104 # /usr/include/X11/extensions/XInput.h:5224 class struct_anon_105(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'time', 'request', 'first_keycode', 'count', ] struct_anon_105._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('deviceid', XID), ('time', Time), ('request', c_int), ('first_keycode', c_int), ('count', c_int), ] XDeviceMappingEvent = struct_anon_105 # /usr/include/X11/extensions/XInput.h:5245 class struct_anon_106(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'time', 'request', ] struct_anon_106._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('deviceid', XID), ('time', Time), ('request', c_int), ] XChangeDeviceNotifyEvent = struct_anon_106 # /usr/include/X11/extensions/XInput.h:5263 class struct_anon_107(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'time', 'devchange', 'deviceid', 'control', ] struct_anon_107._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('time', Time), ('devchange', c_int), ('deviceid', XID), ('control', XID), ] XDevicePresenceNotifyEvent = struct_anon_107 # /usr/include/X11/extensions/XInput.h:5288 class struct_anon_108(Structure): __slots__ = [ 'class', 'length', 'id', ] struct_anon_108._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ] XFeedbackState = struct_anon_108 # /usr/include/X11/extensions/XInput.h:5306 class struct_anon_109(Structure): __slots__ = [ 'class', 'length', 'id', 'click', 'percent', 'pitch', 'duration', 'led_mask', 'global_auto_repeat', 'auto_repeats', ] struct_anon_109._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('click', c_int), ('percent', c_int), ('pitch', c_int), ('duration', c_int), ('led_mask', c_int), ('global_auto_repeat', c_int), ('auto_repeats', c_char * 32), ] XKbdFeedbackState = struct_anon_109 # /usr/include/X11/extensions/XInput.h:5323 class struct_anon_110(Structure): __slots__ = [ 'class', 'length', 'id', 'accelNum', 'accelDenom', 'threshold', ] struct_anon_110._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('accelNum', c_int), ('accelDenom', c_int), ('threshold', c_int), ] XPtrFeedbackState = struct_anon_110 # /usr/include/X11/extensions/XInput.h:5336 class struct_anon_111(Structure): __slots__ = [ 'class', 'length', 'id', 'resolution', 'minVal', 'maxVal', ] struct_anon_111._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('resolution', c_int), ('minVal', c_int), ('maxVal', c_int), ] XIntegerFeedbackState = struct_anon_111 # /usr/include/X11/extensions/XInput.h:5349 class struct_anon_112(Structure): __slots__ = [ 'class', 'length', 'id', 'max_symbols', 'num_syms_supported', 'syms_supported', ] KeySym = pyglet.window.xlib.xlib.KeySym struct_anon_112._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('max_symbols', c_int), ('num_syms_supported', c_int), ('syms_supported', POINTER(KeySym)), ] XStringFeedbackState = struct_anon_112 # /usr/include/X11/extensions/XInput.h:5362 class struct_anon_113(Structure): __slots__ = [ 'class', 'length', 'id', 'percent', 'pitch', 'duration', ] struct_anon_113._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('percent', c_int), ('pitch', c_int), ('duration', c_int), ] XBellFeedbackState = struct_anon_113 # /usr/include/X11/extensions/XInput.h:5375 class struct_anon_114(Structure): __slots__ = [ 'class', 'length', 'id', 'led_values', 'led_mask', ] struct_anon_114._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('led_values', c_int), ('led_mask', c_int), ] XLedFeedbackState = struct_anon_114 # /usr/include/X11/extensions/XInput.h:5387 class struct_anon_115(Structure): __slots__ = [ 'class', 'length', 'id', ] struct_anon_115._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ] XFeedbackControl = struct_anon_115 # /usr/include/X11/extensions/XInput.h:5397 class struct_anon_116(Structure): __slots__ = [ 'class', 'length', 'id', 'accelNum', 'accelDenom', 'threshold', ] struct_anon_116._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('accelNum', c_int), ('accelDenom', c_int), ('threshold', c_int), ] XPtrFeedbackControl = struct_anon_116 # /usr/include/X11/extensions/XInput.h:5410 class struct_anon_117(Structure): __slots__ = [ 'class', 'length', 'id', 'click', 'percent', 'pitch', 'duration', 'led_mask', 'led_value', 'key', 'auto_repeat_mode', ] struct_anon_117._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('click', c_int), ('percent', c_int), ('pitch', c_int), ('duration', c_int), ('led_mask', c_int), ('led_value', c_int), ('key', c_int), ('auto_repeat_mode', c_int), ] XKbdFeedbackControl = struct_anon_117 # /usr/include/X11/extensions/XInput.h:5428 class struct_anon_118(Structure): __slots__ = [ 'class', 'length', 'id', 'num_keysyms', 'syms_to_display', ] struct_anon_118._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('num_keysyms', c_int), ('syms_to_display', POINTER(KeySym)), ] XStringFeedbackControl = struct_anon_118 # /usr/include/X11/extensions/XInput.h:5440 class struct_anon_119(Structure): __slots__ = [ 'class', 'length', 'id', 'int_to_display', ] struct_anon_119._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('int_to_display', c_int), ] XIntegerFeedbackControl = struct_anon_119 # /usr/include/X11/extensions/XInput.h:5451 class struct_anon_120(Structure): __slots__ = [ 'class', 'length', 'id', 'percent', 'pitch', 'duration', ] struct_anon_120._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('percent', c_int), ('pitch', c_int), ('duration', c_int), ] XBellFeedbackControl = struct_anon_120 # /usr/include/X11/extensions/XInput.h:5464 class struct_anon_121(Structure): __slots__ = [ 'class', 'length', 'id', 'led_mask', 'led_values', ] struct_anon_121._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('led_mask', c_int), ('led_values', c_int), ] XLedFeedbackControl = struct_anon_121 # /usr/include/X11/extensions/XInput.h:5476 class struct_anon_122(Structure): __slots__ = [ 'control', 'length', ] struct_anon_122._fields_ = [ ('control', XID), ('length', c_int), ] XDeviceControl = struct_anon_122 # /usr/include/X11/extensions/XInput.h:5487 class struct_anon_123(Structure): __slots__ = [ 'control', 'length', 'first_valuator', 'num_valuators', 'resolutions', ] struct_anon_123._fields_ = [ ('control', XID), ('length', c_int), ('first_valuator', c_int), ('num_valuators', c_int), ('resolutions', POINTER(c_int)), ] XDeviceResolutionControl = struct_anon_123 # /usr/include/X11/extensions/XInput.h:5495 class struct_anon_124(Structure): __slots__ = [ 'control', 'length', 'num_valuators', 'resolutions', 'min_resolutions', 'max_resolutions', ] struct_anon_124._fields_ = [ ('control', XID), ('length', c_int), ('num_valuators', c_int), ('resolutions', POINTER(c_int)), ('min_resolutions', POINTER(c_int)), ('max_resolutions', POINTER(c_int)), ] XDeviceResolutionState = struct_anon_124 # /usr/include/X11/extensions/XInput.h:5504 class struct_anon_125(Structure): __slots__ = [ 'control', 'length', 'min_x', 'max_x', 'min_y', 'max_y', 'flip_x', 'flip_y', 'rotation', 'button_threshold', ] struct_anon_125._fields_ = [ ('control', XID), ('length', c_int), ('min_x', c_int), ('max_x', c_int), ('min_y', c_int), ('max_y', c_int), ('flip_x', c_int), ('flip_y', c_int), ('rotation', c_int), ('button_threshold', c_int), ] XDeviceAbsCalibControl = struct_anon_125 # /usr/include/X11/extensions/XInput.h:5517 class struct_anon_126(Structure): __slots__ = [ 'control', 'length', 'min_x', 'max_x', 'min_y', 'max_y', 'flip_x', 'flip_y', 'rotation', 'button_threshold', ] struct_anon_126._fields_ = [ ('control', XID), ('length', c_int), ('min_x', c_int), ('max_x', c_int), ('min_y', c_int), ('max_y', c_int), ('flip_x', c_int), ('flip_y', c_int), ('rotation', c_int), ('button_threshold', c_int), ] XDeviceAbsCalibState = struct_anon_126 # /usr/include/X11/extensions/XInput.h:5517 class struct_anon_127(Structure): __slots__ = [ 'control', 'length', 'offset_x', 'offset_y', 'width', 'height', 'screen', 'following', ] struct_anon_127._fields_ = [ ('control', XID), ('length', c_int), ('offset_x', c_int), ('offset_y', c_int), ('width', c_int), ('height', c_int), ('screen', c_int), ('following', XID), ] XDeviceAbsAreaControl = struct_anon_127 # /usr/include/X11/extensions/XInput.h:5528 class struct_anon_128(Structure): __slots__ = [ 'control', 'length', 'offset_x', 'offset_y', 'width', 'height', 'screen', 'following', ] struct_anon_128._fields_ = [ ('control', XID), ('length', c_int), ('offset_x', c_int), ('offset_y', c_int), ('width', c_int), ('height', c_int), ('screen', c_int), ('following', XID), ] XDeviceAbsAreaState = struct_anon_128 # /usr/include/X11/extensions/XInput.h:5528 class struct_anon_129(Structure): __slots__ = [ 'control', 'length', 'status', ] struct_anon_129._fields_ = [ ('control', XID), ('length', c_int), ('status', c_int), ] XDeviceCoreControl = struct_anon_129 # /usr/include/X11/extensions/XInput.h:5534 class struct_anon_130(Structure): __slots__ = [ 'control', 'length', 'status', 'iscore', ] struct_anon_130._fields_ = [ ('control', XID), ('length', c_int), ('status', c_int), ('iscore', c_int), ] XDeviceCoreState = struct_anon_130 # /usr/include/X11/extensions/XInput.h:5541 class struct_anon_131(Structure): __slots__ = [ 'control', 'length', 'enable', ] struct_anon_131._fields_ = [ ('control', XID), ('length', c_int), ('enable', c_int), ] XDeviceEnableControl = struct_anon_131 # /usr/include/X11/extensions/XInput.h:5547 class struct_anon_132(Structure): __slots__ = [ 'control', 'length', 'enable', ] struct_anon_132._fields_ = [ ('control', XID), ('length', c_int), ('enable', c_int), ] XDeviceEnableState = struct_anon_132 # /usr/include/X11/extensions/XInput.h:5547 class struct__XAnyClassinfo(Structure): __slots__ = [ ] struct__XAnyClassinfo._fields_ = [ ('_opaque_struct', c_int) ] class struct__XAnyClassinfo(Structure): __slots__ = [ ] struct__XAnyClassinfo._fields_ = [ ('_opaque_struct', c_int) ] XAnyClassPtr = POINTER(struct__XAnyClassinfo) # /usr/include/X11/extensions/XInput.h:5559 class struct__XAnyClassinfo(Structure): __slots__ = [ 'class', 'length', ] struct__XAnyClassinfo._fields_ = [ ('class', XID), ('length', c_int), ] XAnyClassInfo = struct__XAnyClassinfo # /usr/include/X11/extensions/XInput.h:5568 class struct__XDeviceInfo(Structure): __slots__ = [ ] struct__XDeviceInfo._fields_ = [ ('_opaque_struct', c_int) ] class struct__XDeviceInfo(Structure): __slots__ = [ ] struct__XDeviceInfo._fields_ = [ ('_opaque_struct', c_int) ] XDeviceInfoPtr = POINTER(struct__XDeviceInfo) # /usr/include/X11/extensions/XInput.h:5570 class struct__XDeviceInfo(Structure): __slots__ = [ 'id', 'type', 'name', 'num_classes', 'use', 'inputclassinfo', ] Atom = pyglet.window.xlib.xlib.Atom struct__XDeviceInfo._fields_ = [ ('id', XID), ('type', Atom), ('name', c_char_p), ('num_classes', c_int), ('use', c_int), ('inputclassinfo', XAnyClassPtr), ] XDeviceInfo = struct__XDeviceInfo # /usr/include/X11/extensions/XInput.h:5580 class struct__XKeyInfo(Structure): __slots__ = [ ] struct__XKeyInfo._fields_ = [ ('_opaque_struct', c_int) ] class struct__XKeyInfo(Structure): __slots__ = [ ] struct__XKeyInfo._fields_ = [ ('_opaque_struct', c_int) ] XKeyInfoPtr = POINTER(struct__XKeyInfo) # /usr/include/X11/extensions/XInput.h:5582 class struct__XKeyInfo(Structure): __slots__ = [ 'class', 'length', 'min_keycode', 'max_keycode', 'num_keys', ] struct__XKeyInfo._fields_ = [ ('class', XID), ('length', c_int), ('min_keycode', c_ushort), ('max_keycode', c_ushort), ('num_keys', c_ushort), ] XKeyInfo = struct__XKeyInfo # /usr/include/X11/extensions/XInput.h:5595 class struct__XButtonInfo(Structure): __slots__ = [ ] struct__XButtonInfo._fields_ = [ ('_opaque_struct', c_int) ] class struct__XButtonInfo(Structure): __slots__ = [ ] struct__XButtonInfo._fields_ = [ ('_opaque_struct', c_int) ] XButtonInfoPtr = POINTER(struct__XButtonInfo) # /usr/include/X11/extensions/XInput.h:5597 class struct__XButtonInfo(Structure): __slots__ = [ 'class', 'length', 'num_buttons', ] struct__XButtonInfo._fields_ = [ ('class', XID), ('length', c_int), ('num_buttons', c_short), ] XButtonInfo = struct__XButtonInfo # /usr/include/X11/extensions/XInput.h:5607 class struct__XAxisInfo(Structure): __slots__ = [ ] struct__XAxisInfo._fields_ = [ ('_opaque_struct', c_int) ] class struct__XAxisInfo(Structure): __slots__ = [ ] struct__XAxisInfo._fields_ = [ ('_opaque_struct', c_int) ] XAxisInfoPtr = POINTER(struct__XAxisInfo) # /usr/include/X11/extensions/XInput.h:5609 class struct__XAxisInfo(Structure): __slots__ = [ 'resolution', 'min_value', 'max_value', ] struct__XAxisInfo._fields_ = [ ('resolution', c_int), ('min_value', c_int), ('max_value', c_int), ] XAxisInfo = struct__XAxisInfo # /usr/include/X11/extensions/XInput.h:5615 class struct__XValuatorInfo(Structure): __slots__ = [ ] struct__XValuatorInfo._fields_ = [ ('_opaque_struct', c_int) ] class struct__XValuatorInfo(Structure): __slots__ = [ ] struct__XValuatorInfo._fields_ = [ ('_opaque_struct', c_int) ] XValuatorInfoPtr = POINTER(struct__XValuatorInfo) # /usr/include/X11/extensions/XInput.h:5617 class struct__XValuatorInfo(Structure): __slots__ = [ 'class', 'length', 'num_axes', 'mode', 'motion_buffer', 'axes', ] struct__XValuatorInfo._fields_ = [ ('class', XID), ('length', c_int), ('num_axes', c_ubyte), ('mode', c_ubyte), ('motion_buffer', c_ulong), ('axes', XAxisInfoPtr), ] XValuatorInfo = struct__XValuatorInfo # /usr/include/X11/extensions/XInput.h:5631 class struct_anon_133(Structure): __slots__ = [ 'input_class', 'event_type_base', ] struct_anon_133._fields_ = [ ('input_class', c_ubyte), ('event_type_base', c_ubyte), ] XInputClassInfo = struct_anon_133 # /usr/include/X11/extensions/XInput.h:5648 class struct_anon_134(Structure): __slots__ = [ 'device_id', 'num_classes', 'classes', ] struct_anon_134._fields_ = [ ('device_id', XID), ('num_classes', c_int), ('classes', POINTER(XInputClassInfo)), ] XDevice = struct_anon_134 # /usr/include/X11/extensions/XInput.h:5654 class struct_anon_135(Structure): __slots__ = [ 'event_type', 'device', ] struct_anon_135._fields_ = [ ('event_type', XEventClass), ('device', XID), ] XEventList = struct_anon_135 # /usr/include/X11/extensions/XInput.h:5667 class struct_anon_136(Structure): __slots__ = [ 'time', 'data', ] struct_anon_136._fields_ = [ ('time', Time), ('data', POINTER(c_int)), ] XDeviceTimeCoord = struct_anon_136 # /usr/include/X11/extensions/XInput.h:5680 class struct_anon_137(Structure): __slots__ = [ 'device_id', 'num_classes', 'data', ] struct_anon_137._fields_ = [ ('device_id', XID), ('num_classes', c_int), ('data', POINTER(XInputClass)), ] XDeviceState = struct_anon_137 # /usr/include/X11/extensions/XInput.h:5694 class struct_anon_138(Structure): __slots__ = [ 'class', 'length', 'num_valuators', 'mode', 'valuators', ] struct_anon_138._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_valuators', c_ubyte), ('mode', c_ubyte), ('valuators', POINTER(c_int)), ] XValuatorState = struct_anon_138 # /usr/include/X11/extensions/XInput.h:5717 class struct_anon_139(Structure): __slots__ = [ 'class', 'length', 'num_keys', 'keys', ] struct_anon_139._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_keys', c_short), ('keys', c_char * 32), ] XKeyState = struct_anon_139 # /usr/include/X11/extensions/XInput.h:5728 class struct_anon_140(Structure): __slots__ = [ 'class', 'length', 'num_buttons', 'buttons', ] struct_anon_140._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_buttons', c_short), ('buttons', c_char * 32), ] XButtonState = struct_anon_140 # /usr/include/X11/extensions/XInput.h:5739 # /usr/include/X11/extensions/XInput.h:5749 XChangeKeyboardDevice = _lib.XChangeKeyboardDevice XChangeKeyboardDevice.restype = c_int XChangeKeyboardDevice.argtypes = [POINTER(Display), POINTER(XDevice)] # /usr/include/X11/extensions/XInput.h:5754 XChangePointerDevice = _lib.XChangePointerDevice XChangePointerDevice.restype = c_int XChangePointerDevice.argtypes = [POINTER(Display), POINTER(XDevice), c_int, c_int] # /usr/include/X11/extensions/XInput.h:5761 XGrabDevice = _lib.XGrabDevice XGrabDevice.restype = c_int XGrabDevice.argtypes = [POINTER(Display), POINTER(XDevice), Window, c_int, c_int, POINTER(XEventClass), c_int, c_int, Time] # /usr/include/X11/extensions/XInput.h:5773 XUngrabDevice = _lib.XUngrabDevice XUngrabDevice.restype = c_int XUngrabDevice.argtypes = [POINTER(Display), POINTER(XDevice), Time] # /usr/include/X11/extensions/XInput.h:5779 XGrabDeviceKey = _lib.XGrabDeviceKey XGrabDeviceKey.restype = c_int XGrabDeviceKey.argtypes = [POINTER(Display), POINTER(XDevice), c_uint, c_uint, POINTER(XDevice), Window, c_int, c_uint, POINTER(XEventClass), c_int, c_int] # /usr/include/X11/extensions/XInput.h:5793 XUngrabDeviceKey = _lib.XUngrabDeviceKey XUngrabDeviceKey.restype = c_int XUngrabDeviceKey.argtypes = [POINTER(Display), POINTER(XDevice), c_uint, c_uint, POINTER(XDevice), Window] # /usr/include/X11/extensions/XInput.h:5802 XGrabDeviceButton = _lib.XGrabDeviceButton XGrabDeviceButton.restype = c_int XGrabDeviceButton.argtypes = [POINTER(Display), POINTER(XDevice), c_uint, c_uint, POINTER(XDevice), Window, c_int, c_uint, POINTER(XEventClass), c_int, c_int] # /usr/include/X11/extensions/XInput.h:5816 XUngrabDeviceButton = _lib.XUngrabDeviceButton XUngrabDeviceButton.restype = c_int XUngrabDeviceButton.argtypes = [POINTER(Display), POINTER(XDevice), c_uint, c_uint, POINTER(XDevice), Window] # /usr/include/X11/extensions/XInput.h:5825 XAllowDeviceEvents = _lib.XAllowDeviceEvents XAllowDeviceEvents.restype = c_int XAllowDeviceEvents.argtypes = [POINTER(Display), POINTER(XDevice), c_int, Time] # /usr/include/X11/extensions/XInput.h:5832 XGetDeviceFocus = _lib.XGetDeviceFocus XGetDeviceFocus.restype = c_int XGetDeviceFocus.argtypes = [POINTER(Display), POINTER(XDevice), POINTER(Window), POINTER(c_int), POINTER(Time)] # /usr/include/X11/extensions/XInput.h:5840 XSetDeviceFocus = _lib.XSetDeviceFocus XSetDeviceFocus.restype = c_int XSetDeviceFocus.argtypes = [POINTER(Display), POINTER(XDevice), Window, c_int, Time] # /usr/include/X11/extensions/XInput.h:5848 XGetFeedbackControl = _lib.XGetFeedbackControl XGetFeedbackControl.restype = POINTER(XFeedbackState) XGetFeedbackControl.argtypes = [POINTER(Display), POINTER(XDevice), POINTER(c_int)] # /usr/include/X11/extensions/XInput.h:5854 XFreeFeedbackList = _lib.XFreeFeedbackList XFreeFeedbackList.restype = None XFreeFeedbackList.argtypes = [POINTER(XFeedbackState)] # /usr/include/X11/extensions/XInput.h:5858 XChangeFeedbackControl = _lib.XChangeFeedbackControl XChangeFeedbackControl.restype = c_int XChangeFeedbackControl.argtypes = [POINTER(Display), POINTER(XDevice), c_ulong, POINTER(XFeedbackControl)] # /usr/include/X11/extensions/XInput.h:5865 XDeviceBell = _lib.XDeviceBell XDeviceBell.restype = c_int XDeviceBell.argtypes = [POINTER(Display), POINTER(XDevice), XID, XID, c_int] KeyCode = pyglet.window.xlib.xlib.KeyCode # /usr/include/X11/extensions/XInput.h:5873 XGetDeviceKeyMapping = _lib.XGetDeviceKeyMapping XGetDeviceKeyMapping.restype = POINTER(KeySym) XGetDeviceKeyMapping.argtypes = [POINTER(Display), POINTER(XDevice), KeyCode, c_int, POINTER(c_int)] # /usr/include/X11/extensions/XInput.h:5885 XChangeDeviceKeyMapping = _lib.XChangeDeviceKeyMapping XChangeDeviceKeyMapping.restype = c_int XChangeDeviceKeyMapping.argtypes = [POINTER(Display), POINTER(XDevice), c_int, c_int, POINTER(KeySym), c_int] XModifierKeymap = pyglet.window.xlib.xlib.XModifierKeymap # /usr/include/X11/extensions/XInput.h:5894 XGetDeviceModifierMapping = _lib.XGetDeviceModifierMapping XGetDeviceModifierMapping.restype = POINTER(XModifierKeymap) XGetDeviceModifierMapping.argtypes = [POINTER(Display), POINTER(XDevice)] # /usr/include/X11/extensions/XInput.h:5899 XSetDeviceModifierMapping = _lib.XSetDeviceModifierMapping XSetDeviceModifierMapping.restype = c_int XSetDeviceModifierMapping.argtypes = [POINTER(Display), POINTER(XDevice), POINTER(XModifierKeymap)] # /usr/include/X11/extensions/XInput.h:5905 XSetDeviceButtonMapping = _lib.XSetDeviceButtonMapping XSetDeviceButtonMapping.restype = c_int XSetDeviceButtonMapping.argtypes = [POINTER(Display), POINTER(XDevice), POINTER(c_ubyte), c_int] # /usr/include/X11/extensions/XInput.h:5912 XGetDeviceButtonMapping = _lib.XGetDeviceButtonMapping XGetDeviceButtonMapping.restype = c_int XGetDeviceButtonMapping.argtypes = [POINTER(Display), POINTER(XDevice), POINTER(c_ubyte), c_uint] # /usr/include/X11/extensions/XInput.h:5919 XQueryDeviceState = _lib.XQueryDeviceState XQueryDeviceState.restype = POINTER(XDeviceState) XQueryDeviceState.argtypes = [POINTER(Display), POINTER(XDevice)] # /usr/include/X11/extensions/XInput.h:5924 XFreeDeviceState = _lib.XFreeDeviceState XFreeDeviceState.restype = None XFreeDeviceState.argtypes = [POINTER(XDeviceState)] # /usr/include/X11/extensions/XInput.h:5928 XGetExtensionVersion = _lib.XGetExtensionVersion XGetExtensionVersion.restype = POINTER(XExtensionVersion) XGetExtensionVersion.argtypes = [POINTER(Display), c_char_p] # /usr/include/X11/extensions/XInput.h:5933 XListInputDevices = _lib.XListInputDevices XListInputDevices.restype = POINTER(XDeviceInfo) XListInputDevices.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/extensions/XInput.h:5938 XFreeDeviceList = _lib.XFreeDeviceList XFreeDeviceList.restype = None XFreeDeviceList.argtypes = [POINTER(XDeviceInfo)] # /usr/include/X11/extensions/XInput.h:5942 XOpenDevice = _lib.XOpenDevice XOpenDevice.restype = POINTER(XDevice) XOpenDevice.argtypes = [POINTER(Display), XID] # /usr/include/X11/extensions/XInput.h:5947 XCloseDevice = _lib.XCloseDevice XCloseDevice.restype = c_int XCloseDevice.argtypes = [POINTER(Display), POINTER(XDevice)] # /usr/include/X11/extensions/XInput.h:5952 XSetDeviceMode = _lib.XSetDeviceMode XSetDeviceMode.restype = c_int XSetDeviceMode.argtypes = [POINTER(Display), POINTER(XDevice), c_int] # /usr/include/X11/extensions/XInput.h:5958 XSetDeviceValuators = _lib.XSetDeviceValuators XSetDeviceValuators.restype = c_int XSetDeviceValuators.argtypes = [POINTER(Display), POINTER(XDevice), POINTER(c_int), c_int, c_int] # /usr/include/X11/extensions/XInput.h:5966 XGetDeviceControl = _lib.XGetDeviceControl XGetDeviceControl.restype = POINTER(XDeviceControl) XGetDeviceControl.argtypes = [POINTER(Display), POINTER(XDevice), c_int] # /usr/include/X11/extensions/XInput.h:5972 XChangeDeviceControl = _lib.XChangeDeviceControl XChangeDeviceControl.restype = c_int XChangeDeviceControl.argtypes = [POINTER(Display), POINTER(XDevice), c_int, POINTER(XDeviceControl)] # /usr/include/X11/extensions/XInput.h:5979 XSelectExtensionEvent = _lib.XSelectExtensionEvent XSelectExtensionEvent.restype = c_int XSelectExtensionEvent.argtypes = [POINTER(Display), Window, POINTER(XEventClass), c_int] # /usr/include/X11/extensions/XInput.h:5986 XGetSelectedExtensionEvents = _lib.XGetSelectedExtensionEvents XGetSelectedExtensionEvents.restype = c_int XGetSelectedExtensionEvents.argtypes = [POINTER(Display), Window, POINTER(c_int), POINTER(POINTER(XEventClass)), POINTER(c_int), POINTER(POINTER(XEventClass))] # /usr/include/X11/extensions/XInput.h:5995 XChangeDeviceDontPropagateList = _lib.XChangeDeviceDontPropagateList XChangeDeviceDontPropagateList.restype = c_int XChangeDeviceDontPropagateList.argtypes = [POINTER(Display), Window, c_int, POINTER(XEventClass), c_int] # /usr/include/X11/extensions/XInput.h:6003 XGetDeviceDontPropagateList = _lib.XGetDeviceDontPropagateList XGetDeviceDontPropagateList.restype = POINTER(XEventClass) XGetDeviceDontPropagateList.argtypes = [POINTER(Display), Window, POINTER(c_int)] XEvent = pyglet.window.xlib.xlib.XEvent # /usr/include/X11/extensions/XInput.h:6009 XSendExtensionEvent = _lib.XSendExtensionEvent XSendExtensionEvent.restype = c_int XSendExtensionEvent.argtypes = [POINTER(Display), POINTER(XDevice), Window, c_int, c_int, POINTER(XEventClass), POINTER(XEvent)] # /usr/include/X11/extensions/XInput.h:6019 XGetDeviceMotionEvents = _lib.XGetDeviceMotionEvents XGetDeviceMotionEvents.restype = POINTER(XDeviceTimeCoord) XGetDeviceMotionEvents.argtypes = [POINTER(Display), POINTER(XDevice), Time, Time, POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/extensions/XInput.h:6029 XFreeDeviceMotionEvents = _lib.XFreeDeviceMotionEvents XFreeDeviceMotionEvents.restype = None XFreeDeviceMotionEvents.argtypes = [POINTER(XDeviceTimeCoord)] # /usr/include/X11/extensions/XInput.h:6033 XFreeDeviceControl = _lib.XFreeDeviceControl XFreeDeviceControl.restype = None XFreeDeviceControl.argtypes = [POINTER(XDeviceControl)] __all__ = ['sz_xGetExtensionVersionReq', 'sz_xGetExtensionVersionReply', 'sz_xListInputDevicesReq', 'sz_xListInputDevicesReply', 'sz_xOpenDeviceReq', 'sz_xOpenDeviceReply', 'sz_xCloseDeviceReq', 'sz_xSetDeviceModeReq', 'sz_xSetDeviceModeReply', 'sz_xSelectExtensionEventReq', 'sz_xGetSelectedExtensionEventsReq', 'sz_xGetSelectedExtensionEventsReply', 'sz_xChangeDeviceDontPropagateListReq', 'sz_xGetDeviceDontPropagateListReq', 'sz_xGetDeviceDontPropagateListReply', 'sz_xGetDeviceMotionEventsReq', 'sz_xGetDeviceMotionEventsReply', 'sz_xChangeKeyboardDeviceReq', 'sz_xChangeKeyboardDeviceReply', 'sz_xChangePointerDeviceReq', 'sz_xChangePointerDeviceReply', 'sz_xGrabDeviceReq', 'sz_xGrabDeviceReply', 'sz_xUngrabDeviceReq', 'sz_xGrabDeviceKeyReq', 'sz_xGrabDeviceKeyReply', 'sz_xUngrabDeviceKeyReq', 'sz_xGrabDeviceButtonReq', 'sz_xGrabDeviceButtonReply', 'sz_xUngrabDeviceButtonReq', 'sz_xAllowDeviceEventsReq', 'sz_xGetDeviceFocusReq', 'sz_xGetDeviceFocusReply', 'sz_xSetDeviceFocusReq', 'sz_xGetFeedbackControlReq', 'sz_xGetFeedbackControlReply', 'sz_xChangeFeedbackControlReq', 'sz_xGetDeviceKeyMappingReq', 'sz_xGetDeviceKeyMappingReply', 'sz_xChangeDeviceKeyMappingReq', 'sz_xGetDeviceModifierMappingReq', 'sz_xSetDeviceModifierMappingReq', 'sz_xSetDeviceModifierMappingReply', 'sz_xGetDeviceButtonMappingReq', 'sz_xGetDeviceButtonMappingReply', 'sz_xSetDeviceButtonMappingReq', 'sz_xSetDeviceButtonMappingReply', 'sz_xQueryDeviceStateReq', 'sz_xQueryDeviceStateReply', 'sz_xSendExtensionEventReq', 'sz_xDeviceBellReq', 'sz_xSetDeviceValuatorsReq', 'sz_xSetDeviceValuatorsReply', 'sz_xGetDeviceControlReq', 'sz_xGetDeviceControlReply', 'sz_xChangeDeviceControlReq', 'sz_xChangeDeviceControlReply', 'Dont_Check', 'XInput_Initial_Release', 'XInput_Add_XDeviceBell', 'XInput_Add_XSetDeviceValuators', 'XInput_Add_XChangeDeviceControl', 'XInput_Add_DevicePresenceNotify', 'XI_Absent', 'XI_Present', 'XI_Initial_Release_Major', 'XI_Initial_Release_Minor', 'XI_Add_XDeviceBell_Major', 'XI_Add_XDeviceBell_Minor', 'XI_Add_XSetDeviceValuators_Major', 'XI_Add_XSetDeviceValuators_Minor', 'XI_Add_XChangeDeviceControl_Major', 'XI_Add_XChangeDeviceControl_Minor', 'XI_Add_DevicePresenceNotify_Major', 'XI_Add_DevicePresenceNotify_Minor', 'DEVICE_RESOLUTION', 'DEVICE_ABS_CALIB', 'DEVICE_CORE', 'DEVICE_ENABLE', 'DEVICE_ABS_AREA', 'NoSuchExtension', 'COUNT', 'CREATE', 'NewPointer', 'NewKeyboard', 'XPOINTER', 'XKEYBOARD', 'UseXKeyboard', 'IsXPointer', 'IsXKeyboard', 'IsXExtensionDevice', 'IsXExtensionKeyboard', 'IsXExtensionPointer', 'AsyncThisDevice', 'SyncThisDevice', 'ReplayThisDevice', 'AsyncOtherDevices', 'AsyncAll', 'SyncAll', 'FollowKeyboard', 'RevertToFollowKeyboard', 'DvAccelNum', 'DvAccelDenom', 'DvThreshold', 'DvKeyClickPercent', 'DvPercent', 'DvPitch', 'DvDuration', 'DvLed', 'DvLedMode', 'DvKey', 'DvAutoRepeatMode', 'DvString', 'DvInteger', 'DeviceMode', 'Relative', 'Absolute', 'ProximityState', 'InProximity', 'OutOfProximity', 'AddToList', 'DeleteFromList', 'KeyClass', 'ButtonClass', 'ValuatorClass', 'FeedbackClass', 'ProximityClass', 'FocusClass', 'OtherClass', 'KbdFeedbackClass', 'PtrFeedbackClass', 'StringFeedbackClass', 'IntegerFeedbackClass', 'LedFeedbackClass', 'BellFeedbackClass', '_devicePointerMotionHint', '_deviceButton1Motion', '_deviceButton2Motion', '_deviceButton3Motion', '_deviceButton4Motion', '_deviceButton5Motion', '_deviceButtonMotion', '_deviceButtonGrab', '_deviceOwnerGrabButton', '_noExtensionEvent', '_devicePresence', 'DeviceAdded', 'DeviceRemoved', 'DeviceEnabled', 'DeviceDisabled', 'DeviceUnrecoverable', 'XI_BadDevice', 'XI_BadEvent', 'XI_BadMode', 'XI_DeviceBusy', 'XI_BadClass', 'XEventClass', 'XExtensionVersion', '_deviceKeyPress', '_deviceKeyRelease', '_deviceButtonPress', '_deviceButtonRelease', '_deviceMotionNotify', '_deviceFocusIn', '_deviceFocusOut', '_proximityIn', '_proximityOut', '_deviceStateNotify', '_deviceMappingNotify', '_changeDeviceNotify', 'XDeviceKeyEvent', 'XDeviceKeyPressedEvent', 'XDeviceKeyReleasedEvent', 'XDeviceButtonEvent', 'XDeviceButtonPressedEvent', 'XDeviceButtonReleasedEvent', 'XDeviceMotionEvent', 'XDeviceFocusChangeEvent', 'XDeviceFocusInEvent', 'XDeviceFocusOutEvent', 'XProximityNotifyEvent', 'XProximityInEvent', 'XProximityOutEvent', 'XInputClass', 'XDeviceStateNotifyEvent', 'XValuatorStatus', 'XKeyStatus', 'XButtonStatus', 'XDeviceMappingEvent', 'XChangeDeviceNotifyEvent', 'XDevicePresenceNotifyEvent', 'XFeedbackState', 'XKbdFeedbackState', 'XPtrFeedbackState', 'XIntegerFeedbackState', 'XStringFeedbackState', 'XBellFeedbackState', 'XLedFeedbackState', 'XFeedbackControl', 'XPtrFeedbackControl', 'XKbdFeedbackControl', 'XStringFeedbackControl', 'XIntegerFeedbackControl', 'XBellFeedbackControl', 'XLedFeedbackControl', 'XDeviceControl', 'XDeviceResolutionControl', 'XDeviceResolutionState', 'XDeviceAbsCalibControl', 'XDeviceAbsCalibState', 'XDeviceAbsAreaControl', 'XDeviceAbsAreaState', 'XDeviceCoreControl', 'XDeviceCoreState', 'XDeviceEnableControl', 'XDeviceEnableState', 'XAnyClassPtr', 'XAnyClassInfo', 'XDeviceInfoPtr', 'XDeviceInfo', 'XKeyInfoPtr', 'XKeyInfo', 'XButtonInfoPtr', 'XButtonInfo', 'XAxisInfoPtr', 'XAxisInfo', 'XValuatorInfoPtr', 'XValuatorInfo', 'XInputClassInfo', 'XDevice', 'XEventList', 'XDeviceTimeCoord', 'XDeviceState', 'XValuatorState', 'XKeyState', 'XButtonState', 'XChangeKeyboardDevice', 'XChangePointerDevice', 'XGrabDevice', 'XUngrabDevice', 'XGrabDeviceKey', 'XUngrabDeviceKey', 'XGrabDeviceButton', 'XUngrabDeviceButton', 'XAllowDeviceEvents', 'XGetDeviceFocus', 'XSetDeviceFocus', 'XGetFeedbackControl', 'XFreeFeedbackList', 'XChangeFeedbackControl', 'XDeviceBell', 'XGetDeviceKeyMapping', 'XChangeDeviceKeyMapping', 'XGetDeviceModifierMapping', 'XSetDeviceModifierMapping', 'XSetDeviceButtonMapping', 'XGetDeviceButtonMapping', 'XQueryDeviceState', 'XFreeDeviceState', 'XGetExtensionVersion', 'XListInputDevices', 'XFreeDeviceList', 'XOpenDevice', 'XCloseDevice', 'XSetDeviceMode', 'XSetDeviceValuators', 'XGetDeviceControl', 'XChangeDeviceControl', 'XSelectExtensionEvent', 'XGetSelectedExtensionEvents', 'XChangeDeviceDontPropagateList', 'XGetDeviceDontPropagateList', 'XSendExtensionEvent', 'XGetDeviceMotionEvents', 'XFreeDeviceMotionEvents', 'XFreeDeviceControl']
Python
#!/usr/bin/python # $Id:$ from docutils.core import publish_doctree from docutils import nodes import pyglet from pyglet.text.formats import structured class Stylesheet(object): default = dict( font_name='Times New Roman', font_size=12, margin_bottom=12) emphasis = dict( italic=True) strong = dict( bold=True) literal = dict( font_name='Courier New') literal_block = dict( font_name='Courier New', font_size=10, margin_left=20, ) def get_title(self, level): return { 0: dict( font_size=24, bold=True, align='center'), 1: dict( font_size=16, bold=True), 2: dict( font_size=14, bold=True), 3: dict( font_size=12, italic=True), }.get(level, {}) class Section(object): def __init__(self, level): self.level = level class DocutilsDecoder(structured.StructuredTextDecoder): def __init__(self, stylesheet=None): if not stylesheet: stylesheet = Stylesheet() self.stylesheet = stylesheet def decode_structured(self, text, location): self.location = location if isinstance(location, pyglet.resource.FileLocation): doctree = publish_doctree(text, source_path=location.path) else: doctree = publish_doctree(text) self.decode_doctree(doctree) def decode_doctree(self, doctree): self.push_style('_default', self.stylesheet.default) self.section_stack = [Section(0)] self.in_literal = False doctree.walkabout(DocutilsVisitor(doctree, self)) def visit_Text(self, node): text = node.astext() if self.in_literal: text = text.replace('\n', u'\u2028') self.add_text(text) def visit_unknown(self, node): pass def depart_unknown(self, node): pass # Structural elements def visit_title(self, node): level = self.section_stack[-1].level self.push_style(node, self.stylesheet.get_title(level)) def depart_title(self, node): self.add_text('\n') def visit_section(self, node): self.section_stack.append(Section(len(self.section_stack))) def depart_section(self, node): self.section_stack.pop() # Body elements def depart_paragraph(self, node): self.add_text('\n') def visit_literal_block(self, node): self.push_style(node, self.stylesheet.literal_block) self.in_literal = True def depart_literal_block(self, node): self.in_literal = False self.add_text('\n') # Inline elements def visit_emphasis(self, node): self.push_style(node, self.stylesheet.emphasis) def visit_strong(self, node): self.push_style(node, self.stylesheet.strong) def visit_literal(self, node): self.push_style(node, self.stylesheet.literal) def visit_superscript(self, node): self.push_style(node, self.stylesheet.superscript) def visit_subscript(self, node): self.push_style(node, self.stylesheet.subscript) class DocutilsVisitor(nodes.NodeVisitor): def __init__(self, document, decoder): nodes.NodeVisitor.__init__(self, document) self.decoder = decoder def dispatch_visit(self, node): node_name = node.__class__.__name__ method = getattr(self.decoder, 'visit_%s' % node_name, self.decoder.visit_unknown) method(node) def dispatch_departure(self, node): self.decoder.pop_style(node) node_name = node.__class__.__name__ method = getattr(self.decoder, 'depart_%s' % node_name, self.decoder.depart_unknown) method(node)
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' from timeit import Timer NUMBER=100000 setup=''' from pyglet.gl.VERSION_1_1 import glBindTexture, glEnable, GL_TEXTURE_2D from pyglet.gl.VERSION_1_1 import glBegin, glEnd, glVertex2f, GL_LINES from pyglet.window import Window from pyglet.image import Texture w = Window(visible=False) t1 = t2 = Texture.load('examples/kitten.png') glEnable(GL_TEXTURE_2D) ''' print 'No repeated binding' print Timer(''' glBindTexture(GL_TEXTURE_2D, t1.id) glBegin(GL_LINES) glVertex2f(0,0) glVertex2f(0,0) glEnd() glBegin(GL_LINES) glVertex2f(0,0) glVertex2f(0,0) glEnd() ''', setup).repeat(number=NUMBER) print 'Repeated binding' print Timer(''' glBindTexture(GL_TEXTURE_2D, t1.id) glBegin(GL_LINES) glVertex2f(0,0) glVertex2f(0,0) glEnd() glBindTexture(GL_TEXTURE_2D, t2.id) glBegin(GL_LINES) glVertex2f(0,0) glVertex2f(0,0) glEnd() ''', setup).repeat(number=NUMBER) print 'Bind to different tex' print Timer(''' glBindTexture(GL_TEXTURE_2D, t1.id) glBegin(GL_LINES) glVertex2f(0,0) glVertex2f(0,0) glEnd() glBindTexture(GL_TEXTURE_2D, t2.id) glBegin(GL_LINES) glVertex2f(0,0) glVertex2f(0,0) glEnd() ''', setup).repeat(number=NUMBER)
Python
# Number MacBook # 500 59.1715965271 # 1000 29.5857982635 # 2000 19.8412704468 import os import sys import random import pygame import pygame.time from pygame.locals import * pygame.init() win = pygame.display.set_mode((600, 600)) ww, wh = win.get_size() img = pygame.image.load('examples/noisy/ball.png') class BouncySprite(pygame.sprite.Sprite): def update(self, dt): # move, check bounds p = self.properties self.rect.x += p['dx']; self.rect.y += p['dy'] if self.rect.left < 0: self.rect.left = 0; p['dx'] = -p['dx'] elif self.rect.right > 600: self.rect.right = 600; p['dx'] = -p['dx'] if self.rect.bottom < 0: self.rect.bottom = 0; p['dy'] = -p['dy'] elif self.rect.top > 600: self.rect.top = 600; p['dy'] = -p['dy'] group = pygame.sprite.Group() numsprites = int(sys.argv[1]) iw, ih = img.get_size() for i in range(numsprites): x = random.randint(0, ww - iw) y = random.randint(0, wh - ih) s = BouncySprite(group) s.image = img s.rect = pygame.Rect(x, y, iw, ih) s.properties = {'dx': random.randint(-10, 10), 'dy': random.randint(-10, 10)} clock = pygame.time.Clock() t = 0 numframes = 0 while 1: dt = clock.tick() for event in pygame.event.get(): if event.type in (QUIT, KEYDOWN, MOUSEBUTTONDOWN): print 'FPS:', clock.get_fps() print 'us per sprite:', float(t) / (numsprites * numframes) * 1000 sys.exit(0) group.update(dt) win.fill((0,0,0)) group.draw(win) pygame.display.flip() t += dt numframes += 1
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '1.2' import sys from pyglet import clock from pyglet import image from pyglet import window class AnimationPlayer(object): expected_delay = 0 def __init__(self, animation): self.animation = animation self.index = -1 self.next_frame(0) def next_frame(self, dt): self.index = (self.index + 1) % len(self.animation.frames) frame = self.animation.frames[self.index] if frame.duration is not None: delay = frame.duration - (self.expected_delay - dt) delay = min(max(0, delay), frame.duration) clock.schedule_once(self.next_frame, delay) self.expected_delay = delay def blit(self, x, y): self.animation.frames[self.index].image.blit(x, y) try: animation = image.load_animation(sys.argv[1]) except image.codecs.ImageDecodeException: from pyglet import media source = media.load(sys.argv[1]) source._seek(0) animation = source.get_animation() except IndexError: sys.exit('usage: animation.py <image>') w = window.Window() clock.tick() player = AnimationPlayer(animation) while not w.has_exit: clock.tick() w.dispatch_events() w.clear() player.blit(w.width//2, w.height//2) w.flip()
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import gzip import cPickle as marshal import optparse import os import sys import xml.sax def parse_type(type_string): '''Get a tuple of the type components for a SWIG-formatted type. For example, given the type "p.f(p.struct _XExtData).int", return ('int', ('f', ('struct _XExtData', 'p'),), 'p') Qualifiers are ignored (removed). ''' # Scan the type string left-to-right buf = '' stack = [()] def flush(): # buf = flush() if buf: stack[-1] = stack[-1] + (buf,) return '' def push(): stack.append(()) def pop(): item = finalize(stack.pop()) if item is not None: stack[-1] = stack[-1] + (item,) def finalize(item): assert type(item) is tuple if not item: # Empty tuple is dropped (empty param list) return elif item[0] == 'q': # Discard qualifiers return # Reverse (puts pointers at end) item = item[::-1] # Reverse arguments of function if item[-1] == 'f': item = item[::-1] # Empty out (void) param list if item == ('f', ('void',)): item = ('f',) # Varargs encoding elif item[-1] == 'v': item = '...' # Array encoding elif item[-1] == 'a': try: item = ('a',) + tuple(int(j[0]) for j in item[-2::-1]) except (TypeError, ValueError): # TODO arrays of dimension given by sizeof expression item = ('a', 0) # Remove one level of indirection for function types (CFUNCTYPE is # already a pointer) off = 0 for i, j in enumerate(item): if type(j) is tuple and j and j[0] == 'f': item = item[:i+1+off] + item[i+2+off:] off -= 1 return item for c in type_string: if c == '.': buf = flush() elif c == '(': push() # Push param list buf = flush() push() # Push item elif c == ',': buf = flush() pop() # Pop item push() # Push item elif c == ')': buf = flush() pop() # Pop item pop() # Pop param list else: buf += c flush() type_tuple = finalize(stack[0]) return type_tuple class SwigInterfaceHandler(object): def __init__(self): self.name = None self.cdecls = [] self.constants = [] def attribute(self, attrs): if attrs['name'] == 'name': self.name = str(attrs['value']) def typemap(self, attrs): return IgnoreElementHandler() def cdecl(self, attrs): handler = CDeclHandler(attrs) self.cdecls.append(handler) return handler def constant(self, attrs): handler = ConstantHandler(attrs) self.constants.append(handler) return handler def class_(self, attrs): handler = ClassHandler(attrs) self.cdecls.append(handler) return handler def classforward(self, attrs): handler = ClassForwardHandler(attrs) self.cdecls.append(handler) return handler def enum(self, attrs): handler = EnumHandler(attrs) self.cdecls.append(handler) return handler def get_map(self): map = {} for cdecl in self.cdecls: # ('typedef', type) if cdecl.kind == 'typedef': map[cdecl.name] = (cdecl.kind, cdecl.get_type(with_decl=True)) # ('enum', items) elif cdecl.kind == 'enum': enum = (cdecl.kind, cdecl.get_items()) map[cdecl.kind + ' ' + cdecl.name] = enum map[cdecl.get_tdname()] = enum # ('struct', variables) # ('union', variables) elif cdecl.kind in ('struct', 'union'): class_ = (cdecl.kind, cdecl.get_variables()) map[cdecl.kind + ' ' + cdecl.name] = class_ map[cdecl.get_tdname()] = class_ # ('function', type) elif cdecl.kind == 'function': map[cdecl.name] = (cdecl.kind, cdecl.get_type(with_decl=True)) # ('variable', type) elif cdecl.kind == 'variable': map[cdecl.name] = (cdecl.kind, cdecl.get_type()) else: assert False, (cdecl.kind, cdecl.type, cdecl.name) # Constants: ('constant', value) for constant in self.constants: map[constant.name] = ('constant', constant.get_value()) import pprint pprint.pprint(map) return map class IgnoreElementHandler(object): pass class ConstantHandler(object): name = None value = None type = None def __init__(self, attrs): pass def attribute(self, attrs): name = attrs['name'] if name == 'name': self.name = str(attrs['value']) elif name == 'value': self.value = str(attrs['value']) elif name == 'type': self.type = str(attrs['value']) def get_value(self): if self.type in ('int', 'long'): # Yes, ugly and bad -- most C int constants can also be # parsed as Python expressions; e.g. "1L << 8". return int(eval(self.value)) return self.value class EnumHandler(object): name = None tdname = None kind = 'enum' unnamed = False def __init__(self, attrs): self.items = [] def attribute(self, attrs): name = attrs['name'] if name == 'name' and not self.unnamed: self.name = str(attrs['value']) elif name == 'unnamed': self.name = str(attrs['value']) self.unnamed = True elif name == 'tdname': self.tdname = str(attrs['value']) def enumitem(self, attrs): handler = EnumItemHandler(attrs) self.items.append(handler) return handler def get_items(self): items = [] index = 0 for item in self.items: try: # TODO parse enumvalueex properly index = int(item.value) except ValueError: index += 1 items.append((item.name, index)) return tuple(items) def get_tdname(self): if self.tdname: return self.tdname else: return self.name class EnumItemHandler(object): name = None value = None type = None def __init__(self, attrs): pass def attribute(self, attrs): name = attrs['name'] if name == 'name': self.name = str(attrs['value']) elif name == 'unnamed': self.name = str(attrs['value']) elif name == 'enumvalueex': self.value = str(attrs['value']) elif name == 'type': self.type = str(attrs['value']) def get_value(self): if self.type in ('int', 'long'): # Yes, ugly and bad -- most C int constants can also be # parsed as Python expressions; e.g. "1L << 8". return int(eval(self.value)) return self.value class CDeclHandler(object): name = None kind = None type = None decl = '' params = None def __init__(self, attrs): pass def attribute(self, attrs): name = attrs['name'] if name == 'name': self.name = str(attrs['value']) elif name == 'kind': self.kind = str(attrs['value']) elif name == 'type': self.type = str(attrs['value']) elif name == 'decl': self.decl = str(attrs['value']) def parmlist(self, attrs): self.params = [] handler = ParmListHandler(attrs, self.params) return handler def get_params(self): # (type, ...) if self.params is None: return None return tuple(p.get_type() for p in self.params) def get_type(self, with_decl=False): if with_decl: return parse_type(self.decl + self.type) else: return parse_type(self.type) def __str__(self): if self.params: return self.name + \ '(' + ', '.join(map(str, self.params)) + ') : ' + self.type else: return self.name + ' : ' + self.type class ParmListHandler(object): def __init__(self, attrs, params): self.params = params def parm(self, attrs): param = ParmHandler(attrs) self.params.append(param) return param class ParmHandler(object): name = '' type = None def __init__(self, attrs): pass def attribute(self, attrs): name = attrs['name'] if name == 'name': self.name = str(attrs['value']) elif name == 'type': self.type = str(attrs['value']) def get_type(self): return parse_type(self.type) def __str__(self): return self.name + ' : ' + self.type class ClassHandler(object): name = '' kind = None tdname = None unnamed = False def __init__(self, attrs): self.cdecls = [] def attribute(self, attrs): name = attrs['name'] if name == 'name' and not self.unnamed: self.name = str(attrs['value']) elif name == 'unnamed': self.name = str(attrs['value']) self.unnamed = True elif name == 'kind': self.kind = str(attrs['value']) assert self.kind in ('struct', 'union'), self.kind elif name == 'tdname': self.tdname = str(attrs['value']) def cdecl(self, attrs): handler = CDeclHandler(attrs) self.cdecls.append(handler) return handler def get_variables(self): # ((name, type), ...) return tuple((cdecl.name, cdecl.get_type(with_decl=True)) for cdecl in self.cdecls if cdecl.kind == 'variable') def get_tdname(self): if self.tdname: return self.tdname else: return self.name class ClassForwardHandler(object): name = '' kind = None tdname = None def __init__(self, attrs): pass def attribute(self, attrs): name = attrs['name'] if name == 'name': self.name = str(attrs['value']) elif name == 'kind': self.kind = str(attrs['value']) assert self.kind in ('struct', 'union'), self.kind elif name == 'tdname': self.tdname = str(attrs['value']) def get_variables(self): return () def get_tdname(self): if self.tdname: return self.tdname else: return self.name class FFIContentHandler(xml.sax.handler.ContentHandler): def __init__(self): self.swig_interface_handler = SwigInterfaceHandler() self.stack = [self.swig_interface_handler] def startElement(self, name, attrs): if name == 'class': name = 'class_' top = self.stack[-1] func = getattr(top, name, None) if func: self.stack.append(func(attrs)) else: self.stack.append(top) def endElement(self, name): del self.stack[-1] class KeepGoingErrorHandler(xml.sax.handler.ErrorHandler): def error(self, exception): print exception def fatalError(self, exception): print exception def parse(xml_filename, output_filename): handler = FFIContentHandler() error_handler = KeepGoingErrorHandler() xml.sax.parse(xml_filename, handler, error_handler) map = handler.swig_interface_handler.get_map() data = marshal.dumps(map) output_file = gzip.open(output_filename, 'w') output_file.write(data) output_file.close() if __name__ == '__main__': usage = 'usage: %prog [options] <module.xml>' op = optparse.OptionParser(usage=usage) op.add_option('-o', '--output') (options, args) = op.parse_args(sys.argv[1:]) if len(args) < 1: print >> sys.stderr, 'No input file given' sys.exit(1) xml_filename = args[0] module_name, _ = os.path.splitext(os.path.basename(xml_filename)) ffi_filename = module_name + '.ffi' parse(xml_filename, ffi_filename)
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes as c import gzip import marshal import sys class AnonymousStruct(c.Structure): __slots__ = () _fields_ = ( ('foo', c.c_int), ) class AnonymousUnion(c.Union): __slots__ = () _fields_ = ( ('foo', c.c_int), ) class EnumType(type(c.c_int)): def __new__(metaclass, name, bases, dict): cls = type(c.c_int).__new__(metaclass, name, bases, dict) return cls class Enum(c.c_int): __metaclass__ = EnumType _values_ = () @classmethod def from_param(cls, obj): assert obj in cls._values_ return cls(obj) class FFILibrary(object): def __init__(self, ffi_file, lib): data = gzip.GzipFile(mode='r', fileobj=ffi_file).read() self.lib = lib self.map = marshal.loads(data) self.type_map = {} self.forward_map = {} self.builtin_type_map = { 'void': None, 'char': c.c_char, 'signed char': c.c_char, 'unsigned char': c.c_byte, 'wchar_t': c.c_wchar, 'short': c.c_short, 'signed short': c.c_short, 'unsigned short': c.c_ushort, 'int': c.c_int, 'signed int': c.c_int, 'unsigned int': c.c_uint, 'long': c.c_long, 'signed long': c.c_long, 'unsigned long': c.c_ulong, 'long long': c.c_longlong, 'signed long long': c.c_longlong, 'unsigned long long': c.c_ulonglong, 'float': c.c_float, 'double': c.c_double, '...': c.c_int, # Sentinal for va_args list } def dump(self, name): print self.map[name] def __getattr__(self, name): kind, value = self.map[name] if kind == 'constant': result = value elif kind == 'typedef': result = self.get_type(value) elif kind == 'enum': result = self.get_enum_type(name, value) elif kind == 'struct': result = self.get_class_type(name, value, c.Structure) elif kind == 'union': result = self.get_class_type(name, value, c.Union) elif kind == 'function': address = c.addressof(getattr(self.lib, name)) result_type = self.get_type(value) result = result_type.from_address(address) elif kind == 'variable': address = c.addressof(getattr(self.lib, name)) result_type = self.get_type(value) result = result_type.from_address(address) else: raise RuntimeError(kind) setattr(self, name, result) return result def get_type(self, parts): try: return self.type_map[parts] except KeyError: pass result = self.get_base_type(parts[0]) for part in parts[1:]: if part == 'p': result = c.POINTER(result) elif type(part) is tuple: if part[0] == 'f': result = self.get_function_type(result, part[1:]) elif part[0] == 'a': result = self.get_array_type(result, part[1:]) else: raise RuntimeError(part) else: raise RuntimeError(part) self.type_map[parts] = result return result def get_base_type(self, name): try: return self.type_map[name] except KeyError: pass try: return self.builtin_type_map[name] except KeyError: pass try: return self.forward_map[name] except KeyError: pass try: kind, value = self.map[name] except KeyError: if name.startswith('struct '): return AnonymousStruct elif name.startswith('union '): return AnonymousUnion else: raise RuntimeError('FFI contains no type "%s"' % name) if kind == 'typedef': return self.get_type(value) elif kind == 'enum': return self.get_enum_type(name, value) elif kind == 'struct': return self.get_class_type(name, value, c.Structure) elif kind == 'union': return self.get_class_type(name, value, c.Union) else: raise RuntimeError(kind) def get_enum_type(self, name, items): class _FFIEnum(Enum): pass _FFIEnum.__name__ = name for key, value in items: setattr(_FFIEnum, key, value) _FFIEnum._values_ = tuple([value for key, value in items]) return _FFIEnum def get_class_type(self, name, fields, base): slots = tuple(name for name, _ in fields) class _FFIStruct(base): __slots__ = slots _FFIStruct.__name__ = name self.forward_map[name] = _FFIStruct _FFIStruct._fields_ = tuple((name, self.get_type(type)) for (name, type) in fields) del self.forward_map[name] return _FFIStruct def get_function_type(self, restype, params): params = map(self.get_type, params) return c.CFUNCTYPE(restype, *params) def get_array_type(self, element_type, dimensions): result = element_type # TODO is order reversed for multi-dim? for d in dimensions: result = element_type * d return result if __name__ == '__main__': ffi_filename = sys.argv[1] libname = sys.argv[2] lib = FFILibrary(open(ffi_filename, 'rb'), c.cdll.LoadLibrary(libname)) if len(sys.argv) > 3: lib.dump(sys.argv[3]) else: for key in lib.map: print key, getattr(lib, key) try: getattr(lib, key) except AttributeError, e: print e
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import optparse import os import re import subprocess import sys import parse def create_swig_interface(header_filename, interface_filename, includes=(), module_name=None, defines=()): defines = list(defines) defines += [ '_WCHAR_T=wchar_t', r'__attribute__\(x\)=', '__restrict=', '__const=', '__extension__=', '__signed__=signed', ] includes = ['-I' + include for include in includes] defines = ['-D' + define for define in defines] cflags = ' '.join(includes + defines) interface_file = open(interface_filename, 'w') skip_predefined_macros_re = re.compile('^#define __.*', flags=re.DOTALL) if module_name is None: module_name, _ = os.path.splitext(os.path.basename(header_filename)) print >> interface_file, '%%module %s' % module_name cmd = 'gcc %s -E -P -dD %s -o -' % ( cflags, header_filename) print cmd gcc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) for line in gcc.stdout.readlines(): if not skip_predefined_macros_re.match(line): interface_file.write(line) gcc.stdout.close() interface_file.close() def create_swig_xml(interface_filename, xml_filename): cmd = 'swig -xml -xmllite -o %s %s' % (xml_filename, interface_filename) print cmd result = subprocess.call(cmd, shell=True) if result: sys.exit(result) if __name__ == '__main__': usage = 'usage: %prog [options] <header.h>' op = optparse.OptionParser(usage=usage) op.add_option('-o', '--output') op.add_option('-i', '--interface-file') op.add_option('-x', '--xml-file') op.add_option('-I', dest='includes', action='append', default=[]) op.add_option('-D', dest='defines', action='append', default=[]) (options, args) = op.parse_args(sys.argv[1:]) if len(args) < 1: print >> sys.stderr, 'No input file given' sys.exit(1) header_filename = args[0] module_name, _ = os.path.splitext(os.path.basename(header_filename)) if options.interface_file is None: options.interface_file = module_name + '.i' if options.xml_file is None: options.xml_file = module_name + '.xml' if options.output is None: options.output = module_name + '.ffi' create_swig_interface(header_filename, options.interface_file, includes=options.includes, defines=options.defines) create_swig_xml(options.interface_file, options.xml_file) parse.parse(options.xml_file, options.output)
Python
#!/usr/bin/env python # -*- coding: latin-1 -*- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import math import random import re import os.path import pyglet from pyglet.gl import * import xml.dom import xml.dom.minidom class SmoothLineGroup(pyglet.graphics.Group): def set_state(self): glPushAttrib(GL_ENABLE_BIT) glEnable(GL_LINE_SMOOTH) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE) def unset_state(self): glPopAttrib() class Curve(object): PATH_RE = re.compile(r'([MLHVCSQTAZ])([^MLHVCSQTAZ]+)', re.IGNORECASE) INT = r'([+-]?\d+)' FLOAT = r'(?:[\s,]*)([+-]?\d+(?:\.\d+)?)' HANDLERS = {} def handle(char, rx, types, HANDLERS=HANDLERS): def register(function): HANDLERS[char] = (rx and re.compile(rx), function, types) return function return register def __init__(self, spec, batch): self.batch = batch self.start = None self.current = None self.min_x = self.min_y = self.max_x = self.max_y = None for cmd, value in self.PATH_RE.findall(spec): #print (cmd, value) if not cmd: continue rx, handler, types = self.HANDLERS[cmd.upper()] if rx is None: handler(self, cmd) else: v = [] for fields in rx.findall(value): v.append([types[i](e) for i, e in enumerate(fields)]) handler(self, cmd, v) def _determine_rect(self, x, y): y = -y if self.min_x is None: self.min_x = self.max_x = x self.min_y = self.max_y = y else: if self.min_x > x: self.min_x = x elif self.max_x < x: self.max_x = x if self.min_y > y: self.min_y = y elif self.max_y < y: self.max_y = y @handle('M', FLOAT*2, (float, float)) def moveto(self, cmd, points): '''Start a new sub-path at the given (x,y) coordinate. M (uppercase) indicates that absolute coordinates will follow; m (lowercase) indicates that relative coordinates will follow. If a relative moveto (m) appears as the first element of the path, then it is treated as a pair of absolute coordinates. If a moveto is followed by multiple pairs of coordinates, the subsequent pairs are treated as implicit lineto commands. Parameters are (x y)+ ''' points = [map(float, point) for point in points] # XXX handle relative # XXX confirm that we always reset start here self.start = self.current = points[0] if len(points) > 2: self.lineto({'m': 'l', 'M': 'L'}[cmd], points[1:]) @handle('L', FLOAT*2, (float, float)) def lineto(self, cmd, points): '''Draw a line from the current point to the given (x,y) coordinate which becomes the new current point. L (uppercase) indicates that absolute coordinates will follow; l (lowercase) indicates that relative coordinates will follow. A number of coordinates pairs may be specified to draw a polyline. At the end of the command, the new current point is set to the final set of coordinates provided. Parameters are (x y)+ ''' l = [] self._determine_rect(*self.current) for point in points: cx, cy = self.current x, y = map(float, point) l.extend([cx, -cy]) l.extend([x, -y]) self.current = (x, y) self._determine_rect(x, y) self.batch.add(len(l)/2, GL_LINES, SmoothLineGroup(), ('v2f', l)) @handle('H', FLOAT, (float,)) def horizontal_lineto(self, cmd, xvals): '''Draws a horizontal line from the current point (cpx, cpy) to (x, cpy). H (uppercase) indicates that absolute coordinates will follow; h (lowercase) indicates that relative coordinates will follow. Multiple x values can be provided (although usually this doesn't make sense). At the end of the command, the new current point becomes (x, cpy) for the final value of x. Parameters are x+ ''' cx, cy = self.current self._determine_rect(*self.current) x = float(xvals[-1]) self.batch.add(2, GL_LINES, None, ('v2f', (cx, -cy, x, -cy))) self.current = (x, cy) self._determine_rect(x, cy) @handle('V', FLOAT, (float,)) def vertical_lineto(self, cmd, yvals): '''Draws a vertical line from the current point (cpx, cpy) to (cpx, y). V (uppercase) indicates that absolute coordinates will follow; v (lowercase) indicates that relative coordinates will follow. Multiple y values can be provided (although usually this doesn't make sense). At the end of the command, the new current point becomes (cpx, y) for the final value of y. Parameters are y+ ''' cx, cy = self.current self._determine_rect(*self.current) y = float(yvals[-1]) self.batch.add(2, GL_LINES, None, ('v2f', [cx, -cy, cx, -y])) self.current = (cx, y) self._determine_rect(cx, y) @handle('Z', None, None) def closepath(self, cmd): '''Close the current subpath by drawing a straight line from the current point to current subpath's initial point. ''' self.batch.add(2, GL_LINES, SmoothLineGroup(), ('v2f', self.current + tuple(self.start))) @handle('C', FLOAT*6, (float, )*6) def curveto(self, cmd, control_points): '''Draws a cubic Bézier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve. C (uppercase) indicates that absolute coordinates will follow; c (lowercase) indicates that relative coordinates will follow. Multiple sets of coordinates may be specified to draw a polybézier. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybézier. Control points are (x1 y1 x2 y2 x y)+ ''' l = [] last=None for entry in control_points: x1, y1, x2, y2, x, y = map(float, entry) t = 0 cx, cy = self.current self.last_control = (x2, y2) self.current = (x, y) x1 *= 3; x2 *= 3 y1 *= 3; y2 *= 3 while t <= 1.01: a = t; a2 = a**2; a3 = a**3 b = 1 - t; b2 = b**2; b3 = b**3 px = cx*b3 + x1*b2*a + x2*b*a2 + x*a3 py = cy*b3 + y1*b2*a + y2*b*a2 + y*a3 if last is not None: l.extend(last) l.extend((px, -py)) last = (px, -py) self._determine_rect(px, py) t += 0.01 self.batch.add(len(l)/2, GL_LINES, SmoothLineGroup(), ('v2f', l)) @handle('S', FLOAT*4, (float, )*4) def smooth_curveto(self, cmd, control_points): '''Draws a cubic Bézier curve from the current point to (x,y). The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an C, c, S or s, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). S (uppercase) indicates that absolute coordinates will follow; s (lowercase) indicates that relative coordinates will follow. Multiple sets of coordinates may be specified to draw a polybézier. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybézier. Control points are (x2 y2 x y)+ ''' assert self.last_control is not None, 'S must follow S or C' l = [] last = None for entry in control_points: x2, y2, x, y = map(float, entry) # Reflect last control point cx, cy = self.current; lcx, lcy = self.last_control dx, dy = cx - lcx, cy - lcy x1, y1 = cx + dx, cy + dy t = 0 cx, cy = self.current self.last_control = (x2, y2) self.current = (x, y) x1 *= 3; x2 *= 3 y1 *= 3; y2 *= 3 while t <= 1.01: a = t; a2 = a**2; a3 = a**3 b = 1 - t; b2 = b**2; b3 = b**3 px = cx*b3 + x1*b2*a + x2*b*a2 + x*a3 py = cy*b3 + y1*b2*a + y2*b*a2 + y*a3 if last is not None: l.extend(last) l.extend((px, -py)) last = (px, -py) self._determine_rect(px, py) t += 0.01 # degenerate vertices self.batch.add(len(l)/2, GL_LINES, SmoothLineGroup(), ('v2f', l)) @handle('Q', FLOAT*4, (float, )*4) def quadratic_curveto(self, cmd, control_points): '''Draws a quadratic Bézier curve from the current point to (x,y) using (x1,y1) as the control point. Q (uppercase) indicates that absolute coordinates will follow; q (lowercase) indicates that relative coordinates will follow. Multiple sets of coordinates may be specified to draw a polybézier. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybézier. Control points are (x1 y1 x y)+ ''' raise NotImplementedError('not implemented') @handle('T', FLOAT*2, (float, )*2) def smooth_quadratic_curveto(self, cmd, control_points): '''Draws a quadratic Bézier curve from the current point to (x,y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a Q, q, T or t, assume the control point is coincident with the current point.) T (uppercase) indicates that absolute coordinates will follow; t (lowercase) indicates that relative coordinates will follow. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybézier. Control points are (x y)+ ''' raise NotImplementedError('not implemented') @handle('A', FLOAT*3 + INT*2 + FLOAT*2, (float,)*3 + (int,)*2 + (float,)*2) def elliptical_arc(self, cmd, parameters): '''Draws an elliptical arc from the current point to (x, y). The size and orientation of the ellipse are defined by two radii (rx, ry) and an x-axis-rotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. large-arc-flag and sweep-flag contribute to the automatic calculations and help determine how the arc is drawn. Parameters are (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ ''' raise NotImplementedError('not implemented') class SVG(object): def __init__(self, filename, rect=None): dom = xml.dom.minidom.parse(filename) tag = dom.documentElement if tag.tagName != 'svg': raise ValueError('document is <%s> instead of <svg>'%tag.tagName) # generate all the drawing elements self.batch = pyglet.graphics.Batch() self.objects = [] for tag in tag.getElementsByTagName('g'): for tag in tag.getElementsByTagName('path'): self.objects.append(Curve(tag.getAttribute('d'), self.batch)) # determine drawing bounds self.min_x = min(o.min_x for o in self.objects) self.max_x = max(o.max_x for o in self.objects) self.min_y = min(o.min_y for o in self.objects) self.max_y = max(o.max_y for o in self.objects) # determine or apply drawing rect if rect is None: self._rect = (self.min_x, self.min_y, self.max_x - self.min_x, self.max_y - self.min_y) else: self.set_rect(rect) def set_rect(self, rect): self._rect = rect # figure transform for display rect self.translate_x, self.translate_y, rw, rh = rect self.scale_x = abs(rw / float(self.max_x - self.min_x)) self.scale_y = abs(rh / float(self.max_y - self.min_y)) rect = property(lambda self: self._rect, set_rect) def draw(self): glPushMatrix() if self._rect is not None: glScalef(self.scale_x, self.scale_y, 1) glTranslatef(self.translate_x-self.min_x, self.translate_x-self.min_y, 0) self.batch.draw() glPopMatrix() w = pyglet.window.Window(width=600, height=300, resizable=True) dirname = os.path.dirname(__file__) svg = SVG(os.path.join(dirname, 'hello_world.svg'), rect=(0, 0, 600, 300)) @w.event def on_draw(): w.clear() svg.draw() @w.event def on_resize(w, h): svg.rect = svg.rect[:2] + (w, h) pyglet.app.run()
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import time from pyglet.ext.layout import * from pyglet.window import * window = Window(visible=False) def print_time(start, msg): dt = time.time() - start print '%f\t%s' % (dt, msg) def profile(xhtml, widths=[800,600,400,200,100], runs=3): for i in range(runs): start = time.time() layout = Layout() layout.set_xhtml(xhtml) print_time(start, 'create layout') for width in widths: for i in range(runs): start = time.time() layout.viewport_width = width layout.draw() print_time(start, 'layout width=%d' % width) for i in range(runs): start = time.time() layout.draw() print_time(start, 'draw width=%d' % width) xhtml = '''<?xml version="1.0"?> <html> <head> <style> h1 {border-bottom: 1px solid; background-image: url(examples/stripe.png)} body {background-image: url(examples/paper.jpg); background-repeat: repeat} </style> </head> <body> <h1>The Frog King</h1> <h2>Brothers Grimm</h2> <p> In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything. </p> <p> Now it so happened that on one occasion the princess's golden ball did not fall into the little hand which she was holding up for it, but on to the ground beyond, and rolled straight into the water. The king's daughter followed it with her eyes, but it vanished, and the well was deep, so deep that the bottom could not be seen. At this she began to cry, and cried louder and louder, and could not be comforted. And as she thus lamented someone said to her, "What ails you, king's daughter? You weep so that even a stone would show pity." </p> <p> She looked round to the side from whence the voice came, and saw a frog stretching forth its big, ugly head from the water. "Ah, old water-splasher, is it you," she said, "I am weeping for my golden ball, which has fallen into the well." "Be quiet, and do not weep," answered the frog, "I can help you, but what will you give me if I bring your plaything up again?" "Whatever you will have, dear frog," said she, "My clothes, my pearls and jewels, and even the golden crown which I am wearing." The frog answered, "I do not care for your clothes, your pearls and jewels, nor for your golden crown, but if you will love me and let me be your companion and play-fellow, and sit by you at your little table, and eat off your little golden plate, and drink out of your little cup, and sleep in your little bed---if you will promise me this I will go down below, and bring you your golden ball up again." </p> <p> "Oh yes," said she, "I promise you all you wish, if you will but bring me my ball back again." But she thought, "How the silly frog does talk. All he does is to sit in the water with the other frogs, and croak. He can be no companion to any human being." </p> <p> But the frog when he had received this promise, put his head into the water and sank down; and in a short while came swimmming up again with the ball in his mouth, and threw it on the grass. The king's daughter was delighted to see her pretty plaything once more, and picked it up, and ran away with it. "Wait, wait," said the frog. "Take me with you. I can't run as you can." But what did it avail him to scream his croak, croak, after her, as loudly as he could. She did not listen to it, but ran home and soon forgot the poor frog, who was forced to go back into his well again. </p> <p> The next day when she had seated herself at table with the king and all the courtiers, and was eating from her little golden plate, something came creeping splish splash, splish splash, up the marble staircase, and when it had got to the top, it knocked at the door and cried, "Princess, youngest princess, open the door for me." She ran to see who was outside, but when she opened the door, there sat the frog in front of it. Then she slammed the door to, in great haste, sat down to dinner again, and was quite frightened. The king saw plainly that her heart was beating violently, and said, "My child, what are you so afraid of? Is there perchance a giant outside who wants to carry you away?" "Ah, no," replied she. "It is no giant but a disgusting frog." </p> <p> "What does a frog want with you?" "Ah, dear father, yesterday as I was in the forest sitting by the well, playing, my golden ball fell into the water. And because I cried so, the frog brought it out again for me, and because he so insisted, I promised him he should be my companion, but I never thought he would be able to come out of his water. And now he is outside there, and wants to come in to me." </p> <p> In the meantime it knocked a second time, and cried, "Princess, youngest princess, open the door for me, do you not know what you said to me yesterday by the cool waters of the well. Princess, youngest princess, open the door for me." </p> <p> Then said the king, "That which you have promised must you perform. Go and let him in." She went and opened the door, and the frog hopped in and followed her, step by step, to her chair. There he sat and cried, "Lift me up beside you." She delayed, until at last the king commanded her to do it. Once the frog was on the chair he wanted to be on the table, and when he was on the table he said, "Now, push your little golden plate nearer to me that we may eat together." She did this, but it was easy to see that she did not do it willingly. The frog enjoyed what he ate, but almost every mouthful she took choked her. At length he said, "I have eaten and am satisfied, now I am tired, carry me into your little room and make your little silken bed ready, and we will both lie down and go to sleep." </p> <p> The king's daughter began to cry, for she was afraid of the cold frog which she did not like to touch, and which was now to sleep in her pretty, clean little bed. But the king grew angry and said, "He who helped you when you were in trouble ought not afterwards to be despised by you." So she took hold of the frog with two fingers, carried him upstairs, and put him in a corner, but when she was in bed he crept to her and said, "I am tired, I want to sleep as well as you, lift me up or I will tell your father." At this she was terribly angry, and took him up and threw him with all her might against the wall. "Now, will you be quiet, odious frog," said she. But when he fell down he was no frog but a king's son with kind and beautiful eyes. He by her father's will was now her dear companion and husband. Then he told her how he had been bewitched by a wicked witch, and how no one could have delivered him from the well but herself, and that to-morrow they would go together into his kingdom. </p> <p> Then they went to sleep, and next morning when the sun awoke them, a carriage came driving up with eight white horses, which had white ostrich feathers on their heads, and were harnessed with golden chains, and behind stood the young king's servant Faithful Henry. Faithful Henry had been so unhappy when his master was changed into a frog, that he had caused three iron bands to be laid round his heart, lest it should burst with grief and sadness. The carriage was to conduct the young king into his kingdom. Faithful Henry helped them both in, and placed himself behind again, and was full of joy because of this deliverance. And when they had driven a part of the way the king's son heard a cracking behind him as if something had broken. So he turned round and cried, "Henry, the carriage is breaking." "No, master, it is not the carriage. It is a band from my heart, which was put there in my great pain when you were a frog and imprisoned in the well." Again and once again while they were on their way something cracked, and each time the king's son thought the carriage was breaking, but it was only the bands which were springing from the heart of Faithful Henry because his master was set free and was happy. </p> </body> </html> ''' if __name__ == '__main__': profile(xhtml)
Python
#!/usr/bin/python # $Id:$ import ctypes import sys import pyglet from pyglet.window import key from pyglet.gl import * class Shader(object): '''Generic shader loader.''' def __init__(self, vertex_source, fragment_source=None): vertex_shader = self._create_shader(GL_VERTEX_SHADER, vertex_source) if fragment_source: fragment_shader = self._create_shader(GL_FRAGMENT_SHADER, fragment_source) program = glCreateProgram() glAttachShader(program, vertex_shader) if fragment_source: glAttachShader(program, fragment_shader) glLinkProgram(program) status = ctypes.c_int() glGetProgramiv(program, GL_LINK_STATUS, status) if not status.value: length = ctypes.c_int() glGetProgramiv(program, GL_INFO_LOG_LENGTH, length) log = ctypes.c_buffer(length.value) glGetProgramInfoLog(program, len(log), None, log) print >> sys.stderr, log.value raise RuntimeError('Program link error') self.program = program self._uniforms = {} def _create_shader(self, type, source): shader = glCreateShader(type) c_source = ctypes.create_string_buffer(source) c_source_ptr = ctypes.cast(ctypes.pointer(c_source), ctypes.POINTER(c_char)) glShaderSource(shader, 1, ctypes.byref(c_source_ptr), None) glCompileShader(shader) status = ctypes.c_int() glGetShaderiv(shader, GL_COMPILE_STATUS, status) if not status.value: length = ctypes.c_int() glGetShaderiv(shader, GL_INFO_LOG_LENGTH, length) log = ctypes.c_buffer(length.value) glGetShaderInfoLog(shader, len(log), None, log) print >> sys.stderr, log.value raise RuntimeError('Shader compile error') return shader def __getitem__(self, name): try: return self._uniforms[name] except KeyError: location = self._uniforms[name] = \ glGetUniformLocation(self.program, name) return location class DistFieldTextureGroup(pyglet.sprite.SpriteGroup): '''Override sprite's texture group to enable either the shader or alpha testing.''' def set_state(self): glEnable(self.texture.target) glBindTexture(self.texture.target, self.texture.id) glPushAttrib(GL_COLOR_BUFFER_BIT) if enable_shader: glUseProgram(shader.program) glUniform1i(shader['bidirectional'], enable_bidirectional) glUniform1i(shader['antialias'], enable_antialias) glUniform1i(shader['outline'], enable_outline) glUniform1f(shader['outline_width'], outline_width) glUniform1i(shader['glow'], enable_glow) glUniform1f(shader['glow_width'], glow_width) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) else: glEnable(GL_ALPHA_TEST) glAlphaFunc(GL_GEQUAL, 0.5) def unset_state(self): if enable_shader: glUseProgram(0) glPopAttrib(GL_COLOR_BUFFER_BIT) glDisable(self.texture.target) class DistFieldSprite(pyglet.sprite.Sprite): '''Override sprite to use DistFieldTextureGroup.''' 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'): super(DistFieldSprite, self).__init__( img, x, y, blend_src, blend_dest, batch, group, usage) self._group = DistFieldTextureGroup( self._texture, blend_src, blend_dest, group) self._usage = usage self._create_vertex_list() window = pyglet.window.Window(resizable=True) @window.event def on_resize(width, height): scale_width = width / float(image.width) scale_height = height / float(image.height) sprite.scale = min(scale_width, scale_height) sprite.x = width / 2 sprite.y = height / 2 @window.event def on_draw(): window.clear() sprite.draw() @window.event def on_key_press(symbol, modifiers): global enable_shader global enable_bidirectional global enable_antialias global enable_outline global enable_glow global outline_width global glow_width if symbol == key.S: enable_shader = not enable_shader elif symbol == key.B: enable_bidirectional = not enable_bidirectional elif symbol == key.A: enable_antialias = not enable_antialias elif symbol == key.O: enable_outline = not enable_outline enable_glow = False elif symbol == key.G: enable_glow = not enable_glow enable_outline = False elif symbol == key.PERIOD: if enable_glow: glow_width += 0.005 else: outline_width += 0.005 elif symbol == key.COMMA: if enable_glow: glow_width -= 0.005 else: outline_width -= 0.005 print '-' * 78 print 'enable_shader', enable_shader print 'enable_bidirectional', enable_bidirectional print 'enable_antialias', enable_antialias print 'enable_outline', enable_outline print 'enable_glow', enable_glow print 'outline_width', outline_width image = pyglet.image.load(sys.argv[1]) image.anchor_x = image.width // 2 image.anchor_y = image.height // 2 sprite = DistFieldSprite(image) shader = Shader(''' /* Vertex shader */ void main() { /* Pass through */ gl_Position = ftransform(); gl_FrontColor = gl_Color; gl_TexCoord[0] = gl_MultiTexCoord0; } ''', ''' /* Fragment shader */ uniform sampler2D tex; uniform bool bidirectional; uniform bool antialias; uniform bool outline; uniform bool glow; uniform float outline_width; uniform float glow_width; const vec4 outline_color = vec4(0.0, 0.0, 1.0, 1.0); const vec4 glow_color = vec4(1.0, 0.0, 0.0, 1.0); void main() { float alpha_mask; if (bidirectional) { vec4 field = texture2D(tex, gl_TexCoord[0].st); alpha_mask = float(field.r >= 0.5 && field.g >= 0.5); } else { alpha_mask = texture2D(tex, gl_TexCoord[0].st).a; } float alpha_width = fwidth(alpha_mask); float intensity = alpha_mask; gl_FragColor = gl_Color; if (glow) { float glow_min = 0.5 - glow_width; intensity = (alpha_mask - glow_min) / (0.5 - glow_min); float glow_intensity = 0.0; if (antialias) glow_intensity = 1.0 - smoothstep(0.5 - alpha_width, 0.5 + alpha_width, alpha_mask) * 2.0; else glow_intensity = float(alpha_mask < 0.5); gl_FragColor = lerp(gl_FragColor, glow_color, glow_intensity); } else if (outline) { float outline_intensity = 0.0; float outline_min = 0.5 - outline_width; float outline_max = 0.5; if (antialias) { outline_intensity = 1.0 - smoothstep(outline_max - alpha_width, outline_max + alpha_width, alpha_mask) * 2.0; intensity *= smoothstep(outline_min - alpha_width, outline_min + alpha_width, alpha_mask) * 2.0; } else { outline_intensity = float(alpha_mask >= outline_min && alpha_mask <= outline_max); intensity = float(alpha_mask >= outline_min); } gl_FragColor = lerp(gl_FragColor, outline_color, outline_intensity); } else if (antialias) { intensity *= smoothstep(0.5 - alpha_width, 0.5 + alpha_width, alpha_mask) * 2.0; } else { intensity = float(alpha_mask >= 0.5); } gl_FragColor.a = intensity; } ''') enable_shader = True enable_bidirectional = False enable_antialias = False enable_outline = False enable_glow = False outline_width = 0.02 glow_width = 0.1 pyglet.app.run()
Python
#!/usr/bin/python # $Id:$ import ctypes import math import optparse import pyglet root2 = math.sqrt(2) def gen_dist_field(img, width, height, spread, bidirectional=True): sample_width = img.width // width sample_height = img.height // height max_dist = spread * root2 dist_scale = 127. / max_dist # Grab image data as list of int. data = img.get_data('L', img.width) if isinstance(data, str): data = map(ord, data) # Pad input image by `spread` on each side to avoid having to check bounds # Add left and right sides data_tmp = [] padx = [0] * spread pitch = img.width in_i = 0 for row_i in range(img.height): data_tmp.extend(padx) data_tmp.extend(data[in_i:in_i + pitch]) data_tmp.extend(padx) in_i += pitch pitch += spread * 2 # Add top and bottom pady = [0] * (pitch * spread) data = pady + data_tmp + pady field = [] for y in range(height): in_i = (spread + int((y + 0.5) * sample_height)) * pitch + \ spread + sample_width // 2 for x in range(width): colour = data[in_i] dist1_sq = dist2_sq = dist_sq = (max_dist + 1) ** 2 for sy in range(-spread, spread + 1): row_i = in_i + sy * pitch for sx in range(-spread, spread + 1): if data[row_i + sx] != colour: dist_sq = min(dist_sq, sy * sy + sx * sx) if sx * sy > 0: dist1_sq = min(dist1_sq, sy * sy + sx * sx) else: dist2_sq = min(dist2_sq, sy * sy + sx * sx) dist = math.sqrt(dist_sq) dist1 = math.sqrt(dist1_sq) dist2 = math.sqrt(dist2_sq) if not colour: dist = -dist dist1 = -dist1 dist2 = -dist2 dist = int(dist * dist_scale) + 128 dist1 = int(dist1 * dist_scale) + 128 dist2 = int(dist2 * dist_scale) + 128 if bidirectional: field.append(dist1) field.append(dist2) field.append(dist) else: field.append(255) field.append(dist) in_i += sample_width field = (ctypes.c_byte * len(field))(*field) out_img = pyglet.image.create(width, height) if bidirectional: out_img.set_data('RGBA', width * 4, field) else: out_img.set_data('LA', width * 2, field) return out_img if __name__ == '__main__': import os parser = optparse.OptionParser() parser.add_option('-s', '--size', type=int, default=32) parser.add_option('-p', '--spread', type=int, default=128) parser.add_option('-o', '--output', default=None) parser.add_option('-b', '--bidirectional', action='store_true', default=False) (options, args) = parser.parse_args() filename = args[0] img = pyglet.image.load(filename) img2 = gen_dist_field(img, options.size, options.size, options.spread, options.bidirectional) if not options.output: base, _ = os.path.splitext(filename) options.output = '%s.df.png' % base img2.save(options.output)
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import math import warnings import pyglet import pyglet.image try: from pyglet.gl.VERSION_1_5 import * except ImportError: warnings.warn('OpenGL 1.5 or later is required collision detection. '\ 'Please update your video card driver.') class Sprite(object): # <rj> slots buy us nothing #__slots__ = ['texture', 'anchor', 'position', 'rotation', 'scale', 'color'] _collision_stencil = 1 def __init__(self, texture, anchor=None): if isinstance(texture, pyglet.image.Image): texture = pyglet.image.Texture.from_image(texture) self.texture = texture self.position = (0,0) self.anchor = (self.texture.size[0] / 2, self.texture.size[1] / 2) self.rotation = 0.0 self.scale = 1.0 self.color = (1, 1, 1, 1) def draw(self): glPushMatrix() glPushAttrib(GL_CURRENT_BIT) glColor4fv(self.color) glTranslate(self.position[0], self.position[1], 0) glRotate(self.rotation, 0, 0, -1) glScale(self.scale, self.scale, 1) glTranslate(-self.anchor[0], -self.anchor[1], 0) self.texture.draw() glPopAttrib() glPopMatrix() def translate(self, dx, dy): '''Move the sprite by the given units, transformed by its current rotation. Useful for moving a sprite "forward" according to its current direction.''' r = math.pi * self.rotation / 180.0 c = math.cos(r) s = math.sin(r) x = self.position[0] y = self.position[1] self.position = x + c * dx + s * dy, y + s * dx + c * dy def collide(self, other): '''Get the number of pixels of overlap between self and other. other can be a Sprite or list of Sprites.''' glPushAttrib(GL_COLOR_BUFFER_BIT | \ GL_STENCIL_BUFFER_BIT | \ GL_ENABLE_BIT) glColorMask(0, 0, 0, 0) glEnable(GL_ALPHA_TEST) glAlphaFunc(GL_GEQUAL, 0.5) # Draw collider into stencil glClear(GL_STENCIL_BUFFER_BIT) glStencilFunc(GL_ALWAYS, self._collision_stencil, self._collision_stencil) glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE) glEnable(GL_STENCIL_TEST) if hasattr(other, '__len__'): for o in other: other.draw() else: other.draw() # Occlusion query self glStencilFunc(GL_EQUAL, self._collision_stencil, self._collision_stencil) query = c_uint() glGenQueries(1, byref(query)) glBeginQuery(GL_SAMPLES_PASSED, query) self.draw() glEndQuery(GL_SAMPLES_PASSED) result = c_int() glGetQueryObjectiv(query, GL_QUERY_RESULT, byref(result)) glDeleteQueries(1, byref(query)) glPopAttrib() return result.value def collide_list(self, others): '''Get a list of Sprites in others that collide with self.''' glPushAttrib(GL_COLOR_BUFFER_BIT | \ GL_STENCIL_BUFFER_BIT | \ GL_ENABLE_BIT) glColorMask(0, 0, 0, 0) glEnable(GL_ALPHA_TEST) glAlphaFunc(GL_GEQUAL, 0.5) # Draw self into stencil glClear(GL_STENCIL_BUFFER_BIT) glStencilFunc(GL_ALWAYS, self._collision_stencil, self._collision_stencil) glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE) glEnable(GL_STENCIL_TEST) self.draw() # Occlusion query each other glStencilFunc(GL_EQUAL, self._collision_stencil, self._collision_stencil) # Using multiple queries is noticeably faster than reusing the # one query. n_query = len(others) query = (c_uint * n_query)() glGenQueries(n_query, query) collisions = [] for i, other in enumerate(others): glBeginQuery(GL_SAMPLES_PASSED, query[i]) other.draw() glEndQuery(GL_SAMPLES_PASSED) for i, other in enumerate(others): result = c_int() glGetQueryObjectiv(query[i], GL_QUERY_RESULT, byref(result)) if result.value > 0: collisions.append(other) glDeleteQueries(n_query, query) glPopAttrib() return collisions
Python
from ctypes import * from pyglet.gl import * class GLSLException(Exception): pass def glsl_log(handle): if handle == 0: return '' log_len = c_int(0) glGetObjectParameterivARB(handle, GL_OBJECT_INFO_LOG_LENGTH_ARB, byref(log_len)) if log_len.value == 0: return '' log = create_string_buffer(log_len.value) # does log_len include the NUL? chars_written = c_int(0) glGetInfoLogARB(handle, log_len.value, byref(chars_written), log) return log.value class Shader(object): s_tag = 0 def __init__(self, name, prog): self.name = name self.prog = prog self.shader = 0 self.compiling = False self.tag = -1 self.dependencies = [] def __del__(self): self.destroy() def _source(self): if self.tag == Shader.s_tag: return [] self.tag = Shader.s_tag r = [] for d in self.dependencies: r.extend(d._source()) r.append(self.prog) return r def _compile(self): if self.shader: return if self.compiling : return self.compiling = True self.shader = glCreateShaderObjectARB(self.shaderType()) if self.shader == 0: raise GLSLException('faled to create shader object') prog = c_char_p(self.prog) length = c_int(-1) glShaderSourceARB(self.shader, 1, cast(byref(prog), POINTER(POINTER(c_char))), byref(length)) glCompileShaderARB(self.shader) self.compiling = False compile_status = c_int(0) glGetObjectParameterivARB(self.shader, GL_OBJECT_COMPILE_STATUS_ARB, byref(compile_status)) if not compile_status.value: err = glsl_log(self.shader) glDeleteObjectARB(self.shader) self.shader = 0 raise GLSLException('failed to compile shader', err) def _attachTo(self, program): if self.tag == Shader.s_tag: return self.tag = Shader.s_tag for d in self.dependencies: d._attachTo(program) if self.isCompiled(): glAttachObjectARB(program, self.shader) def addDependency(self, shader): self.dependencies.append(shader) return self def destroy(self): if self.shader != 0: glDeleteObjectARB(self.shader) def shaderType(self): raise NotImplementedError() def isCompiled(self): return self.shader != 0 def attachTo(self, program): Shader.s_tag = Shader.s_tag + 1 self._attachTo(program) # ATI/apple's glsl compiler is broken. def attachFlat(self, program): if self.isCompiled(): glAttachObjectARB(program, self.shader) def compileFlat(self): if self.isCompiled(): return self.shader = glCreateShaderObjectARB(self.shaderType()) if self.shader == 0: raise GLSLException('faled to create shader object') all_source = ['\n'.join(self._source())] prog = (c_char_p * len(all_source))(*all_source) length = (c_int * len(all_source))(-1) glShaderSourceARB(self.shader, len(all_source), cast(prog, POINTER(POINTER(c_char))), length) glCompileShaderARB(self.shader) compile_status = c_int(0) glGetObjectParameterivARB(self.shader, GL_OBJECT_COMPILE_STATUS_ARB, byref(compile_status)) if not compile_status.value: err = glsl_log(self.shader) glDeleteObjectARB(self.shader) self.shader = 0 raise GLSLException('failed to compile shader', err) def compile(self): if self.isCompiled(): return for d in self.dependencies: d.compile() self._compile() class VertexShader(Shader): def shaderType(self): return GL_VERTEX_SHADER_ARB class FragmentShader(Shader): def shaderType(self): return GL_FRAGMENT_SHADER_ARB class ShaderProgram(object): def __init__(self, vertex_shader=None, fragment_shader=None): self.vertex_shader = vertex_shader self.fragment_shader = fragment_shader self.program = 0 def __del__(self): self.destroy() def destroy(self): if self.program != 0: glDeleteObjectARB(self.program) def setShader(self, shader): if isinstance(shader, FragmentShader): self.fragment_shader = shader if isinstance(shader, VertexShader): self.vertex_shader = shader if self.program != 0: glDeleteObjectARB(self.program) def link(self): if self.vertex_shader is not None: self.vertex_shader.compileFlat() if self.fragment_shader is not None: self.fragment_shader.compileFlat() self.program = glCreateProgramObjectARB() if self.program == 0: raise GLSLException('failed to create program object') if self.vertex_shader is not None: self.vertex_shader.attachFlat(self.program) if self.fragment_shader is not None: self.fragment_shader.attachFlat(self.program) glLinkProgramARB(self.program) link_status = c_int(0) glGetObjectParameterivARB(self.program, GL_OBJECT_LINK_STATUS_ARB, byref(link_status)) if link_status.value == 0: err = glsl_log(self.program) glDeleteObjectARB(self.program) self.program = 0 raise GLSLException('failed to link shader', err) self.__class__._uloc_ = {} self.__class__._vloc_ = {} return self.program def prog(self): if self.program: return self.program return self.link() def install(self): p = self.prog() if p != 0: glUseProgramObjectARB(p) def uninstall(self): glUseProgramObjectARB(0) def uniformLoc(self, var): try: return self.__class__._uloc_[var] except: if self.program == 0: self.link() self.__class__._uloc_[var] = v = glGetUniformLocationARB(self.program, var) return v def uset1F(self, var, x): glUniform1fARB(self.uniformLoc(var), x) def uset2F(self, var, x, y): glUniform2fARB(self.uniformLoc(var), x, y) def uset3F(self, var, x, y, z): glUniform3fARB(self.uniformLoc(var), x, y, z) def uset4F(self, var, x, y, z, w): glUniform4fARB(self.uniformLoc(var), x, y, z, w) def uset1I(self, var, x): glUniform1iARB(self.uniformLoc(var), x) def uset3I(self, var, x, y, z): glUniform1iARB(self.uniformLoc(var), x, y, z) def usetM4F(self, var, m): pass # glUniform1iARB(self.uniformLoc(var), x, y, z) def usetTex(self, var, u, v): glUniform1iARB(self.uniformLoc(var), u) glActiveTexture(GL_TEXTURE0 + u) glBindTexture(v.gl_tgt, v.gl_id) __all__ = ['VertexShader', 'FragmentShader', 'ShaderProgram', 'GLSLException']
Python
'''Wrapper for avformat Generated with: ../tools/wraptypes/wrap.py /usr/include/ffmpeg/avformat.h -o lib_avformat.py .. Then hacked. DON'T REGENERATE. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * from avcodec import get_library _lib = get_library('avformat') _int_types = (c_int16, c_int32) if hasattr(ctypes, 'c_int64'): # Some builds of ctypes apparently do not have c_int64 # defined; it's a pretty good bet that these builds do not # have 64-bit pointers. _int_types += (ctypes.c_int64,) for t in _int_types: if sizeof(t) == sizeof(c_size_t): c_ptrdiff_t = t class c_void(Structure): # c_void_p is a buggy return type, converting to int, so # POINTER(None) == c_void_p is actually written as # POINTER(c_void), so it can be treated as a real pointer. _fields_ = [('dummy', c_int)] LIBAVFORMAT_BUILD = 4621 # /usr/include/ffmpeg/avformat.h:8 LIBAVFORMAT_VERSION_INT = 0 # /usr/include/ffmpeg/avformat.h:10 LIBAVFORMAT_VERSION = 0 # /usr/include/ffmpeg/avformat.h:11 class struct_AVPacket(Structure): __slots__ = [ 'pts', 'dts', 'data', 'size', 'stream_index', 'flags', 'duration', 'destruct', 'priv', ] struct_AVPacket._fields_ = [ ('pts', c_int64), ('dts', c_int64), ('data', POINTER(c_uint8)), ('size', c_int), ('stream_index', c_int), ('flags', c_int), ('duration', c_int), ('destruct', POINTER(CFUNCTYPE(None, POINTER(struct_AVPacket)))), ('priv', POINTER(None)), ] AVPacket = struct_AVPacket # /usr/include/ffmpeg/avformat.h:42 PKT_FLAG_KEY = 1 # /usr/include/ffmpeg/avformat.h:43 # /usr/include/ffmpeg/avformat.h:45 av_destruct_packet_nofree = _lib.av_destruct_packet_nofree av_destruct_packet_nofree.restype = None av_destruct_packet_nofree.argtypes = [POINTER(AVPacket)] # /usr/include/ffmpeg/avformat.h:58 av_new_packet = _lib.av_new_packet av_new_packet.restype = c_int av_new_packet.argtypes = [POINTER(AVPacket), c_int] # /usr/include/ffmpeg/avformat.h:59 av_dup_packet = _lib.av_dup_packet av_dup_packet.restype = c_int av_dup_packet.argtypes = [POINTER(AVPacket)] class struct_AVFrac(Structure): __slots__ = [ 'val', 'num', 'den', ] struct_AVFrac._fields_ = [ ('val', c_int64), ('num', c_int64), ('den', c_int64), ] AVFrac = struct_AVFrac # /usr/include/ffmpeg/avformat.h:80 # /usr/include/ffmpeg/avformat.h:82 av_frac_init = _lib.av_frac_init av_frac_init.restype = None av_frac_init.argtypes = [POINTER(AVFrac), c_int64, c_int64, c_int64] # /usr/include/ffmpeg/avformat.h:83 av_frac_add = _lib.av_frac_add av_frac_add.restype = None av_frac_add.argtypes = [POINTER(AVFrac), c_int64] # /usr/include/ffmpeg/avformat.h:84 av_frac_set = _lib.av_frac_set av_frac_set.restype = None av_frac_set.argtypes = [POINTER(AVFrac), c_int64] class struct_AVProbeData(Structure): __slots__ = [ 'filename', 'buf', 'buf_size', ] struct_AVProbeData._fields_ = [ ('filename', c_char_p), ('buf', POINTER(c_ubyte)), ('buf_size', c_int), ] AVProbeData = struct_AVProbeData # /usr/include/ffmpeg/avformat.h:96 AVPROBE_SCORE_MAX = 100 # /usr/include/ffmpeg/avformat.h:98 class struct_AVFormatParameters(Structure): __slots__ = [ 'frame_rate', 'frame_rate_base', 'sample_rate', 'channels', 'width', 'height', 'pix_fmt', 'image_format', 'channel', 'device', 'standard', 'mpeg2ts_raw', 'mpeg2ts_compute_pcr', 'initial_pause', 'video_codec_id', 'audio_codec_id', ] enum_PixelFormat = c_int class struct_AVImageFormat(Structure): __slots__ = [ ] struct_AVImageFormat._fields_ = [ ('_opaque_struct', c_int) ] enum_CodecID = c_int struct_AVFormatParameters._fields_ = [ ('frame_rate', c_int), ('frame_rate_base', c_int), ('sample_rate', c_int), ('channels', c_int), ('width', c_int), ('height', c_int), ('pix_fmt', enum_PixelFormat), ('image_format', POINTER(struct_AVImageFormat)), ('channel', c_int), ('device', c_char_p), ('standard', c_char_p), ('mpeg2ts_raw', c_int), ('mpeg2ts_compute_pcr', c_int), ('initial_pause', c_int), ('video_codec_id', enum_CodecID), ('audio_codec_id', enum_CodecID), ] AVFormatParameters = struct_AVFormatParameters # /usr/include/ffmpeg/avformat.h:120 AVFMT_NOFILE = 1 # /usr/include/ffmpeg/avformat.h:122 AVFMT_NEEDNUMBER = 2 # /usr/include/ffmpeg/avformat.h:123 AVFMT_SHOW_IDS = 8 # /usr/include/ffmpeg/avformat.h:124 AVFMT_RAWPICTURE = 32 # /usr/include/ffmpeg/avformat.h:125 class struct_AVOutputFormat(Structure): __slots__ = [ 'name', 'long_name', 'mime_type', 'extensions', 'priv_data_size', 'audio_codec', 'video_codec', 'write_header', 'write_packet', 'write_trailer', 'flags', 'set_parameters', 'interleave_packet', 'next', ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] struct_AVOutputFormat._fields_ = [ ('name', c_char_p), ('long_name', c_char_p), ('mime_type', c_char_p), ('extensions', c_char_p), ('priv_data_size', c_int), ('audio_codec', enum_CodecID), ('video_codec', enum_CodecID), ('write_header', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext)))), ('write_packet', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext), POINTER(AVPacket)))), ('write_trailer', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext)))), ('flags', c_int), ('set_parameters', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext), POINTER(AVFormatParameters)))), ('interleave_packet', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext), POINTER(AVPacket), POINTER(AVPacket), c_int))), ('next', POINTER(struct_AVOutputFormat)), ] AVOutputFormat = struct_AVOutputFormat # /usr/include/ffmpeg/avformat.h:148 class struct_AVInputFormat(Structure): __slots__ = [ 'name', 'long_name', 'priv_data_size', 'read_probe', 'read_header', 'read_packet', 'read_close', 'read_seek', 'read_timestamp', 'flags', 'extensions', 'value', 'read_play', 'read_pause', 'next', ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVFormatContext(Structure): __slots__ = [ ] struct_AVFormatContext._fields_ = [ ('_opaque_struct', c_int) ] struct_AVInputFormat._fields_ = [ ('name', c_char_p), ('long_name', c_char_p), ('priv_data_size', c_int), ('read_probe', POINTER(CFUNCTYPE(c_int, POINTER(AVProbeData)))), ('read_header', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext), POINTER(AVFormatParameters)))), ('read_packet', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext), POINTER(AVPacket)))), ('read_close', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext)))), ('read_seek', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext), c_int, c_int64, c_int))), ('read_timestamp', POINTER(CFUNCTYPE(c_int64, POINTER(struct_AVFormatContext), c_int, POINTER(c_int64), c_int64))), ('flags', c_int), ('extensions', c_char_p), ('value', c_int), ('read_play', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext)))), ('read_pause', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVFormatContext)))), ('next', POINTER(struct_AVInputFormat)), ] AVInputFormat = struct_AVInputFormat # /usr/include/ffmpeg/avformat.h:203 AVINDEX_KEYFRAME = 1 # /usr/include/ffmpeg/avformat.h:208 class struct_AVIndexEntry(Structure): __slots__ = [ 'pos', 'timestamp', 'flags', 'min_distance', ] struct_AVIndexEntry._fields_ = [ ('pos', c_int64), ('timestamp', c_int64), ('flags', c_int), ('min_distance', c_int), ] AVIndexEntry = struct_AVIndexEntry # /usr/include/ffmpeg/avformat.h:212 class struct_AVStream(Structure): __slots__ = [ 'index', 'id', 'codec', 'r_frame_rate', 'r_frame_rate_base', 'priv_data', 'codec_info_duration', 'codec_info_nb_frames', 'pts', 'time_base', 'pts_wrap_bits', 'stream_copy', 'discard', 'quality', 'start_time', 'duration', 'need_parsing', 'parser', 'cur_dts', 'last_IP_duration', 'last_IP_pts', 'index_entries', 'nb_index_entries', 'index_entries_allocated_size', ] class struct_AVCodecContext(Structure): __slots__ = [ 'av_class', 'bit_rate', 'bit_rate_tolerance', 'flags', 'sub_id', 'me_method', 'extradata', 'extradata_size', 'frame_rate', 'width', 'height', 'gop_size', 'pix_fmt', 'rate_emu', 'draw_horiz_band', 'sample_rate', 'channels', 'sample_fmt', 'frame_size', 'frame_number', 'real_pict_num', 'delay', 'qcompress', 'qblur', 'qmin', 'qmax', 'max_qdiff', 'max_b_frames', 'b_quant_factor', 'rc_strategy', 'b_frame_strategy', 'hurry_up', 'codec', 'priv_data', 'rtp_mode', 'rtp_payload_size', 'rtp_callback', 'mv_bits', 'header_bits', 'i_tex_bits', 'p_tex_bits', 'i_count', 'p_count', 'skip_count', 'misc_bits', 'frame_bits', 'opaque', 'codec_name', 'codec_type', 'codec_id', 'codec_tag', 'workaround_bugs', 'luma_elim_threshold', 'chroma_elim_threshold', 'strict_std_compliance', 'b_quant_offset', 'error_resilience', 'get_buffer', 'release_buffer', 'has_b_frames', 'block_align', 'parse_only', 'mpeg_quant', 'stats_out', 'stats_in', 'rc_qsquish', 'rc_qmod_amp', 'rc_qmod_freq', 'rc_override', 'rc_override_count', 'rc_eq', 'rc_max_rate', 'rc_min_rate', 'rc_buffer_size', 'rc_buffer_aggressivity', 'i_quant_factor', 'i_quant_offset', 'rc_initial_cplx', 'dct_algo', 'lumi_masking', 'temporal_cplx_masking', 'spatial_cplx_masking', 'p_masking', 'dark_masking', 'unused', 'idct_algo', 'slice_count', 'slice_offset', 'error_concealment', 'dsp_mask', 'bits_per_sample', 'prediction_method', 'sample_aspect_ratio', 'coded_frame', 'debug', 'debug_mv', 'error', 'mb_qmin', 'mb_qmax', 'me_cmp', 'me_sub_cmp', 'mb_cmp', 'ildct_cmp', 'dia_size', 'last_predictor_count', 'pre_me', 'me_pre_cmp', 'pre_dia_size', 'me_subpel_quality', 'get_format', 'dtg_active_format', 'me_range', 'frame_rate_base', 'intra_quant_bias', 'inter_quant_bias', 'color_table_id', 'internal_buffer_count', 'internal_buffer', 'global_quality', 'coder_type', 'context_model', 'slice_flags', 'xvmc_acceleration', 'mb_decision', 'intra_matrix', 'inter_matrix', 'stream_codec_tag', 'scenechange_threshold', 'lmin', 'lmax', 'palctrl', 'noise_reduction', 'reget_buffer', 'rc_initial_buffer_occupancy', 'inter_threshold', 'flags2', 'error_rate', 'antialias_algo', 'quantizer_noise_shaping', 'thread_count', 'execute', 'thread_opaque', 'me_threshold', 'mb_threshold', 'intra_dc_precision', 'nsse_weight', 'skip_top', 'skip_bottom', 'profile', 'level', 'lowres', 'coded_width', 'coded_height', 'frame_skip_threshold', 'frame_skip_factor', 'frame_skip_exp', 'frame_skip_cmp', 'border_masking', 'mb_lmin', 'mb_lmax', ] class struct_AVCLASS(Structure): __slots__ = [ ] struct_AVCLASS._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVCLASS(Structure): __slots__ = [ ] struct_AVCLASS._fields_ = [ ('_opaque_struct', c_int) ] AVClass = struct_AVCLASS # /usr/include/ffmpeg/avcodec.h:728 class struct_AVFrame(Structure): __slots__ = [ 'data', 'linesize', 'base', 'key_frame', 'pict_type', 'pts', 'coded_picture_number', 'display_picture_number', 'quality', 'age', 'reference', 'qscale_table', 'qstride', 'mbskip_table', 'motion_val', 'mb_type', 'motion_subsample_log2', 'opaque', 'error', 'type', 'repeat_pict', 'qscale_type', 'interlaced_frame', 'top_field_first', 'pan_scan', 'palette_has_changed', 'buffer_hints', 'dct_coeff', 'ref_index', ] class struct_AVPanScan(Structure): __slots__ = [ 'id', 'width', 'height', 'position', ] struct_AVPanScan._fields_ = [ ('id', c_int), ('width', c_int), ('height', c_int), ('position', (c_int16 * 2) * 3), ] AVPanScan = struct_AVPanScan # /usr/include/ffmpeg/avcodec.h:474 struct_AVFrame._fields_ = [ ('data', POINTER(c_uint8) * 4), ('linesize', c_int * 4), ('base', POINTER(c_uint8) * 4), ('key_frame', c_int), ('pict_type', c_int), ('pts', c_int64), ('coded_picture_number', c_int), ('display_picture_number', c_int), ('quality', c_int), ('age', c_int), ('reference', c_int), ('qscale_table', POINTER(c_int8)), ('qstride', c_int), ('mbskip_table', POINTER(c_uint8)), ('motion_val', POINTER(c_int16 * 2) * 2), ('mb_type', POINTER(c_uint32)), ('motion_subsample_log2', c_uint8), ('opaque', POINTER(None)), ('error', c_uint64 * 4), ('type', c_int), ('repeat_pict', c_int), ('qscale_type', c_int), ('interlaced_frame', c_int), ('top_field_first', c_int), ('pan_scan', POINTER(AVPanScan)), ('palette_has_changed', c_int), ('buffer_hints', c_int), ('dct_coeff', POINTER(c_short)), ('ref_index', POINTER(c_int8) * 2), ] AVFrame = struct_AVFrame # /usr/include/ffmpeg/avcodec.h:721 enum_SampleFormat = c_int class struct_AVCodec(Structure): __slots__ = [ ] struct_AVCodec._fields_ = [ ('_opaque_struct', c_int) ] enum_CodecType = c_int class struct_RcOverride(Structure): __slots__ = [ 'start_frame', 'end_frame', 'qscale', 'quality_factor', ] struct_RcOverride._fields_ = [ ('start_frame', c_int), ('end_frame', c_int), ('qscale', c_int), ('quality_factor', c_float), ] RcOverride = struct_RcOverride # /usr/include/ffmpeg/avcodec.h:308 class struct_AVRational(Structure): __slots__ = [ 'num', 'den', ] struct_AVRational._fields_ = [ ('num', c_int), ('den', c_int), ] AVRational = struct_AVRational # /usr/include/ffmpeg/rational.h:38 class struct_AVPaletteControl(Structure): __slots__ = [ ] struct_AVPaletteControl._fields_ = [ ('_opaque_struct', c_int) ] struct_AVCodecContext._fields_ = [ ('av_class', POINTER(AVClass)), ('bit_rate', c_int), ('bit_rate_tolerance', c_int), ('flags', c_int), ('sub_id', c_int), ('me_method', c_int), ('extradata', POINTER(None)), ('extradata_size', c_int), ('frame_rate', c_int), ('width', c_int), ('height', c_int), ('gop_size', c_int), ('pix_fmt', enum_PixelFormat), ('rate_emu', c_int), ('draw_horiz_band', POINTER(CFUNCTYPE(None, POINTER(struct_AVCodecContext), POINTER(AVFrame), c_int * 4, c_int, c_int, c_int))), ('sample_rate', c_int), ('channels', c_int), ('sample_fmt', enum_SampleFormat), ('frame_size', c_int), ('frame_number', c_int), ('real_pict_num', c_int), ('delay', c_int), ('qcompress', c_float), ('qblur', c_float), ('qmin', c_int), ('qmax', c_int), ('max_qdiff', c_int), ('max_b_frames', c_int), ('b_quant_factor', c_float), ('rc_strategy', c_int), ('b_frame_strategy', c_int), ('hurry_up', c_int), ('codec', POINTER(struct_AVCodec)), ('priv_data', POINTER(None)), ('rtp_mode', c_int), ('rtp_payload_size', c_int), ('rtp_callback', POINTER(CFUNCTYPE(None, POINTER(struct_AVCodecContext), POINTER(None), c_int, c_int))), ('mv_bits', c_int), ('header_bits', c_int), ('i_tex_bits', c_int), ('p_tex_bits', c_int), ('i_count', c_int), ('p_count', c_int), ('skip_count', c_int), ('misc_bits', c_int), ('frame_bits', c_int), ('opaque', POINTER(None)), ('codec_name', c_char * 32), ('codec_type', enum_CodecType), ('codec_id', enum_CodecID), ('codec_tag', c_uint), ('workaround_bugs', c_int), ('luma_elim_threshold', c_int), ('chroma_elim_threshold', c_int), ('strict_std_compliance', c_int), ('b_quant_offset', c_float), ('error_resilience', c_int), ('get_buffer', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVCodecContext), POINTER(AVFrame)))), ('release_buffer', POINTER(CFUNCTYPE(None, POINTER(struct_AVCodecContext), POINTER(AVFrame)))), ('has_b_frames', c_int), ('block_align', c_int), ('parse_only', c_int), ('mpeg_quant', c_int), ('stats_out', c_char_p), ('stats_in', c_char_p), ('rc_qsquish', c_float), ('rc_qmod_amp', c_float), ('rc_qmod_freq', c_int), ('rc_override', POINTER(RcOverride)), ('rc_override_count', c_int), ('rc_eq', c_char_p), ('rc_max_rate', c_int), ('rc_min_rate', c_int), ('rc_buffer_size', c_int), ('rc_buffer_aggressivity', c_float), ('i_quant_factor', c_float), ('i_quant_offset', c_float), ('rc_initial_cplx', c_float), ('dct_algo', c_int), ('lumi_masking', c_float), ('temporal_cplx_masking', c_float), ('spatial_cplx_masking', c_float), ('p_masking', c_float), ('dark_masking', c_float), ('unused', c_int), ('idct_algo', c_int), ('slice_count', c_int), ('slice_offset', POINTER(c_int)), ('error_concealment', c_int), ('dsp_mask', c_uint), ('bits_per_sample', c_int), ('prediction_method', c_int), ('sample_aspect_ratio', AVRational), ('coded_frame', POINTER(AVFrame)), ('debug', c_int), ('debug_mv', c_int), ('error', c_uint64 * 4), ('mb_qmin', c_int), ('mb_qmax', c_int), ('me_cmp', c_int), ('me_sub_cmp', c_int), ('mb_cmp', c_int), ('ildct_cmp', c_int), ('dia_size', c_int), ('last_predictor_count', c_int), ('pre_me', c_int), ('me_pre_cmp', c_int), ('pre_dia_size', c_int), ('me_subpel_quality', c_int), ('get_format', POINTER(CFUNCTYPE(enum_PixelFormat, POINTER(struct_AVCodecContext), POINTER(enum_PixelFormat)))), ('dtg_active_format', c_int), ('me_range', c_int), ('frame_rate_base', c_int), ('intra_quant_bias', c_int), ('inter_quant_bias', c_int), ('color_table_id', c_int), ('internal_buffer_count', c_int), ('internal_buffer', POINTER(None)), ('global_quality', c_int), ('coder_type', c_int), ('context_model', c_int), ('slice_flags', c_int), ('xvmc_acceleration', c_int), ('mb_decision', c_int), ('intra_matrix', POINTER(c_uint16)), ('inter_matrix', POINTER(c_uint16)), ('stream_codec_tag', c_uint), ('scenechange_threshold', c_int), ('lmin', c_int), ('lmax', c_int), ('palctrl', POINTER(struct_AVPaletteControl)), ('noise_reduction', c_int), ('reget_buffer', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVCodecContext), POINTER(AVFrame)))), ('rc_initial_buffer_occupancy', c_int), ('inter_threshold', c_int), ('flags2', c_int), ('error_rate', c_int), ('antialias_algo', c_int), ('quantizer_noise_shaping', c_int), ('thread_count', c_int), ('execute', POINTER(CFUNCTYPE(c_int, POINTER(struct_AVCodecContext), CFUNCTYPE(c_int, POINTER(struct_AVCodecContext), POINTER(None)), POINTER(POINTER(None)), POINTER(c_int), c_int))), ('thread_opaque', POINTER(None)), ('me_threshold', c_int), ('mb_threshold', c_int), ('intra_dc_precision', c_int), ('nsse_weight', c_int), ('skip_top', c_int), ('skip_bottom', c_int), ('profile', c_int), ('level', c_int), ('lowres', c_int), ('coded_width', c_int), ('coded_height', c_int), ('frame_skip_threshold', c_int), ('frame_skip_factor', c_int), ('frame_skip_exp', c_int), ('frame_skip_cmp', c_int), ('border_masking', c_float), ('mb_lmin', c_int), ('mb_lmax', c_int), ] AVCodecContext = struct_AVCodecContext # /usr/include/ffmpeg/avcodec.h:1883 class struct_AVCodecParserContext(Structure): __slots__ = [ ] struct_AVCodecParserContext._fields_ = [ ('_opaque_struct', c_int) ] struct_AVStream._fields_ = [ ('index', c_int), ('id', c_int), ('codec', AVCodecContext), ('r_frame_rate', c_int), ('r_frame_rate_base', c_int), ('priv_data', POINTER(None)), ('codec_info_duration', c_int64), ('codec_info_nb_frames', c_int), ('pts', AVFrac), ('time_base', AVRational), ('pts_wrap_bits', c_int), ('stream_copy', c_int), ('discard', c_int), ('quality', c_float), ('start_time', c_int64), ('duration', c_int64), ('need_parsing', c_int), ('parser', POINTER(struct_AVCodecParserContext)), ('cur_dts', c_int64), ('last_IP_duration', c_int), ('last_IP_pts', c_int64), ('index_entries', POINTER(AVIndexEntry)), ('nb_index_entries', c_int), ('index_entries_allocated_size', c_int), ] AVStream = struct_AVStream # /usr/include/ffmpeg/avformat.h:256 AVFMTCTX_NOHEADER = 1 # /usr/include/ffmpeg/avformat.h:258 MAX_STREAMS = 20 # /usr/include/ffmpeg/avformat.h:261 class struct_AVFormatContext(Structure): __slots__ = [ 'av_class', 'iformat', 'oformat', 'priv_data', 'pb', 'nb_streams', 'streams', 'filename', 'timestamp', 'title', 'author', 'copyright', 'comment', 'album', 'year', 'track', 'genre', 'ctx_flags', 'packet_buffer', 'start_time', 'duration', 'file_size', 'bit_rate', 'cur_st', 'cur_ptr', 'cur_len', 'cur_pkt', 'data_offset', 'index_built', 'mux_rate', 'packet_size', 'preload', 'max_delay', ] class struct_anon_17(Structure): __slots__ = [ 'buffer', 'buffer_size', 'buf_ptr', 'buf_end', 'opaque', 'read_packet', 'write_packet', 'seek', 'pos', 'must_flush', 'eof_reached', 'write_flag', 'is_streamed', 'max_packet_size', 'checksum', 'checksum_ptr', 'update_checksum', 'error', ] offset_t = c_int64 # /usr/include/ffmpeg/avio.h:6 struct_anon_17._fields_ = [ ('buffer', POINTER(c_ubyte)), ('buffer_size', c_int), ('buf_ptr', POINTER(c_ubyte)), ('buf_end', POINTER(c_ubyte)), ('opaque', POINTER(None)), ('read_packet', POINTER(CFUNCTYPE(c_int, POINTER(None), POINTER(c_uint8), c_int))), ('write_packet', POINTER(CFUNCTYPE(c_int, POINTER(None), POINTER(c_uint8), c_int))), ('seek', POINTER(CFUNCTYPE(c_int, POINTER(None), offset_t, c_int))), ('pos', offset_t), ('must_flush', c_int), ('eof_reached', c_int), ('write_flag', c_int), ('is_streamed', c_int), ('max_packet_size', c_int), ('checksum', c_ulong), ('checksum_ptr', POINTER(c_ubyte)), ('update_checksum', POINTER(CFUNCTYPE(c_ulong, c_ulong, POINTER(c_uint8), c_uint))), ('error', c_int), ] ByteIOContext = struct_anon_17 # /usr/include/ffmpeg/avio.h:86 class struct_AVPacketList(Structure): __slots__ = [ ] struct_AVPacketList._fields_ = [ ('_opaque_struct', c_int) ] struct_AVFormatContext._fields_ = [ ('av_class', POINTER(AVClass)), ('iformat', POINTER(struct_AVInputFormat)), ('oformat', POINTER(struct_AVOutputFormat)), ('priv_data', POINTER(None)), ('pb', ByteIOContext), ('nb_streams', c_int), ('streams', POINTER(AVStream) * 20), ('filename', c_char * 1024), ('timestamp', c_int64), ('title', c_char * 512), ('author', c_char * 512), ('copyright', c_char * 512), ('comment', c_char * 512), ('album', c_char * 512), ('year', c_int), ('track', c_int), ('genre', c_char * 32), ('ctx_flags', c_int), ('packet_buffer', POINTER(struct_AVPacketList)), ('start_time', c_int64), ('duration', c_int64), ('file_size', c_int64), ('bit_rate', c_int), ('cur_st', POINTER(AVStream)), ('cur_ptr', POINTER(c_uint8)), ('cur_len', c_int), ('cur_pkt', AVPacket), ('data_offset', c_int64), ('index_built', c_int), ('mux_rate', c_int), ('packet_size', c_int), ('preload', c_int), ('max_delay', c_int), ] AVFormatContext = struct_AVFormatContext # /usr/include/ffmpeg/avformat.h:321 class struct_AVPacketList(Structure): __slots__ = [ 'pkt', 'next', ] struct_AVPacketList._fields_ = [ ('pkt', AVPacket), ('next', POINTER(struct_AVPacketList)), ] AVPacketList = struct_AVPacketList # /usr/include/ffmpeg/avformat.h:326 class struct_AVInputImageContext(Structure): __slots__ = [ ] struct_AVInputImageContext._fields_ = [ ('_opaque_struct', c_int) ] class struct_AVInputImageContext(Structure): __slots__ = [ ] struct_AVInputImageContext._fields_ = [ ('_opaque_struct', c_int) ] AVInputImageContext = struct_AVInputImageContext # /usr/include/ffmpeg/avformat.h:333 class struct_AVImageInfo(Structure): __slots__ = [ 'pix_fmt', 'width', 'height', 'interleaved', 'pict', ] class struct_AVPicture(Structure): __slots__ = [ 'data', 'linesize', ] struct_AVPicture._fields_ = [ ('data', POINTER(c_uint8) * 4), ('linesize', c_int * 4), ] AVPicture = struct_AVPicture # /usr/include/ffmpeg/avcodec.h:1975 struct_AVImageInfo._fields_ = [ ('pix_fmt', enum_PixelFormat), ('width', c_int), ('height', c_int), ('interleaved', c_int), ('pict', AVPicture), ] AVImageInfo = struct_AVImageInfo # /usr/include/ffmpeg/avformat.h:341 AVIMAGE_INTERLEAVED = 1 # /usr/include/ffmpeg/avformat.h:344 class struct_AVImageFormat(Structure): __slots__ = [ 'name', 'extensions', 'img_probe', 'img_read', 'supported_pixel_formats', 'img_write', 'flags', 'next', ] struct_AVImageFormat._fields_ = [ ('name', c_char_p), ('extensions', c_char_p), ('img_probe', POINTER(CFUNCTYPE(c_int, POINTER(AVProbeData)))), ('img_read', POINTER(CFUNCTYPE(c_int, POINTER(ByteIOContext), CFUNCTYPE(c_int, POINTER(None), POINTER(AVImageInfo)), POINTER(None)))), ('supported_pixel_formats', c_int), ('img_write', POINTER(CFUNCTYPE(c_int, POINTER(ByteIOContext), POINTER(AVImageInfo)))), ('flags', c_int), ('next', POINTER(struct_AVImageFormat)), ] AVImageFormat = struct_AVImageFormat # /usr/include/ffmpeg/avformat.h:362 # /usr/include/ffmpeg/avformat.h:364 av_register_image_format = _lib.av_register_image_format av_register_image_format.restype = None av_register_image_format.argtypes = [POINTER(AVImageFormat)] # /usr/include/ffmpeg/avformat.h:365 av_probe_image_format = _lib.av_probe_image_format av_probe_image_format.restype = POINTER(AVImageFormat) av_probe_image_format.argtypes = [POINTER(AVProbeData)] # /usr/include/ffmpeg/avformat.h:366 guess_image_format = _lib.guess_image_format guess_image_format.restype = POINTER(AVImageFormat) guess_image_format.argtypes = [c_char_p] # /usr/include/ffmpeg/avformat.h:367 av_guess_image2_codec = _lib.av_guess_image2_codec av_guess_image2_codec.restype = enum_CodecID av_guess_image2_codec.argtypes = [c_char_p] # /usr/include/ffmpeg/avformat.h:368 av_read_image = _lib.av_read_image av_read_image.restype = c_int av_read_image.argtypes = [POINTER(ByteIOContext), c_char_p, POINTER(AVImageFormat), CFUNCTYPE(c_int, POINTER(None), POINTER(AVImageInfo)), POINTER(None)] # /usr/include/ffmpeg/avformat.h:371 av_write_image = _lib.av_write_image av_write_image.restype = c_int av_write_image.argtypes = [POINTER(ByteIOContext), POINTER(AVImageFormat), POINTER(AVImageInfo)] # /usr/include/ffmpeg/avformat.h:528 av_register_input_format = _lib.av_register_input_format av_register_input_format.restype = None av_register_input_format.argtypes = [POINTER(AVInputFormat)] # /usr/include/ffmpeg/avformat.h:529 av_register_output_format = _lib.av_register_output_format av_register_output_format.restype = None av_register_output_format.argtypes = [POINTER(AVOutputFormat)] # /usr/include/ffmpeg/avformat.h:530 guess_stream_format = _lib.guess_stream_format guess_stream_format.restype = POINTER(AVOutputFormat) guess_stream_format.argtypes = [c_char_p, c_char_p, c_char_p] # /usr/include/ffmpeg/avformat.h:532 guess_format = _lib.guess_format guess_format.restype = POINTER(AVOutputFormat) guess_format.argtypes = [c_char_p, c_char_p, c_char_p] # /usr/include/ffmpeg/avformat.h:534 av_guess_codec = _lib.av_guess_codec av_guess_codec.restype = enum_CodecID av_guess_codec.argtypes = [POINTER(AVOutputFormat), c_char_p, c_char_p, c_char_p, enum_CodecType] class struct__IO_FILE(Structure): __slots__ = [ ] struct__IO_FILE._fields_ = [ ('_opaque_struct', c_int) ] class struct__IO_FILE(Structure): __slots__ = [ ] struct__IO_FILE._fields_ = [ ('_opaque_struct', c_int) ] FILE = struct__IO_FILE # /usr/include/gentoo-multilib/amd64/stdio.h:46 # /usr/include/ffmpeg/avformat.h:537 av_hex_dump = _lib.av_hex_dump av_hex_dump.restype = None av_hex_dump.argtypes = [POINTER(FILE), POINTER(c_uint8), c_int] # /usr/include/ffmpeg/avformat.h:538 av_pkt_dump = _lib.av_pkt_dump av_pkt_dump.restype = None av_pkt_dump.argtypes = [POINTER(FILE), POINTER(AVPacket), c_int] # /usr/include/ffmpeg/avformat.h:540 av_register_all = _lib.av_register_all av_register_all.restype = None av_register_all.argtypes = [] class struct_FifoBuffer(Structure): __slots__ = [ 'buffer', 'rptr', 'wptr', 'end', ] struct_FifoBuffer._fields_ = [ ('buffer', POINTER(c_uint8)), ('rptr', POINTER(c_uint8)), ('wptr', POINTER(c_uint8)), ('end', POINTER(c_uint8)), ] FifoBuffer = struct_FifoBuffer # /usr/include/ffmpeg/avformat.h:545 # /usr/include/ffmpeg/avformat.h:547 fifo_init = _lib.fifo_init fifo_init.restype = c_int fifo_init.argtypes = [POINTER(FifoBuffer), c_int] # /usr/include/ffmpeg/avformat.h:548 fifo_free = _lib.fifo_free fifo_free.restype = None fifo_free.argtypes = [POINTER(FifoBuffer)] # /usr/include/ffmpeg/avformat.h:549 fifo_size = _lib.fifo_size fifo_size.restype = c_int fifo_size.argtypes = [POINTER(FifoBuffer), POINTER(c_uint8)] # /usr/include/ffmpeg/avformat.h:550 fifo_read = _lib.fifo_read fifo_read.restype = c_int fifo_read.argtypes = [POINTER(FifoBuffer), POINTER(c_uint8), c_int, POINTER(POINTER(c_uint8))] # /usr/include/ffmpeg/avformat.h:551 fifo_write = _lib.fifo_write fifo_write.restype = None fifo_write.argtypes = [POINTER(FifoBuffer), POINTER(c_uint8), c_int, POINTER(POINTER(c_uint8))] # /usr/include/ffmpeg/avformat.h:552 put_fifo = _lib.put_fifo put_fifo.restype = c_int put_fifo.argtypes = [POINTER(ByteIOContext), POINTER(FifoBuffer), c_int, POINTER(POINTER(c_uint8))] # /usr/include/ffmpeg/avformat.h:553 fifo_realloc = _lib.fifo_realloc fifo_realloc.restype = None fifo_realloc.argtypes = [POINTER(FifoBuffer), c_uint] # /usr/include/ffmpeg/avformat.h:556 av_find_input_format = _lib.av_find_input_format av_find_input_format.restype = POINTER(AVInputFormat) av_find_input_format.argtypes = [c_char_p] # /usr/include/ffmpeg/avformat.h:557 av_probe_input_format = _lib.av_probe_input_format av_probe_input_format.restype = POINTER(AVInputFormat) av_probe_input_format.argtypes = [POINTER(AVProbeData), c_int] # /usr/include/ffmpeg/avformat.h:558 av_open_input_stream = _lib.av_open_input_stream av_open_input_stream.restype = c_int av_open_input_stream.argtypes = [POINTER(POINTER(AVFormatContext)), POINTER(ByteIOContext), c_char_p, POINTER(AVInputFormat), POINTER(AVFormatParameters)] # /usr/include/ffmpeg/avformat.h:561 av_open_input_file = _lib.av_open_input_file av_open_input_file.restype = c_int av_open_input_file.argtypes = [POINTER(POINTER(AVFormatContext)), c_char_p, POINTER(AVInputFormat), c_int, POINTER(AVFormatParameters)] # /usr/include/ffmpeg/avformat.h:566 av_alloc_format_context = _lib.av_alloc_format_context av_alloc_format_context.restype = POINTER(AVFormatContext) av_alloc_format_context.argtypes = [] AVERROR_UNKNOWN = -1 # /usr/include/ffmpeg/avformat.h:568 AVERROR_IO = -2 # /usr/include/ffmpeg/avformat.h:569 AVERROR_NUMEXPECTED = -3 # /usr/include/ffmpeg/avformat.h:570 AVERROR_INVALIDDATA = -4 # /usr/include/ffmpeg/avformat.h:571 AVERROR_NOMEM = -5 # /usr/include/ffmpeg/avformat.h:572 AVERROR_NOFMT = -6 # /usr/include/ffmpeg/avformat.h:573 AVERROR_NOTSUPP = -7 # /usr/include/ffmpeg/avformat.h:574 # /usr/include/ffmpeg/avformat.h:576 av_find_stream_info = _lib.av_find_stream_info av_find_stream_info.restype = c_int av_find_stream_info.argtypes = [POINTER(AVFormatContext)] # /usr/include/ffmpeg/avformat.h:577 av_read_packet = _lib.av_read_packet av_read_packet.restype = c_int av_read_packet.argtypes = [POINTER(AVFormatContext), POINTER(AVPacket)] # /usr/include/ffmpeg/avformat.h:578 av_read_frame = _lib.av_read_frame av_read_frame.restype = c_int av_read_frame.argtypes = [POINTER(AVFormatContext), POINTER(AVPacket)] # /usr/include/ffmpeg/avformat.h:579 av_seek_frame = _lib.av_seek_frame av_seek_frame.restype = c_int av_seek_frame.argtypes = [POINTER(AVFormatContext), c_int, c_int64, c_int] # /usr/include/ffmpeg/avformat.h:580 av_read_play = _lib.av_read_play av_read_play.restype = c_int av_read_play.argtypes = [POINTER(AVFormatContext)] # /usr/include/ffmpeg/avformat.h:581 av_read_pause = _lib.av_read_pause av_read_pause.restype = c_int av_read_pause.argtypes = [POINTER(AVFormatContext)] # /usr/include/ffmpeg/avformat.h:582 av_close_input_file = _lib.av_close_input_file av_close_input_file.restype = None av_close_input_file.argtypes = [POINTER(AVFormatContext)] # /usr/include/ffmpeg/avformat.h:583 av_new_stream = _lib.av_new_stream av_new_stream.restype = POINTER(AVStream) av_new_stream.argtypes = [POINTER(AVFormatContext), c_int] # /usr/include/ffmpeg/avformat.h:584 av_set_pts_info = _lib.av_set_pts_info av_set_pts_info.restype = None av_set_pts_info.argtypes = [POINTER(AVStream), c_int, c_int, c_int] AVSEEK_FLAG_BACKWARD = 1 # /usr/include/ffmpeg/avformat.h:587 AVSEEK_FLAG_BYTE = 2 # /usr/include/ffmpeg/avformat.h:589 # /usr/include/ffmpeg/avformat.h:592 av_find_default_stream_index = _lib.av_find_default_stream_index av_find_default_stream_index.restype = c_int av_find_default_stream_index.argtypes = [POINTER(AVFormatContext)] # /usr/include/ffmpeg/avformat.h:593 av_index_search_timestamp = _lib.av_index_search_timestamp av_index_search_timestamp.restype = c_int av_index_search_timestamp.argtypes = [POINTER(AVStream), c_int64, c_int] # /usr/include/ffmpeg/avformat.h:594 av_add_index_entry = _lib.av_add_index_entry av_add_index_entry.restype = c_int av_add_index_entry.argtypes = [POINTER(AVStream), c_int64, c_int64, c_int, c_int] # /usr/include/ffmpeg/avformat.h:596 av_seek_frame_binary = _lib.av_seek_frame_binary av_seek_frame_binary.restype = c_int av_seek_frame_binary.argtypes = [POINTER(AVFormatContext), c_int, c_int64, c_int] # /usr/include/ffmpeg/avformat.h:599 av_set_parameters = _lib.av_set_parameters av_set_parameters.restype = c_int av_set_parameters.argtypes = [POINTER(AVFormatContext), POINTER(AVFormatParameters)] # /usr/include/ffmpeg/avformat.h:600 av_write_header = _lib.av_write_header av_write_header.restype = c_int av_write_header.argtypes = [POINTER(AVFormatContext)] # /usr/include/ffmpeg/avformat.h:601 av_write_frame = _lib.av_write_frame av_write_frame.restype = c_int av_write_frame.argtypes = [POINTER(AVFormatContext), POINTER(AVPacket)] # /usr/include/ffmpeg/avformat.h:602 av_interleaved_write_frame = _lib.av_interleaved_write_frame av_interleaved_write_frame.restype = c_int av_interleaved_write_frame.argtypes = [POINTER(AVFormatContext), POINTER(AVPacket)] # /usr/include/ffmpeg/avformat.h:604 av_write_trailer = _lib.av_write_trailer av_write_trailer.restype = c_int av_write_trailer.argtypes = [POINTER(AVFormatContext)] # /usr/include/ffmpeg/avformat.h:606 dump_format = _lib.dump_format dump_format.restype = None dump_format.argtypes = [POINTER(AVFormatContext), c_int, c_char_p, c_int] # /usr/include/ffmpeg/avformat.h:610 parse_image_size = _lib.parse_image_size parse_image_size.restype = c_int parse_image_size.argtypes = [POINTER(c_int), POINTER(c_int), c_char_p] # /usr/include/ffmpeg/avformat.h:611 parse_frame_rate = _lib.parse_frame_rate parse_frame_rate.restype = c_int parse_frame_rate.argtypes = [POINTER(c_int), POINTER(c_int), c_char_p] # /usr/include/ffmpeg/avformat.h:612 parse_date = _lib.parse_date parse_date.restype = c_int64 parse_date.argtypes = [c_char_p, c_int] # /usr/include/ffmpeg/avformat.h:614 av_gettime = _lib.av_gettime av_gettime.restype = c_int64 av_gettime.argtypes = [] FFM_PACKET_SIZE = 4096 # /usr/include/ffmpeg/avformat.h:617 # /usr/include/ffmpeg/avformat.h:618 ffm_read_write_index = _lib.ffm_read_write_index ffm_read_write_index.restype = offset_t ffm_read_write_index.argtypes = [c_int] # /usr/include/ffmpeg/avformat.h:619 ffm_write_write_index = _lib.ffm_write_write_index ffm_write_write_index.restype = None ffm_write_write_index.argtypes = [c_int, offset_t] # /usr/include/ffmpeg/avformat.h:620 ffm_set_write_index = _lib.ffm_set_write_index ffm_set_write_index.restype = None ffm_set_write_index.argtypes = [POINTER(AVFormatContext), offset_t, offset_t] # /usr/include/ffmpeg/avformat.h:622 find_info_tag = _lib.find_info_tag find_info_tag.restype = c_int find_info_tag.argtypes = [c_char_p, c_int, c_char_p, c_char_p] # /usr/include/ffmpeg/avformat.h:624 get_frame_filename = _lib.get_frame_filename get_frame_filename.restype = c_int get_frame_filename.argtypes = [c_char_p, c_int, c_char_p, c_int] # /usr/include/ffmpeg/avformat.h:626 filename_number_test = _lib.filename_number_test filename_number_test.restype = c_int filename_number_test.argtypes = [c_char_p] __all__ = ['LIBAVFORMAT_BUILD', 'LIBAVFORMAT_VERSION_INT', 'LIBAVFORMAT_VERSION', 'AVPacket', 'PKT_FLAG_KEY', 'av_destruct_packet_nofree', 'av_new_packet', 'av_dup_packet', 'AVFrac', 'av_frac_init', 'av_frac_add', 'av_frac_set', 'AVProbeData', 'AVPROBE_SCORE_MAX', 'AVFormatParameters', 'AVFMT_NOFILE', 'AVFMT_NEEDNUMBER', 'AVFMT_SHOW_IDS', 'AVFMT_RAWPICTURE', 'AVOutputFormat', 'AVInputFormat', 'AVINDEX_KEYFRAME', 'AVIndexEntry', 'AVStream', 'AVFMTCTX_NOHEADER', 'MAX_STREAMS', 'AVFormatContext', 'AVPacketList', 'AVInputImageContext', 'AVImageInfo', 'AVIMAGE_INTERLEAVED', 'AVImageFormat', 'av_register_image_format', 'av_probe_image_format', 'guess_image_format', 'av_guess_image2_codec', 'av_read_image', 'av_write_image', 'mpegps_init', 'mpegts_init', 'rm_init', 'crc_init', 'img_init', 'img2_init', 'asf_init', 'avienc_init', 'avidec_init', 'swf_init', 'mov_init', 'movenc_init', 'flvenc_init', 'flvdec_init', 'jpeg_init', 'gif_init', 'au_init', 'amr_init', 'ff_wav_init', 'pcm_read_seek', 'raw_init', 'mp3_init', 'yuv4mpeg_init', 'ogg_init', 'ff_dv_init', 'ffm_init', 'redir_open', 'fourxm_init', 'str_init', 'roq_init', 'ipmovie_init', 'nut_init', 'wc3_init', 'westwood_init', 'film_init', 'idcin_init', 'flic_init', 'vmd_init', 'matroska_init', 'sol_init', 'ea_init', 'nsvdec_init', 'av_register_input_format', 'av_register_output_format', 'guess_stream_format', 'guess_format', 'av_guess_codec', 'av_hex_dump', 'av_pkt_dump', 'av_register_all', 'FifoBuffer', 'fifo_init', 'fifo_free', 'fifo_size', 'fifo_read', 'fifo_write', 'put_fifo', 'fifo_realloc', 'av_find_input_format', 'av_probe_input_format', 'av_open_input_stream', 'av_open_input_file', 'av_alloc_format_context', 'AVERROR_UNKNOWN', 'AVERROR_IO', 'AVERROR_NUMEXPECTED', 'AVERROR_INVALIDDATA', 'AVERROR_NOMEM', 'AVERROR_NOFMT', 'AVERROR_NOTSUPP', 'av_find_stream_info', 'av_read_packet', 'av_read_frame', 'av_seek_frame', 'av_read_play', 'av_read_pause', 'av_close_input_file', 'av_new_stream', 'av_set_pts_info', 'AVSEEK_FLAG_BACKWARD', 'AVSEEK_FLAG_BYTE', 'av_find_default_stream_index', 'av_index_search_timestamp', 'av_add_index_entry', 'av_seek_frame_binary', 'av_set_parameters', 'av_write_header', 'av_write_frame', 'av_interleaved_write_frame', 'av_write_trailer', 'dump_format', 'parse_image_size', 'parse_frame_rate', 'parse_date', 'av_gettime', 'FFM_PACKET_SIZE', 'ffm_read_write_index', 'ffm_write_write_index', 'ffm_set_write_index', 'find_info_tag', 'get_frame_filename', 'filename_number_test', 'video_grab_init', 'audio_init', 'dv1394_init', 'dc1394_init']
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import code import sys import traceback import pyglet.event import pyglet.text from pyglet.window import key from pyglet.gl import * class Console(object): def __init__(self, width, height, globals=None, locals=None): self.font = pyglet.text.default_font_factory.get_font('bitstream vera sans mono', 12) self.lines = [] self.buffer = '' self.pre_buffer = '' self.prompt = '>>> ' self.prompt2 = '... ' self.globals = globals self.locals = locals self.write_pending = '' self.width, self.height = (width, height) self.max_lines = self.height / self.font.glyph_height - 1 self.write('pyglet command console\n') self.write('Version %s\n' % __version__) def on_key_press(self, symbol, modifiers): # TODO cursor control / line editing if modifiers & key.key.MOD_CTRL and symbol == key.key.C: self.buffer = '' self.pre_buffer = '' return if symbol == key.key.ENTER: self.write('%s%s\n' % (self.get_prompt(), self.buffer)) self.execute(self.pre_buffer + self.buffer) self.buffer = '' return if symbol == key.key.BACKSPACE: self.buffer = self.buffer[:-1] return return EVENT_UNHANDLED def on_text(self, text): if ' ' <= text <= '~': self.buffer += text if 0xae <= ord(text) <= 0xff: self.buffer += text def write(self, text): if self.write_pending: text = self.write_pending + text self.write_pending = '' if type(text) in (str, unicode): text = text.split('\n') if text[-1] != '': self.write_pending = text[-1] del text[-1] self.lines = [pyglet.text.layout_text(line.strip(), font=self.font) for line in text] + self.lines if len(self.lines) > self.max_lines: del self.lines[-1] def execute(self, input): old_stderr, old_stdout = sys.stderr, sys.stdout sys.stderr = sys.stdout = self try: c = code.compile_command(input, '<pyglet console>') if c is None: self.pre_buffer = '%s\n' % input else: self.pre_buffer = '' result = eval(c, self.globals, self.locals) if result is not None: self.write('%r\n' % result) except: traceback.print_exc() self.pre_buffer = '' sys.stderr = old_stderr sys.stdout = old_stdout def get_prompt(self): if self.pre_buffer: return self.prompt2 return self.prompt __last = None def draw(self): pyglet.text.begin() glPushMatrix() glTranslatef(0, self.height, 0) for line in self.lines[::-1]: line.draw() glTranslatef(0, -self.font.glyph_height, 0) line = self.get_prompt() + self.buffer if self.__last is None or line != self.__last[0]: self.__last = (line, pyglet.text.layout_text(line.strip(), font=self.font)) self.__last[1].draw() glPopMatrix() pyglet.text.end() if __name__ == '__main__': from pyglet.window import * from pyglet.window.event import * from pyglet import clock w1 = Window(width=600, height=400) console = Console(w1.width, w1.height) w1.push_handlers(console) c = clock.Clock() glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, w1.width, 0, w1.height, -1, 1) glEnable(GL_COLOR_MATERIAL) glMatrixMode(GL_MODELVIEW) glClearColor(1, 1, 1, 1) while not w1.has_exit: c.set_fps(60) w1.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) console.draw() w1.flip()
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', ], # Add _ prefix to the names of temporary build dirs options={ 'build': {'build_base': '_build'}, 'sdist': {'dist_dir': '_dist'}, } ) 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/env python from __future__ import print_function import os import os.path as op import sys import shutil import inspect import webbrowser from subprocess import call, check_output THIS_DIR = op.dirname(op.abspath(__file__)) DOC_DIR = op.join(THIS_DIR, 'doc') def clean(): dirs = [op.join(DOC_DIR, '_build')] for d in dirs: print(' Removing:', d) shutil.rmtree(d, ignore_errors=True) def docs(): make_bin = 'make.exe' if sys.platform=='win32' else 'make' call([make_bin, 'html'], cwd=DOC_DIR) if '--no-open' not in sys.argv: webbrowser.open('file://'+op.abspath(DOC_DIR)+'/_build/html/index.html') if __name__=='__main__': avail_cmds = dict(filter(lambda kv: not kv[0].startswith('_') and inspect.isfunction(kv[1]) and kv[1].__module__ == '__main__', locals().items())) try: cmd = avail_cmds[sys.argv[1]] except Exception as exc: print(type(exc).__name__, ':', exc) print('Usage:', op.basename(sys.argv[0]), '<command>') print(' where commands are:', ', '.join(avail_cmds)) else: cmd()
Python
#!/usr/bin/env python '''Test that window move event works correctly. Expected behaviour: One window will be opened. Move the window and ensure that the location printed to the terminal is correct. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_MOVE(unittest.TestCase): def on_move(self, x, y): print 'Window moved to %dx%d.' % (x, y) def test_move(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window size can be set. Expected behaviour: One window will be opened. The window's dimensions will be printed to the terminal. - press "x" to increase the width - press "X" to decrease the width - press "y" to increase the height - press "Y" to decrease the height You should see a green border inside the window but no red. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key import window_util class WINDOW_SET_SIZE(unittest.TestCase): def on_key_press(self, symbol, modifiers): delta = 20 if modifiers & key.MOD_SHIFT: delta = -delta if symbol == key.X: self.width += delta elif symbol == key.Y: self.height += delta self.w.set_size(self.width, self.height) print 'Window size set to %dx%d.' % (self.width, self.height) def test_set_size(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, resizable=True) w.push_handlers(self) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that vsync can be set. Expected behaviour: A window will alternate between red and green fill. - Press "v" to toggle vsync on/off. "Tearing" should only be visible when vsync is off (as indicated at the terminal). Not all video drivers support vsync. On Linux, check the output of `tools/info.py`: - If GLX_SGI_video_sync extension is present, should work as expected. - If GLX_MESA_swap_control extension is present, should work as expected. - If GLX_SGI_swap_control extension is present, vsync can be enabled, but once enabled, it cannot be switched off (there will be no error message). - If none of these extensions are present, vsync is not supported by your driver, but no error message or warning will be printed. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from pyglet import window from pyglet.window import key from pyglet.gl import * class WINDOW_SET_VSYNC(unittest.TestCase): colors = [(1, 0, 0, 1), (0, 1, 0, 1)] color_index = 0 def open_window(self): return window.Window(200, 200, vsync=False) def on_key_press(self, symbol, modifiers): if symbol == key.V: vsync = not self.w1.vsync self.w1.set_vsync(vsync) print 'vsync is %r' % self.w1.vsync def draw_window(self, window, colour): window.switch_to() glClearColor(*colour) glClear(GL_COLOR_BUFFER_BIT) window.flip() def test_open_window(self): self.w1 = self.open_window() self.w1.push_handlers(self) print 'vsync is %r' % self.w1.vsync while not self.w1.has_exit: self.color_index = 1 - self.color_index self.draw_window(self.w1, self.colors[self.color_index]) self.w1.dispatch_events() self.w1.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that multiple windows share objects by default. This test is non-interactive. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from ctypes import * from pyglet import window from pyglet.gl import * __noninteractive = True class CONTEXT_SHARE(unittest.TestCase): def create_context(self, share): display = window.get_platform().get_default_display() screen = display.get_default_screen() config = screen.get_best_config() return config.create_context(share) def test_context_share_list(self): w1 = window.Window(200, 200) try: w1.switch_to() glist = glGenLists(1) glNewList(glist, GL_COMPILE) glLoadIdentity() glEndList() self.assertTrue(glIsList(glist)) except: w1.close() raise w2 = window.Window(200, 200) try: w2.switch_to() self.assertTrue(glIsList(glist)) finally: w1.close() w2.close() def test_context_noshare_list(self): w1 = window.Window(200, 200) try: w1.switch_to() glist = glGenLists(1) glNewList(glist, GL_COMPILE) glLoadIdentity() glEndList() self.assertTrue(glIsList(glist)) except: w1.close() raise w2 = window.Window(200, 200, context=self.create_context(None)) try: w2.set_visible(True) w2.switch_to() self.assertTrue(not glIsList(glist)) finally: w1.close() w2.close() def test_context_share_texture(self): w1 = window.Window(200, 200) try: w1.switch_to() textures = c_uint() glGenTextures(1, byref(textures)) texture = textures.value glBindTexture(GL_TEXTURE_2D, texture) data = (c_ubyte * 4)() glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, data) self.assertTrue(glIsTexture(texture)) except: w1.close() raise w2 = window.Window(200, 200) try: w2.switch_to() self.assertTrue(glIsTexture(texture)) glDeleteTextures(1, byref(textures)) self.assertTrue(not glIsTexture(texture)) w1.switch_to() self.assertTrue(not glIsTexture(texture)) finally: w1.close() w2.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # $Id:$ from pyglet.gl import * def draw_client_border(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, window.width, 0, window.height, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def rect(x1, y1, x2, y2): glBegin(GL_LINE_LOOP) glVertex2f(x1, y1) glVertex2f(x2, y1) glVertex2f(x2, y2) glVertex2f(x1, y2) glEnd() glColor3f(1, 0, 0) rect(-2, -2, window.width + 2, window.height + 2) glColor3f(0, 1, 0) rect(1, 1, window.width - 2, window.height - 2)
Python
#!/usr/bin/env python '''Test that a window can be opened fullscreen. Expected behaviour: A fullscreen window will be created, with a flat purple colour. - Press 'g' to leave fullscreen mode and create a window. - Press 'f' to re-enter fullscreen mode. - All events will be printed to the console. Ensure that mouse, keyboard and activation/deactivation events are all correct. Close either window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import pyglet.window from pyglet import window from pyglet.window.event import WindowEventLogger from pyglet.window import key from pyglet.gl import * class WINDOW_INITIAL_FULLSCREEN(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.F: print 'Setting fullscreen.' self.w.set_fullscreen(True) elif symbol == key.G: print 'Leaving fullscreen.' self.w.set_fullscreen(False) def on_expose(self): glClearColor(1, 0, 1, 1) glClear(GL_COLOR_BUFFER_BIT) self.w.flip() def test_initial_fullscreen(self): self.w = window.Window(fullscreen=True) self.w.push_handlers(self) self.w.push_handlers(WindowEventLogger()) self.on_expose() while not self.w.has_exit: self.w.dispatch_events() self.w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window icon can be set. Expected behaviour: One window will be opened. It will have an icon depicting a yellow "A". Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import image from pyglet import window from pyglet.window import key from os.path import join, dirname icon_file = join(dirname(__file__), 'icon1.png') class WINDOW_SET_ICON(unittest.TestCase): def test_set_icon(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.set_icon(image.load(icon_file)) glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that a window can have multisample. A window will be opened containing two rotating squares. Initially, there will be no multisampling (the edges will look "jaggy"). Press: * M to toggle multisampling on/off * S to increase samples (2, 4, 6, 8, 10, ...) * Shift+S to decrease samples Each time sample_buffers or samples is modified, the window will be recreated. Watch the console for success and failure messages. If the multisample options are not supported, a "Failure" message will be printed and the window will be left as-is. Press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_OPEN.py 750 2007-03-17 01:16:12Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import window from pyglet import clock from pyglet.window import key class WINDOW_MULTISAMPLE(unittest.TestCase): win = None width = 640 height = 480 soft_multisample = True multisample = False samples = 2 def set_window(self): oldwindow = self.win try: if self.multisample: print 'Attempting samples=%d...' % self.samples, config = Config(sample_buffers=1, samples=self.samples, double_buffer=True) else: print 'Disabling multisample...', config = Config(double_buffer=True) self.win = window.Window(self.width, self.height, vsync=True, config=config) self.win.switch_to() self.win.push_handlers(self.on_key_press) if self.multisample: if self.soft_multisample: glEnable(GL_MULTISAMPLE_ARB) else: glDisable(GL_MULTISAMPLE_ARB) if oldwindow: oldwindow.close() print 'Success.' except window.NoSuchConfigException: print 'Failed.' def on_key_press(self, symbol, modifiers): mod = 1 if modifiers & key.MOD_SHIFT: mod = -1 if symbol == key.M: self.multisample = not self.multisample self.set_window() if symbol == key.S: self.samples += 2 * mod self.samples = max(2, self.samples) self.set_window() # Another test: try enabling/disabling GL_MULTISAMPLE_ARB... # seems to have no effect if samples > 4. if symbol == key.N: self.soft_multisample = not self.soft_multisample if self.soft_multisample: print 'Enabling GL_MULTISAMPLE_ARB' glEnable(GL_MULTISAMPLE_ARB) else: print 'Disabling GL_MULTISAMPLE_ARB' glDisable(GL_MULTISAMPLE_ARB) def render(self): self.win.switch_to() size = self.height / 4 glClear(GL_COLOR_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glLoadIdentity() glTranslatef(self.width/2, self.height/2, 0) glRotatef(self.angle, 0, 0, 1) glColor3f(1, 0, 0) glBegin(GL_QUADS) glVertex2f(-size, -size) glVertex2f(size, -size) glVertex2f(size, size) glVertex2f(-size, size) glEnd() glRotatef(-self.angle * 2, 0, 0, 1) glColor4f(0, 1, 0, 0.5) glBegin(GL_QUADS) glVertex2f(-size, -size) glVertex2f(size, -size) glVertex2f(size, size) glVertex2f(-size, size) glEnd() def test_multisample(self): self.set_window() self.angle = 0 clock.set_fps_limit(30) while not self.win.has_exit: dt = clock.tick() self.angle += dt self.win.dispatch_events() self.render() self.win.flip() self.win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that text events work correctly. Expected behaviour: One window will be opened. Type into this window and check the console output for text events. - Repeated when keys are held down - Motion events (e.g., arrow keys, HOME/END, etc) are reported - Select events (motion + SHIFT) are reported - Non-keyboard text entry is used (e.g., pen or international palette). - Combining characters do not generate events, but the modified character is sent. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class EVENT_KEYPRESS(unittest.TestCase): def on_text(self, text): print 'Typed %r' % text def on_text_motion(self, motion): print 'Motion %s' % key.motion_string(motion) def on_text_motion_select(self, motion): print 'Select %s' % key.motion_string(motion) def test_text(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # $Id:$ import unittest import time class BaseEventSequence(unittest.TestCase): next_sequence = 0 last_sequence = 0 finished = False timeout = 2 start_time = time.time() def check_sequence(self, sequence, name): if self.next_sequence == 0 and sequence != 0: return if sequence == 0: self.start_time = time.time() if not self.finished: if self.next_sequence != sequence: print 'ERROR: %s out of order' % name else: print 'OK: %s' % name self.next_sequence += 1 if self.next_sequence > self.last_sequence: self.finished = True def check_timeout(self): self.assertTrue(time.time() - self.start_time < self.timeout)
Python
#!/usr/bin/env python '''Test that screens can be selected for fullscreen. Expected behaviour: One window will be created fullscreen on the primary screen. When you close this window, another will open on the next screen, and so on until all screens have been tested. Each screen will be filled with a different color: - Screen 0: Red - Screen 1: Green - Screen 2: Blue - Screen 3: Purple The test will end when all screens have been tested. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.gl import * colours = [ (1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, 0, 1, 1)] class MULTIPLE_SCREEN(unittest.TestCase): def open_next_window(self): screen = self.screens[self.index] self.w = window.Window(screen=screen, fullscreen=True) def on_expose(self): self.w.switch_to() glClearColor(*colours[self.index]) glClear(GL_COLOR_BUFFER_BIT) self.w.flip() def test_multiple_screen(self): display = window.get_platform().get_default_display() self.screens = display.get_screens() for i in range(len(self.screens)): self.index = i self.open_next_window() self.on_expose() while not self.w.has_exit: self.w.dispatch_events() self.w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that a non-resizable window's size can be set. Expected behaviour: One window will be opened. The window's dimensions will be printed to the terminal. - press "x" to increase the width - press "X" to decrease the width - press "y" to increase the height - press "Y" to decrease the height You should see a green border inside the window but no red. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key import window_util class WINDOW_FIXED_SET_SIZE(unittest.TestCase): def on_key_press(self, symbol, modifiers): delta = 20 if modifiers & key.MOD_SHIFT: delta = -delta if symbol == key.X: self.width += delta elif symbol == key.Y: self.height += delta self.w.set_size(self.width, self.height) print 'Window size set to %dx%d.' % (self.width, self.height) def test_set_size(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that image mouse cursor can be set. Expected behaviour: One window will be opened. The mouse cursor in the window will be a custom cursor. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from pyglet.gl import * from pyglet import image from pyglet import window from os.path import join, dirname cursor_file = join(dirname(__file__), 'cursor.png') class WINDOW_SET_MOUSE_CURSOR(unittest.TestCase): def on_mouse_motion(self, x, y, dx, dy): print 'on_mousemotion(x=%f, y=%f, dx=%f, dy=%f)' % (x, y, dx, dy) def test_set_mouse_cursor(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) img = image.load(cursor_file) w.set_mouse_cursor(window.ImageMouseCursor(img, 4, 28)) w.push_handlers(self) glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that the window can be hidden and shown. Expected behaviour: One window will be opened. Every 5 seconds it will toggle between hidden and shown. Press escape or close the window to finish the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window from pyglet.window.event import WindowEventLogger class WINDOW_SET_VISIBLE(unittest.TestCase): def test_set_visible(self): w = window.Window(200, 200) w.push_handlers(WindowEventLogger()) last_time = time.time() visible = True while not w.has_exit: if time.time() - last_time > 5: visible = not visible w.set_visible(visible) last_time = time.time() print 'Set visibility to %r.' % visible w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that exclusive keyboard mode can be set. Expected behaviour: One window will be opened. Press 'e' to enable exclusive mode and 'E' to disable exclusive mode. In exclusive mode: - Pressing system keys, the Expose keys, etc., should have no effect besides displaying as keyboard events. - On OS X, the Power switch is not disabled (though this is possible if desired, see source). - On OS X, the menu bar and dock will disappear during keyboard exclusive mode. - On Windows, only Alt+Tab is disabled. A user can still switch away using Ctrl+Escape, Alt+Escape, the Windows key or Ctrl+Alt+Del. - Switching to another application (i.e., with the mouse) should make these keys work normally again until this application regains focus. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class WINDOW_SET_EXCLUSIVE_KEYBOARD(unittest.TestCase): def on_key_press(self, symbol, modifiers): print 'Pressed %s with modifiers %s' % \ (key.symbol_string(symbol), key.modifiers_string(modifiers)) if symbol == key.E: exclusive = not (modifiers & key.MOD_SHIFT) self.w.set_exclusive_keyboard(exclusive) print 'Exclusive keyboard is now %r' % exclusive def on_key_release(self, symbol, modifiers): print 'Released %s with modifiers %s' % \ (key.symbol_string(symbol), key.modifiers_string(modifiers)) def test_set_exclusive_keyboard(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse cursor can be set to a platform-dependent image. Expected behaviour: One window will be opened. Press the left and right arrow keys to cycle through the system mouse cursors. The current cursor selected will be printed to the terminal. Note that not all cursors are unique on each platform; for example, if a platform doesn't define a cursor for a given name, a suitable replacement (e.g., a plain arrow) will be used instead. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_VISIBLE.py 703 2007-02-28 14:18:00Z Alex.Holkner $' import unittest from pyglet import window from pyglet.window import key from pyglet.gl import * class WINDOW_SET_MOUSE_PLATFORM_CURSOR(unittest.TestCase): i = 0 def on_key_press(self, symbol, modifiers): names = [ self.w.CURSOR_DEFAULT, self.w.CURSOR_CROSSHAIR, self.w.CURSOR_HAND, self.w.CURSOR_HELP, self.w.CURSOR_NO, self.w.CURSOR_SIZE, self.w.CURSOR_SIZE_UP, self.w.CURSOR_SIZE_UP_RIGHT, self.w.CURSOR_SIZE_RIGHT, self.w.CURSOR_SIZE_DOWN_RIGHT, self.w.CURSOR_SIZE_DOWN, self.w.CURSOR_SIZE_DOWN_LEFT, self.w.CURSOR_SIZE_LEFT, self.w.CURSOR_SIZE_UP_LEFT, self.w.CURSOR_SIZE_UP_DOWN, self.w.CURSOR_SIZE_LEFT_RIGHT, self.w.CURSOR_TEXT, self.w.CURSOR_WAIT, self.w.CURSOR_WAIT_ARROW, ] if symbol == key.ESCAPE: self.w.on_close() if symbol == key.RIGHT: self.i = (self.i + 1) % len(names) elif symbol == key.LEFT: self.i = (self.i - 1) % len(names) cursor = self.w.get_system_mouse_cursor(names[self.i]) self.w.set_mouse_cursor(cursor) print 'Set cursor to "%s"' % names[self.i] return True def test_set_visible(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window style can be tool. Expected behaviour: One tool-styled window will be opened. Close the window to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import window class TEST_WINDOW_STYLE_TOOL(unittest.TestCase): def test_style_tool(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, style=window.Window.WINDOW_STYLE_TOOL) glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse motion event works correctly. Expected behaviour: One window will be opened. Move the mouse in and out of this window and ensure the absolute and relative coordinates are correct. - Absolute coordinates should have (0,0) at bottom-left of client area of window with positive y-axis pointing up and positive x-axis right. - Relative coordinates should be positive when moving up and right. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_MOUSEMOTION(unittest.TestCase): def on_mouse_motion(self, x, y, dx, dy): print 'Mouse at (%f, %f); relative (%f, %f).' % \ (x, y, dx, dy) def test_motion(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse drag event works correctly. Expected behaviour: One window will be opened. Click and drag with the mouse and ensure that buttons, coordinates and modifiers are reported correctly. Events should be generated even when the drag leaves the window. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from pyglet import window from pyglet.window.event import WindowEventLogger class EVENT_MOUSE_DRAG(unittest.TestCase): def test_mouse_drag(self): w = window.Window(200, 200) w.push_handlers(WindowEventLogger()) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that the window can be activated (focus set). Expected behaviour: One window will be opened. Every 5 seconds it will be activated; it should be come to the front and accept keyboard input (this will be shown on the terminal). On Windows XP, the taskbar icon may flash (indicating the application requires attention) rather than moving the window to the foreground. This is the correct behaviour. Press escape or close the window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window from pyglet.window.event import WindowEventLogger class WINDOW_ACTVATE(unittest.TestCase): def test_activate(self): w = window.Window(200, 200) w.push_handlers(WindowEventLogger()) last_time = time.time() while not w.has_exit: if time.time() - last_time > 5: w.activate() last_time = time.time() print 'Activated window.' w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window icon can be set for multiple sizes. Expected behaviour: One window will be opened. The window's icon depends on the icon size: 16x16 icon is a yellow "1" 32x32 icon is a purple "2" 48x48 icon is a cyan "3" 72x72 icon is a red "4" 128x128 icon is a blue "5" For other sizes, the operating system may select the closest match and scale it (Linux, Windows), or interpolate between two or more images (Mac OS X). Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import image from pyglet import window from pyglet.window import key import window_util from os.path import join, dirname icon_file1 = join(dirname(__file__), 'icon_size1.png') icon_file2 = join(dirname(__file__), 'icon_size2.png') icon_file3 = join(dirname(__file__), 'icon_size3.png') icon_file4 = join(dirname(__file__), 'icon_size4.png') icon_file5 = join(dirname(__file__), 'icon_size5.png') class WINDOW_SET_ICON_SIZES(unittest.TestCase): def test_set_icon_sizes(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.set_icon(image.load(icon_file1), image.load(icon_file2), image.load(icon_file3), image.load(icon_file4), image.load(icon_file5)) glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be minimized and maximized. Expected behaviour: One window will be opened. - press "x" to maximize the window. - press "n" to minimize the window. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class WINDOW_MINIMIZE_MAXIMIZE(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.X: self.w.maximize() print 'Window maximized.' elif symbol == key.N: self.w.minimize() print 'Window minimized.' def test_minimize_maximize(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, resizable=True) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # $Id:$ import unittest from pyglet import window import base_event_sequence __noninteractive = True class TEST_CLASS(base_event_sequence.BaseEventSequence): last_sequence = 3 def on_resize(self, width, height): self.check_sequence(1, 'on_resize') def on_show(self): self.check_sequence(2, 'on_show') def on_expose(self): self.check_sequence(3, 'on_expose') def test_method(self): win = window.Window(visible=False) win.dispatch_events() win.push_handlers(self) win.set_visible(True) self.check_sequence(0, 'begin') while not win.has_exit and not self.finished: win.dispatch_events() self.check_timeout() win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # $Id: $ import unittest from pyglet import window import base_event_sequence __noninteractive = True class TEST_CLASS(base_event_sequence.BaseEventSequence): last_sequence = 2 def on_resize(self, width, height): self.check_sequence(1, 'on_resize') def on_expose(self): self.check_sequence(2, 'on_expose') def test_method(self): win = window.Window() win.dispatch_events() win.push_handlers(self) win.set_fullscreen() self.check_sequence(0, 'begin') while not win.has_exit and not self.finished: win.dispatch_events() self.check_timeout() win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse enter and leave events work correctly. Expected behaviour: One window will be opened. Move the mouse in and out of this window and ensure the events displayed are correct. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_MOUSE_ENTER_LEAVE(unittest.TestCase): def on_mouse_enter(self, x, y): print 'Entered at %f, %f' % (x, y) def on_mouse_leave(self, x, y): print 'Left at %f, %f' % (x, y) def test_motion(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that a window can be opened. Expected behaviour: One small window will be opened coloured purple. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from pyglet import window from pyglet.gl import * class WINDOW_OPEN(unittest.TestCase): def open_window(self): return window.Window(200, 200) def draw_window(self, window, colour): window.switch_to() glClearColor(*colour) glClear(GL_COLOR_BUFFER_BIT) window.flip() def test_open_window(self): w1 = self.open_window() while not w1.has_exit: self.draw_window(w1, (1, 0, 1, 1)) w1.dispatch_events() w1.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be resized. Expected behaviour: One window will be opened. It should be resizable by the user. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import window from pyglet.window import key import window_util class WINDOW_RESIZABLE(unittest.TestCase): def test_resizable(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, resizable=True) glClearColor(1, 1, 1, 1) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that activate and deactivate events work correctly. Expected behaviour: One window will be opened. Clicking on the window should activate it, clicking on another window should deactivate it. Messages will be printed to the console for both events. On OS X you can also (de)activate a window with Command+Tab, or using Expose (F9) or the Dock. On Windows and most Linux window managers you can use Alt+Tab or the task bar. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_ACTIVATE_DEACTIVATE(unittest.TestCase): def on_activate(self): print 'Window activated.' def on_deactivate(self): print 'Window deactivated.' def test_activate_deactivate(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse button events work correctly. Expected behaviour: One window will be opened. Click within this window and check the console output for mouse events. - Buttons 1, 2, 4 correspond to left, middle, right, respectively. - No events for scroll wheel - Modifiers are correct Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class EVENT_BUTTON(unittest.TestCase): def on_mouse_press(self, x, y, button, modifiers): print 'Mouse button %d pressed at %f,%f with %s' % \ (button, x, y, key.modifiers_string(modifiers)) def on_mouse_release(self, x, y, button, modifiers): print 'Mouse button %d released at %f,%f with %s' % \ (button, x, y, key.modifiers_string(modifiers)) def test_button(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window expose event works correctly. Expected behaviour: One window will be opened. Uncovering the window from other windows or the edge of the screen should produce the expose event. Note that on OS X and other compositing window managers this event is equivalent to EVENT_SHOW. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_EXPOSE(unittest.TestCase): def on_expose(self): print 'Window exposed.' def test_expose(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that minimum and maximum window size can be set. Expected behaviour: One window will be opened. The window's dimensions will be printed to the terminal. Initially the window has no minimum or maximum size (besides any OS-enforced limit). - press "n" to set the minimum size to be the current size. - press "x" to set the maximum size to be the current size. You should see a green border inside the window but no red. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key import window_util class WINDOW_SET_MIN_MAX_SIZE(unittest.TestCase): def on_resize(self, width, height): print 'Window size is %dx%d.' % (width, height) self.width, self.height = width, height def on_key_press(self, symbol, modifiers): if symbol == key.N: self.w.set_minimum_size(self.width, self.height) print 'Minimum size set to %dx%d.' % (self.width, self.height) elif symbol == key.X: self.w.set_maximum_size(self.width, self.height) print 'Maximum size set to %dx%d.' % (self.width, self.height) def test_min_max_size(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, resizable=True) w.push_handlers(self) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window style can be borderless. Expected behaviour: One borderless window will be opened. Mouse click in the window to close it and end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import window from pyglet.window import key class WINDOW_TEST_STYLE_BORDERLESS(unittest.TestCase): def test_style_borderless(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, style=window.Window.WINDOW_STYLE_BORDERLESS) @w.event def on_mouse_press(*args): w.has_exit = True glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # $Id: $ import unittest from pyglet import window import base_event_sequence __noninteractive = True class TEST_CLASS(base_event_sequence.BaseEventSequence): last_sequence = 3 def on_resize(self, width, height): self.check_sequence(1, 'on_resize') def on_show(self): self.check_sequence(2, 'on_show') def on_expose(self): self.check_sequence(3, 'on_expose') def test_method(self): win = window.Window(fullscreen=True) win.push_handlers(self) self.check_sequence(0, 'begin') while not win.has_exit and not self.finished: win.dispatch_events() self.check_timeout() win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that key press and release events work correctly. Expected behaviour: One window will be opened. Type into this window and check the console output for key press and release events. Check that the correct key symbol and modifiers are reported. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class EVENT_KEYPRESS(unittest.TestCase): def on_key_press(self, symbol, modifiers): print 'Pressed %s with modifiers %s' % \ (key.symbol_string(symbol), key.modifiers_string(modifiers)) def on_key_release(self, symbol, modifiers): print 'Released %s with modifiers %s' % \ (key.symbol_string(symbol), key.modifiers_string(modifiers)) def test_keypress(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse cursor can be made visible and hidden. Expected behaviour: One window will be opened. Press 'v' to hide mouse cursor and 'V' to show mouse cursor. It should only affect the mouse when within the client area of the window. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from pyglet import window from pyglet.window import key class WINDOW_SET_MOUSE_VISIBLE(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.V: visible = (modifiers & key.MOD_SHIFT) self.w.set_mouse_visible(visible) print 'Mouse is now %s' % (visible and 'visible' or 'hidden') def on_mouse_motion(self, x, y, dx, dy): print 'on_mousemotion(x=%f, y=%f, dx=%f, dy=%f)' % (x, y, dx, dy) def test_set_visible(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that multiple windows can be opened. Expected behaviour: Two small windows will be opened, one coloured yellow and the other purple. Close either window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.gl import * class MULTIPLE_WINDOW_OPEN(unittest.TestCase): def open_window(self): return window.Window(200, 200) def draw_window(self, window, colour): window.switch_to() glClearColor(*colour) glClear(GL_COLOR_BUFFER_BIT) window.flip() def test_open_window(self): w1 = self.open_window() w2 = self.open_window() while not (w1.has_exit or w2.has_exit): self.draw_window(w1, (1, 0, 1, 1)) self.draw_window(w2, (1, 1, 0, 1)) w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be set fullscreen and back again. Expected behaviour: One window will be opened. - press "f" to enter fullscreen mode. - press "g" to leave fullscreen mode. All events will be printed to the terminal. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window.event import WindowEventLogger from pyglet.window import key from pyglet.gl import * class WINDOW_SET_FULLSCREEN(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.F: print 'Setting fullscreen.' self.w.set_fullscreen(True) elif symbol == key.G: print 'Leaving fullscreen.' self.w.set_fullscreen(False) def on_expose(self): glClearColor(1, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) self.w.flip() def test_set_fullscreen(self): self.w = w = window.Window(200, 200) w.push_handlers(self) w.push_handlers(WindowEventLogger()) self.on_expose() while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(400, 200, resizable=True) w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # $Id: $ import unittest from pyglet import window import base_event_sequence __noninteractive = True class TEST_CLASS(base_event_sequence.BaseEventSequence): last_sequence = 2 def on_resize(self, width, height): self.check_sequence(1, 'on_resize') def on_expose(self): self.check_sequence(2, 'on_expose') def test_method(self): win = window.Window(fullscreen=True) win.dispatch_events() win.push_handlers(self) win.set_fullscreen(False) self.check_sequence(0, 'begin') while not win.has_exit and not self.finished: win.dispatch_events() self.check_timeout() win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window.event import WindowEventLogger from pyglet.window import key from pyglet.gl import * import window_util class WINDOW_SET_FULLSCREEN(unittest.TestCase): def on_text(self, text): text = text[:1] i = ord(text) - ord('a') if 0 <= i < len(self.modes): print 'Switching to %s' % self.modes[i] self.w.screen.set_mode(self.modes[i]) def on_expose(self): glClearColor(1, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) window_util.draw_client_border(self.w) self.w.flip() def test_set_fullscreen(self): self.w = w = window.Window(200, 200) self.modes = w.screen.get_modes() print 'Press a letter to switch to the corresponding mode:' for i, mode in enumerate(self.modes): print '%s: %s' % (chr(i + ord('a')), mode) w.push_handlers(self) #w.push_handlers(WindowEventLogger()) self.on_expose() while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window location can be set. Expected behaviour: One window will be opened. The window's location will be printed to the terminal. - Use the arrow keys to move the window. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class WINDOW_SET_SIZE(unittest.TestCase): def on_key_press(self, symbol, modifiers): x, y = self.w.get_location() if symbol == key.LEFT: x -= 10 if symbol == key.RIGHT: x += 10 if symbol == key.UP: y -= 10 if symbol == key.DOWN: y += 10 self.w.set_location(x, y) print 'Window location set to %dx%d.' % (x, y) def test_set_size(self): self.w = w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window style can be dialog. Expected behaviour: One dialog-styled window will be opened. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import window from pyglet.window import key class TEST_WINDOW_STYLE_DIALOG(unittest.TestCase): def test_style_dialog(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, style=window.Window.WINDOW_STYLE_DIALOG) glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that exclusive mouse mode can be set. Expected behaviour: One window will be opened. Press 'e' to enable exclusive mode and 'E' to disable exclusive mode. In exclusive mode: - the mouse cursor should be invisible - moving the mouse should generate events with bogus x,y but correct dx and dy. - it should not be possible to switch applications with the mouse - if application loses focus (i.e., with keyboard), the mouse should operate normally again until focus is returned to the app, in which case it should hide again. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class WINDOW_SET_EXCLUSIVE_MOUSE(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.E: exclusive = not (modifiers & key.MOD_SHIFT) self.w.set_exclusive_mouse(exclusive) print 'Exclusive mouse is now %r' % exclusive def on_mouse_motion(self, x, y, dx, dy): print 'on_mousemotion(x=%f, y=%f, dx=%f, dy=%f)' % (x, y, dx, dy) def test_set_exclusive_mouse(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that close event works correctly. Expected behaviour: One window will be opened. Click the close button and ensure the event is printed to the terminal. The window should not close when you do this. Press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet import event w = None class EVENT_CLOSE(unittest.TestCase): def on_close(self): print 'Window close event.' return event.EVENT_HANDLED def on_key_press(self, symbol, mods): if symbol == window.key.ESCAPE: global w super(window.Window, w).on_close() def test_close(self): global w w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that resize event works correctly. Expected behaviour: One window will be opened. Resize the window and ensure that the dimensions printed to the terminal are correct. You should see a green border inside the window but no red. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window import window_util class EVENT_RESIZE(unittest.TestCase): def on_resize(self, width, height): print 'Window resized to %dx%d.' % (width, height) def test_resize(self): w = window.Window(200, 200, resizable=True) w.push_handlers(self) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse scroll event works correctly. Expected behaviour: One window will be opened. Move the scroll wheel and check that events are printed to console. Positive values are associated with scrolling up. Scrolling can also be side-to-side, for example with an Apple Mighty Mouse. The actual scroll value is dependent on your operating system user preferences. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_MOUSE_SCROLL(unittest.TestCase): def on_mouse_scroll(self, x, y, dx, dy): print 'Mouse scrolled (%f, %f) (x=%f, y=%f)' % (dx, dy, x, y) def test_mouse_scroll(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be set to and from various fullscreen sizes. Expected behaviour: One window will be opened. Press a number to switch to the corresponding fullscreen size; hold control and press a number to switch back to the corresponding window size: 0 - Default size 1 - 320x200 2 - 640x480 3 - 800x600 4 - 1024x768 5 - 1280x800 (widescreen) 6 - 1280x1024 In all cases the window bounds will be indicated by a green rectangle which should be completely visible. All events will be printed to the terminal. Press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window.event import WindowEventLogger from pyglet.window import key from pyglet.gl import * import window_util class WINDOW_SET_FULLSCREEN(unittest.TestCase): def on_key_press(self, symbol, modifiers): fullscreen = not modifiers & key.MOD_CTRL doing = fullscreen and 'Setting' or 'Restoring from' if symbol == key._0: print '%s default size' % doing self.w.set_fullscreen(fullscreen) return elif symbol == key._1: width, height = 320, 200 elif symbol == key._2: width, height = 640, 480 elif symbol == key._3: width, height = 800, 600 elif symbol == key._4: width, height = 1024, 768 elif symbol == key._5: width, height = 1280, 800 # 16:10 elif symbol == key._6: width, height = 1280, 1024 else: return print '%s width=%d, height=%d' % (doing, width, height) self.w.set_fullscreen(fullscreen, width=width, height=height) def on_expose(self): glClearColor(1, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) window_util.draw_client_border(self.w) self.w.flip() def test_set_fullscreen(self): self.w = w = window.Window(200, 200) w.push_handlers(self) w.push_handlers(WindowEventLogger()) self.on_expose() try: while not w.has_exit: w.dispatch_events() w.close() except SystemExit: # Child process on linux calls sys.exit(0) when it's done. pass if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # $Id: $ import unittest from pyglet import window import base_event_sequence __noninteractive = True class TEST_CLASS(base_event_sequence.BaseEventSequence): last_sequence = 3 def on_resize(self, width, height): self.check_sequence(1, 'on_resize') def on_show(self): self.check_sequence(2, 'on_show') def on_expose(self): self.check_sequence(3, 'on_expose') def test_method(self): win = window.Window() win.push_handlers(self) self.check_sequence(0, 'begin') while not win.has_exit and not self.finished: win.dispatch_events() self.check_timeout() win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that show and hide events work correctly. Expected behaviour: One window will be opened. There should be one shown event printed initially. Minimizing and restoring the window should produce hidden and shown events, respectively. On OS X the events should also be fired when the window is hidden and shown (using Command+H or the dock context menu). Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_SHOW_HIDE(unittest.TestCase): def on_show(self): print 'Window shown.' def on_hide(self): print 'Window hidden.' def test_show_hide(self): w = window.Window(200, 200, visible=False) w.push_handlers(self) w.set_visible() while not w.has_exit: w.dispatch_events() w.close() 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 20: 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. Python 3 -------- The tests have to be processed by 2to3 in order to run them with Python 3. This can be done with:: 2to3 --output-dir=tests3 -W -n tests And then run the tests int tests3 directory. ''' from __future__ import print_function __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__), '..')) from pyglet import compat_platform 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): options.tests_count += 1 if not options.capabilities.intersection(self.capabilities): options.tests_skipped += 1 options.log.debug('Capabilities mismatch. Skipping %s', self) return options.log.info('--- test (%d/%d) %s', options.tests_count, options.num_tests, 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) print("Running Test: %s (%d/%d)\n" % (self, options.tests_count, 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('Passed [Yn]: ') while user_result and user_result not in 'YyNn': print("Unrecognized response '%s'" % user_result) user_result = raw_input('Passed [Yn]: ') if user_result and user_result in 'Nn': 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(object): 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 def run(self, options, names=[]): if not names: components = [self.root] else: components = [] for name in names: if name not in self.names: options.log.error('Unknown test case or section "%s"', name) return False else: components.append(self.names[name]) options.num_tests = sum([c.num_tests() for c in components]) options.tests_count = 0 options.tests_skipped = 0 for component in components: component.test(options) print('-' * 78) return True 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', 'linux-compat': 'X11', 'win32': 'WIN', 'cygwin': 'WIN', 'darwin': 'OSX' } if compat_platform in platform_capabilities: capabilities.append(platform_capabilities[compat_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=20, 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('pyglet.compat_platform = %s', pyglet.compat_platform) options.log.info('Reading test plan from %s', options.plan) plan = TestPlan.from_file(options.plan) if not plan.run(options, args): options.log.error('Test run failed.') print('Test results are saved in log file:', options.log_file) if __name__ == '__main__': main()
Python
#!/usr/bin/env python """Tests immediate drawing. """ import unittest import pyglet from graphics_common import GraphicsGenericTestCase, get_feedback, GL_TRIANGLES __noninteractive = True class GraphicsImmediateTestCase(GraphicsGenericTestCase, unittest.TestCase): def get_feedback(self, data): return get_feedback(lambda: pyglet.graphics.draw(self.n_vertices, GL_TRIANGLES, *data)) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python """Tests immediate drawing using indexed data. """ import unittest import pyglet from graphics_common import GraphicsIndexedGenericTestCase, get_feedback, GL_TRIANGLES __noninteractive = True class GraphicsIndexedImmediateTestCase(GraphicsIndexedGenericTestCase, unittest.TestCase): def get_feedback(self, data): return get_feedback(lambda: pyglet.graphics.draw_indexed(self.n_vertices, GL_TRIANGLES, self.index_data, *data)) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python """Tests vertex list drawing. """ import unittest import pyglet from graphics_common import GraphicsGenericTestCase, get_feedback, GL_TRIANGLES __noninteractive = True class GraphicsVertexListTestCase(GraphicsGenericTestCase, unittest.TestCase): def get_feedback(self, data): vertex_list = pyglet.graphics.vertex_list(self.n_vertices, *data) return get_feedback(lambda: vertex_list.draw(GL_TRIANGLES)) 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 '''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 """Tests vertex list drawing using indexed data. """ import unittest import pyglet from graphics_common import GraphicsIndexedGenericTestCase, get_feedback, GL_TRIANGLES __noninteractive = True class GraphicsIndexedVertexListTestCase(GraphicsIndexedGenericTestCase, unittest.TestCase): def get_feedback(self, data): vertex_list = pyglet.graphics.vertex_list_indexed(self.n_vertices, self.index_data, *data) return get_feedback(lambda: vertex_list.draw(GL_TRIANGLES)) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python from abc import abstractmethod import random from collections import deque from pyglet.gl import * # http://stackoverflow.com/a/312464/931303 def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i+n] def get_feedback(func): feedback_buffer = (GLfloat * 8096)() # 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 class GraphicsGenericTestCase: """ A generic test for asserting vertices positions using openGL Feedback Buffer. This is not really a testcase because it cannot be tested alone. Use it by subclassing it with unittest.TestCase. It has one abstract method that the subclass must overwrite. """ def setUp(self): # has to be a multiple of 3 because of the Feedback buffer. # has to be a multiple of 2 because of indexed data subclass. self.n_vertices = 36 self.v3f_data = [v/float(self.n_vertices*3) for v in range(self.n_vertices * 3)] self.v2f_data = [v/float(self.n_vertices*2) for v in range(self.n_vertices * 2)] self.c4f_data = [v/float(self.n_vertices*4) for v in range(self.n_vertices * 4)] self.c3f_data = [v/float(self.n_vertices*3) for v in range(self.n_vertices * 3)] self.t4f_data = [v/float(self.n_vertices*4) for v in range(self.n_vertices * 4)] self.t3f_data = [v/float(self.n_vertices*3) for v in range(self.n_vertices * 3)] self.t2f_data = [v/float(self.n_vertices*2) for v in range(self.n_vertices * 2)] @staticmethod def _are_equal(expected, result): """ Compares that two lists are equal within an error. Returns True if they are equal and False otherwise. """ for e, r in zip(expected, result): if abs(e - r) > 0.01: return False return True def _are_equal_within_rotation(self, expected, result_chunk): """ Checks that two lists of expected and result are equal within a rotation and a small error. Returns true if they are equal and False otherwise. """ rotation_deque = deque(result_chunk) for rotation in range(3): # triangles require at most 3 rotations rotation_deque.rotate(4) # because it has 4 components. result = list(rotation_deque)[:2] # we only test x and y if self._are_equal(expected, result): return True return False def check(self, expected, result, dimensions): """ Asserts that the result is equivalent to the expected result. """ if len(expected) != len(result) * dimensions / 4: self.fail('Incorrect number of vertices in feedback array: ' 'expected: %d, obtained: %d' % (len(expected), len(result) * dimensions / 4)) # there are two factors here: # 1. there are several triangles and their out-order can be different from in-order. # 2. in each triangle, the out-order of the vertices can be a rotation from its in-order. # to tackle 1: # we divide the result and the expected in chunks, each representing one triangle, # and we compare each triangle individually. # to tackle 2: # within each triangle, we cycle the vertices list and check if any rotation matches the expected. # for each triangle in the expected for e_chunk in chunks(expected, dimensions): expected_chunk = e_chunk[0:2] # we only test x and y # for each triangle in the result (tackling 1.) # notice that result always has 4 dimensions: (x, y, z, z-buffer). was_found = False for result_chunk in chunks(result, 3*4): # here we tackle 2. if self._are_equal_within_rotation(expected_chunk, result_chunk): was_found = True break # we assert that every triangle must be matched. self.assertTrue(was_found) @abstractmethod def get_feedback(self, data): pass def get_data(self, data, _): """ Used for pos-processing of the expected result. See subclass. """ return data 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 = self.get_feedback(data) self.check(self.get_data(v_data, n_v), vertices, n_v) if c_fmt: self.check(self.get_data(c_data, n_c), colors, n_c) if t_fmt: self.check(self.get_data(t_data, n_t), tex_coords, n_t) def test_v2f(self): self.generic_test('v2f', self.v2f_data) def test_v3f(self): self.generic_test('v3f', self.v3f_data) def test_v2f_c3f(self): self.generic_test('v2f', self.v2f_data, 'c3f', self.c3f_data) def test_v2f_c4f(self): self.generic_test('v2f', self.v2f_data, 'c4f', self.c4f_data) def test_v3f_c3f(self): self.generic_test('v3f', self.v3f_data, 'c3f', self.c3f_data) def test_v3f_c4f(self): self.generic_test('v3f', self.v3f_data, 'c4f', self.c4f_data) def test_v2f_t2f(self): self.generic_test('v2f', self.v2f_data, None, None, 't2f', self.t2f_data) def test_v3f_c3f_t2f(self): self.generic_test('v3f', self.v3f_data, 'c3f', self.c3f_data, 't2f', self.t2f_data) def test_v3f_c3f_t3f(self): self.generic_test('v3f', self.v3f_data, 'c3f', self.c3f_data, 't3f', self.t3f_data) def test_v3f_c4f_t4f(self): self.generic_test('v3f', self.v3f_data, 'c4f', self.c4f_data, 't4f', self.t4f_data) class GraphicsIndexedGenericTestCase(GraphicsGenericTestCase): """ A generic test for asserting vertices positions using openGL Feedback Buffer and indexed data. It has one abstract method that the subclass must overwrite. """ def setUp(self): GraphicsGenericTestCase.setUp(self) # we use half of the data so we repeat vertices. self.index_data = range(self.n_vertices//2) * 2 random.seed(1) random.shuffle(self.index_data) def get_data(self, data, dimensions): """ Reorders data according to the indexing. """ ordered = [] for i in self.index_data: ordered.extend(data[i * dimensions:(i+1)*dimensions]) return ordered
Python
#!/usr/bin/env python '''Test that audio playback works. You should hear white noise (static) for 0.5 seconds. The test will exit immediately after. You may want to turn down the volume of your speakers. ''' import unittest from pyglet import media from pyglet.media import procedural class TEST_CASE(unittest.TestCase): def test_method(self): source = procedural.WhiteNoise(0.5) player = media.Player() player.pause() player.queue(source) while player.source: player.dispatch_events() player.play() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that audio playback works. You should hear white noise (static) for 0.5 seconds. The test will exit immediately after. You may want to turn down the volume of your speakers. ''' import unittest from pyglet import media from pyglet.media import procedural class TEST_CASE(unittest.TestCase): def test_method(self): source = procedural.WhiteNoise(0.5) source = media.StaticSource(source) source = media.StaticSource(source) player = media.Player() player.queue(source) player.play() while player.source: player.dispatch_events() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that audio playback works. You should hear white noise (static) for 0.5 seconds. The test will exit immediately after. You may want to turn down the volume of your speakers. ''' import unittest from pyglet import media from pyglet.media import procedural class TEST_CASE(unittest.TestCase): def test_method(self): source = procedural.WhiteNoise(0.5) player = media.Player() player.play() player.queue(source) while player.source: player.dispatch_events() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that audio playback works. You should hear white noise (static) for 0.25 seconds, then a 0.5 second pause then another 0.25 seconds of noise. The test will exit immediately after. You may want to turn down the volume of your speakers. ''' import unittest import time from pyglet import media from pyglet.media import procedural class TEST_CASE(unittest.TestCase): def test_method(self): source = procedural.WhiteNoise(0.5) player = media.Player() player.queue(source) player.play() start_time = time.time() stage = 0 while player.source: if stage == 0 and time.time() - start_time > 0.25: player.pause() stage = 1 if stage == 1 and time.time() - start_time > 0.75: player.play() stage = 2 player.dispatch_events() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that audio playback works. You should hear white noise (static) for 0.5 seconds. The test will exit immediately after. You may want to turn down the volume of your speakers. ''' import unittest from pyglet import media from pyglet.media import procedural class TEST_CASE(unittest.TestCase): def test_method(self): source = procedural.WhiteNoise(0.5) player = media.Player() player.queue(source) player.play() while player.source: player.dispatch_events() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that audio playback works. You should hear a tone at 440Hz (A above middle C) for 1.0 seconds. The test will exit immediately after. You may want to turn down the volume of your speakers. ''' import unittest from pyglet import media from pyglet.media import procedural class TEST_CASE(unittest.TestCase): def test_method(self): source1 = procedural.Sine(0.5) source2 = procedural.Sine(0.5) player = media.Player() player.queue(source1) player.queue(source2) player.play() while player.source: player.dispatch_events() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # $Id:$ import os import sys import unittest from pyglet.gl import * from pyglet import image from pyglet import resource from pyglet import window __noninteractive = True # Test image is laid out # M R # B G # In this test the image is sampled at four points from top-right clockwise: # R G B M (red, green, blue, magenta) class TestCase(unittest.TestCase): def setUp(self): self.w = window.Window(width=10, height=10) self.w.dispatch_events() resource.path.append('@' + __name__) resource.reindex() def tearDown(self): self.w.close() def check(self, img, colors): glClear(GL_COLOR_BUFFER_BIT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) img.blit(img.anchor_x, img.anchor_y) buffer = image.get_buffer_manager().get_color_buffer().get_image_data() bytes = buffer.get_data('RGBA', buffer.width * 4) def sample(x, y): i = y * buffer.pitch + x * len(buffer.format) r, g, b, _ = bytes[i:i+len(buffer.format)] if type(r) is str: r, g, b = map(ord, (r, g, b)) return { (255, 0, 0): 'r', (0, 255, 0): 'g', (0, 0, 255): 'b', (255, 0, 255): 'm'}.get((r, g, b), 'x') samples = ''.join([ sample(3, 3), sample(3, 0), sample(0, 0), sample(0, 3)]) self.assertTrue(samples == colors, samples) def test0(self): self.check(resource.image('rgbm.png'), 'rgbm') def test2(self): self.check(resource.image('rgbm.png', flip_x=True), 'mbgr') def test3(self): self.check(resource.image('rgbm.png', flip_y=True), 'grmb') def test4(self): self.check(resource.image('rgbm.png', flip_x=True, flip_y=True), 'bmrg') def test5(self): self.check(resource.image('rgbm.png', rotate=90), 'mrgb') def test5a(self): self.check(resource.image('rgbm.png', rotate=-270), 'mrgb') def test6(self): self.check(resource.image('rgbm.png', rotate=180), 'bmrg') def test6a(self): self.check(resource.image('rgbm.png', rotate=-180), 'bmrg') def test7(self): self.check(resource.image('rgbm.png', rotate=270), 'gbmr') def test7a(self): self.check(resource.image('rgbm.png', rotate=-90), 'gbmr') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' __noninteractive = True ''' Layout: . (script home) file.txt F1 dir1/ file.txt F2 dir1/ file.txt F3 res.zip/ file.txt F7 dir1/ file.txt F8 dir1/ file.txt F9 dir2/ file.txt F6 ''' import os import sys import unittest from pyglet import resource from pyglet.compat import asbytes class TestCase(unittest.TestCase): def setUp(self): self.script_home = os.path.dirname(__file__) def check(self, path, result): self.check_file(path, 'file.txt', result) def check_file(self, path, file, result): loader = resource.Loader(path, script_home=self.script_home) self.assertTrue(loader.file(file).read() == asbytes('%s\n' % result)) def checkFail(self, path): loader = resource.Loader(path, script_home=self.script_home) self.assertRaises(resource.ResourceNotFoundException, loader.file, 'file.txt') def test1(self): self.check(None, 'F1') def test2(self): self.check('', 'F1') def test2a(self): self.check('.', 'F1') def test2b(self): self.checkFail(()) def test2c(self): self.checkFail('foo') def test2d(self): self.checkFail(['foo']) def test2e(self): self.check(['foo', '.'], 'F1') def test3(self): self.check(['.', 'dir1'], 'F1') def test4(self): self.check(['dir1'], 'F2') def test5(self): self.check(['dir1', '.'], 'F2') def test6(self): self.check(['dir1/dir1'], 'F3') def test7(self): self.check(['dir1', 'dir1/dir1'], 'F2') def test8(self): self.check(['dir1/dir1', 'dir1'], 'F3') def test9(self): self.check('dir1/res.zip', 'F7') def test9a(self): self.check('dir1/res.zip/', 'F7') def test10(self): self.check('dir1/res.zip/dir1', 'F8') def test10a(self): self.check('dir1/res.zip/dir1/', 'F8') def test11(self): self.check(['dir1/res.zip/dir1', 'dir1/res.zip'], 'F8') def test12(self): self.check(['dir1/res.zip', 'dir1/res.zip/dir1'], 'F7') def test12a(self): self.check(['dir1/res.zip', 'dir1/res.zip/dir1/dir1'], 'F7') def test12b(self): self.check(['dir1/res.zip/dir1/dir1/', 'dir1/res.zip/dir1'], 'F9') def test12c(self): self.check(['dir1/res.zip/dir1/dir1', 'dir1/res.zip/dir1'], 'F9') def test13(self): self.check(['dir1', 'dir2'], 'F2') def test14(self): self.check(['dir2', 'dir1'], 'F6') # path tests def test15(self): self.check_file([''], 'dir1/file.txt', 'F2') def test15a(self): self.check_file([''], 'dir1/dir1/file.txt', 'F3') def test15b(self): self.check_file(['dir1'], 'dir1/file.txt', 'F3') def test15c(self): self.check_file([''], 'dir2/file.txt', 'F6') def test15d(self): self.check_file(['.'], 'dir2/file.txt', 'F6') # zip path tests def test16(self): self.check_file(['dir1/res.zip'], 'dir1/file.txt', 'F8') def test16a(self): self.check_file(['dir1/res.zip/'], 'dir1/file.txt', 'F8') def test16a(self): self.check_file(['dir1/res.zip/'], 'dir1/dir1/file.txt', 'F9') def test16b(self): self.check_file(['dir1/res.zip/dir1'], 'dir1/file.txt', 'F9') def test16c(self): self.check_file(['dir1/res.zip/dir1/'], 'dir1/file.txt', 'F9') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that all public modules are accessible after importing just 'pyglet'. This _must_ be the first test run. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $' import unittest import pyglet __noninteractive = True modules = [ 'app', 'clock', 'event', 'font', 'font.base', 'gl', 'gl.gl_info', 'gl.glu_info', 'graphics', 'graphics.allocation', 'graphics.vertexattribute', 'graphics.vertexbuffer', 'graphics.vertexdomain', 'image', 'image.atlas', 'media', 'resource', 'sprite', 'text', 'text.caret', 'text.document', 'text.layout', 'text.runlist', 'window', 'window.event', 'window.key', 'window.mouse', ] def add_module_tests(name, bases, dict): for module in modules: components = module.split('.') def create_test(components): def test_module(self): top = pyglet for component in components: self.assertTrue(hasattr(top, component), 'Cannot access "%s" in "%s"' % (component, top.__name__)) top = getattr(top, component) return test_module test_module = create_test(components) test_name = 'test_%s' % module.replace('.', '_') test_module.__name__ = test_name dict[test_name] = test_module return type.__new__(type, name, bases, dict) class TEST_CASE(unittest.TestCase): __metaclass__ = add_module_tests if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python '''Test that the event loop can do timing. The test will display a series of intervals, iterations and sleep times. It should then display an incrementing number up to 2x the number of iterations, at a rate determined by the interval. ''' import sys import unittest import pyglet __noninteractive = True if sys.platform in ('win32', 'cygwin'): from time import clock as time else: from time import time from time import sleep class EVENT_LOOP(unittest.TestCase): def t_scheduled(self, interval, iterations, sleep_time=0): print 'Test interval=%s, iterations=%s, sleep=%s' % (interval, iterations, sleep_time) warmup_iterations = iterations self.last_t = 0. self.timer_count = 0 def f(dt): sys.stdout.write('%s\r' % self.timer_count) sys.stdout.flush() t = time() self.timer_count += 1 tc = self.timer_count if tc > warmup_iterations: self.assertAlmostEqual(dt, interval, places=2) self.assertAlmostEqual(t - self.last_t, interval, places=2) self.last_t = t if self.timer_count > iterations + warmup_iterations: pyglet.app.exit() if sleep_time: sleep(sleep_time) pyglet.clock.schedule_interval(f, interval) try: pyglet.app.run() finally: pyglet.clock.unschedule(f) print def test_1_5(self): self.t_scheduled(1, 5, 0) def test_1_5_d5(self): self.t_scheduled(1, 5, 0.5) def test_d1_50(self): self.t_scheduled(.1, 50) def test_d1_50_d05(self): self.t_scheduled(.1, 50, 0.05) def test_d05_50(self): self.t_scheduled(.05, 50) def test_d05_50_d03(self): self.t_scheduled(.05, 50, 0.03) def test_d02_50(self): self.t_scheduled(.02, 50) def test_d01_50(self): self.t_scheduled(.01, 50) if __name__ == '__main__': if pyglet.version != '1.2dev': print 'Wrong version of pyglet imported; please check your PYTHONPATH' else: unittest.main()
Python
#!/usr/bin/env python '''Test that text will not wrap when its width is set to its calculated width. You should be able to clearly see "TEST TEST" on a single line (not two) and "SPAM SPAM SPAM" over two lines, not three. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from . import base_text from pyglet import font class TEST_WRAP_INVARIANT(base_text.TextTestBase): font_name = '' text = 'TEST TEST' def render(self): fnt = font.load('', 24) self.label1 = font.Text(fnt, 'TEST TEST', 10, 150) self.label1.width = self.label1.width + 1 self.label2 = font.Text(fnt, 'SPAM SPAM\nSPAM', 10, 50) self.label2.width = self.label2.width + 1 def draw(self): self.label1.draw() self.label2.draw() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that font.have_font() function works correctly.''' import unittest from pyglet import font __noninteractive = True class HAVE_FONT(unittest.TestCase): def test_have_font(self): self.assertTrue(font.have_font('Arial')) self.assertFalse(font.have_font('missing-font-name')) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that rendering of bullet glyphs works. You should see 5 bullet glyphs rendered in the bottom-left of the window. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import font from . import base_text class TEST_HALIGN(base_text.TextTestBase): font_name = '' font_size = 60 text = u'\u2022'*5 if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that a font likely to be installed on the computer can be loaded and displayed correctly. One window will open, it should show "Quickly brown fox" at 24pt using: * "Helvetica" on Mac OS X * "Arial" on Windows ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import sys from . import base_text if sys.platform == 'darwin': font_name = 'Helvetica' elif sys.platform in ('win32', 'cygwin'): font_name = 'Arial' else: font_name = 'Arial' class TEST_SYSTEM(base_text.TextTestBase): font_name = font_name font_size = 24 if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that font.Text horizontal alignment works. Three labels will be rendered aligned left, center and right. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import font from . import base_text class TEST_HALIGN(base_text.TextTestBase): font_name = '' def render(self): fnt = font.load('', self.font_size) h = fnt.ascent - fnt.descent w = self.window.width self.labels = [ font.Text(fnt, 'LEFT', 0, 10 + 3 * h, width=w, halign='left'), font.Text(fnt, 'CENTER', 0, 10 + 2 * h, width=w, halign='center'), font.Text(fnt, 'RIGHT', 0, 10 + h, width=w, halign='right'), ] def on_resize(self, width, height): for label in self.labels: label.width = width def draw(self): for label in self.labels: label.draw() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that font colour is applied correctly. Default font should appear blue. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from . import base_text from pyglet import font class TEST_COLOR(base_text.TextTestBase): def render(self): fnt = font.load(self.font_name, self.font_size) self.label = font.Text(fnt, self.text, 10, 10, color=(0, 0, 1, 1)) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that a specific DPI can be set to render the text with. Some text in Action Man font will be displayed. A green box should exactly bound the top and bottom of the text. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import os import unittest from pyglet.gl import * from pyglet import font from . import base_text base_path = os.path.dirname(__file__) class TEST_ADD_FONT(base_text.TextTestBase): font_name = 'Action Man' def render(self): font.add_file(os.path.join(base_path, 'action_man.ttf')) # Hard-code 16-pt at 100 DPI, and hard-code the pixel coordinates # we see that font at when DPI-specified rendering is correct. fnt = font.load('Action Man', 16, dpi=120) self.text = font.Text(fnt, 'The DPI is 120', 10, 10) def draw(self): self.text.draw() x1 = self.text.x x2 = self.text.x + self.text.width y1 = 9 y2 = 27 glPushAttrib(GL_CURRENT_BIT) glColor3f(0, 1, 0) glBegin(GL_LINE_LOOP) glVertex2f(x1, y1) glVertex2f(x2, y1) glVertex2f(x2, y2) glVertex2f(x1, y2) glEnd() glPopAttrib() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Base class for text tests. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import sys from pyglet import gl from pyglet import font from pyglet.window import Window from pyglet.window.event import key from tests.regression import ImageRegressionTestCase class TextTestBase(ImageRegressionTestCase): font_name = '' font_size = 24 text = 'Quickly brown fox' window_size = 200, 200 def on_key_press(self, symbol, modifiers): if symbol in (key.ENTER, key.ESCAPE): self.window.dispatch_event('on_close') def on_expose(self): gl.glClearColor(0.5, 0, 0, 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glLoadIdentity() self.draw() self.window.flip() if self.capture_regression_image(): self.window.exit_handler.has_exit = True def render(self): fnt = font.load(self.font_name, self.font_size) self.label = font.Text(fnt, self.text, 10, 10) def draw(self): self.label.draw() def test_main(self): width, height = self.window_size self.window = w = Window(width, height, visible=False, resizable=True) w.push_handlers(self) self.render() w.set_visible() while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that font.Text vertical alignment works. Four labels will be aligned top, center, baseline and bottom. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import gl from pyglet import font from . import base_text class TEST_VALIGN(base_text.TextTestBase): font_name = '' window_size = 600, 200 def render(self): fnt = font.load('', self.font_size) h = fnt.ascent - fnt.descent w = self.window.width self.labels = [] x = 0 for align in 'top center baseline bottom'.split(): label = align.upper() + 'y' self.labels.append(font.Text(fnt, label, x, 50, valign=align)) x += self.labels[-1].width def draw(self): gl.glColor3f(1, 1, 1) gl.glBegin(gl.GL_LINES) gl.glVertex2f(0, 50) gl.glVertex2f(self.window.width, 50) gl.glEnd() for label in self.labels: label.draw() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that a font distributed with the application can be displayed. Four lines of text should be displayed, each in a different variant (bold/italic/regular) of Action Man at 24pt. The Action Man fonts are included in the test directory (tests/font) as action_man*.ttf. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import os import unittest from pyglet import font from . import base_text base_path = os.path.dirname(__file__) class TEST_ADD_FONT(base_text.TextTestBase): font_name = 'Action Man' def render(self): font.add_file(os.path.join(base_path, 'action_man.ttf')) font.add_file(os.path.join(base_path, 'action_man_bold.ttf')) font.add_file(os.path.join(base_path, 'action_man_italic.ttf')) font.add_file(os.path.join(base_path, 'action_man_bold_italic.ttf')) fnt = font.load('Action Man', self.font_size) fnt_b = font.load('Action Man', self.font_size, bold=True) fnt_i = font.load('Action Man', self.font_size, italic=True) fnt_bi = font.load('Action Man', self.font_size, bold=True, italic=True) h = fnt.ascent - fnt.descent self.labels = [ font.Text(fnt, 'Action Man', 10, 10 + 3 * h), font.Text(fnt_i, 'Action Man Italic', 10, 10 + 2 * h), font.Text(fnt_b, 'Action Man Bold', 10, 10 + h), font.Text(fnt_bi, 'Action Man Bold Italic', 10, 10) ] def draw(self): for label in self.labels: label.draw() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that font.Text alignment works with multiple lines. Three labels will be rendered at the top-left, center and bottom-right of the window. Resize the window to ensure the alignment is as specified. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import font from . import base_text class TEST_ALIGN_MULTILINE(base_text.TextTestBase): font_name = '' window_size = 400, 500 def render(self): fnt = font.load(self.font_name, self.font_size) w = self.window.width h = self.window.height self.labels = [ font.Text(fnt, 'This text is top-left aligned with several lines.', 0, h, width=w, halign='left', valign='top'), font.Text(fnt, 'This text is centered in the middle.', 0, h//2, width=w, halign='center', valign='center'), font.Text(fnt, 'This text is aligned to the bottom-right of the window.', 0, 0, width=w, halign='right', valign='bottom'), ] def on_resize(self, width, height): for label in self.labels: label.width = width self.labels[0].y = height self.labels[1].y = height // 2 def draw(self): for label in self.labels: label.draw() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that a font with no name given still renders using some sort of default system font. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from . import base_text class TEST_DEFAULT(base_text.TextTestBase): font_name = '' if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that font colour is applied correctly. Default font should appear at 0.1 opacity (faint white) ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from . import base_text from pyglet import font class TEST_COLOR_BLEND(base_text.TextTestBase): def render(self): fnt = font.load(self.font_name, self.font_size) self.label = font.Text(fnt, self.text, 10, 10, color=(1, 1, 1, 0.1)) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that the horizontal font metrics are calculated correctly. Some text in various fonts will be displayed. Green vertical lines mark the left edge of the text. Blue vertical lines mark the right edge of the text. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import os import unittest from pyglet.gl import * from pyglet import font from . import base_text base_path = os.path.dirname(__file__) class TEST_HORIZONTAL_METRICS(base_text.TextTestBase): window_size = 400, 250 def render(self): font.add_file(os.path.join(base_path, 'action_man.ttf')) fnt1 = font.load('Action Man', 16) fnt2 = font.load('Arial', 16) fnt3 = font.load('Times New Roman', 16) h = fnt3.ascent - fnt3.descent + 10 self.texts = [ font.Text(fnt1, 'Action Man', 10, h * 1), font.Text(fnt1, 'Action Man longer test with more words', 10, h*2), font.Text(fnt2, 'Arial', 10, h * 3), font.Text(fnt2, 'Arial longer test with more words', 10, h*4), font.Text(fnt3, 'Times New Roman', 10, h * 5), font.Text(fnt3, 'Times New Roman longer test with more words', 10, h*6), ] def draw(self): glPushAttrib(GL_CURRENT_BIT) for text in self.texts: text.draw() glBegin(GL_LINES) glColor3f(0, 1, 0) glVertex2f(text.x, text.y + text.font.descent) glVertex2f(text.x, text.y + text.font.ascent) glColor3f(0, 0, 1) glVertex2f(text.x + text.width, text.y + text.font.descent) glVertex2f(text.x + text.width, text.y + text.font.ascent) glEnd() glPopAttrib() 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